使用 Microsoft Identity 平台对 Blazor Server 中的 HubConnection 进行身份验证

问题描述 投票:0回答:1

我有一个 Blazor 服务器项目 (NET 8.0),其中设置了 Microsoft Identity 平台作为身份验证。现在我想用 HubConnection 实现聊天功能,如下所示:

protected override async Task OnInitializedAsync()
 {

    hubConnection = new HubConnectionBuilder().WithUrl(NavigationManager.ToAbsoluteUri("/chatservice"), options =>
     {
         options.AccessTokenProvider = async () =>
         {
             //where & how do I get an AccesToken from?
         };
     }).Build();


     hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
     {
         userMessages.Add(new UserMessage { Username = user, Message = message, isCurrentUser = user == usernameInput, DateSent = DateTime.Now });

         this.InvokeAsync(() => this.StateHasChanged());
     });

     await hubConnection.StartAsync();
 }

据我理解正确,我应该授权 HubConnection,但我不知道如何授权。

这就是我的 Program.cs 的样子:

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
        builder.Services.AddControllersWithViews()
            .AddMicrosoftIdentityUI();

        builder.Services.AddRazorPages();
        builder.Services.AddServerSideBlazor();
        builder.Services.AddSingleton<WeatherForecastService>();
        builder.Services.AddSingleton<ChatService>();

        builder.Services.AddSignalR().AddHubOptions<ChatService>(options =>
        {
            options.EnableDetailedErrors = true;
        });


        builder.Services.AddControllers();

        builder.Services.AddResponseCompression(options =>
        {
            options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/octet-stream" });
        });

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.MapBlazorHub();
        app.MapRazorPages();
        app.MapFallbackToPage("/_Host");

        app.MapHub<ChatService>("/chatservice");

        app.Run();
    }
}

本地一切正常。这是我将项目部署到 Azure 应用服务时遇到的错误:

错误:System.Net.Http.HttpRequestException:响应状态代码不表示成功:403(禁止)。

我在这里缺少什么?或者我是否必须以某种方式调整 Azure AD 中的应用程序注册?

提前谢谢您。

azure authentication azure-active-directory blazor-server-side asp.net-core-signalr
1个回答
0
投票

在 Blazor 服务器应用程序中,您可以使用

IHttpContextAccessor
achieve the access_token

@inject IHttpContextAccessor HttpContextAccessor

protected override async Task OnInitializedAsync()
{
    var accessToken = await GetAccessTokenAsync();

    hubConnection = new HubConnectionBuilder()
        .WithUrl(NavigationManager.ToAbsoluteUri("/chatservice"), options =>
        {
            options.AccessTokenProvider = () => Task.FromResult(accessToken);
        })
        .Build();

    // ...
}

private async Task<string> GetAccessTokenAsync()
{
    var httpContext = HttpContextAccessor.HttpContext;
    return await httpContext.GetTokenAsync("access_token");
}
© www.soinside.com 2019 - 2024. All rights reserved.