使用 azure AD B2C 进行 blazor web api 身份验证

Using azure AD B2C for blazor web api authentication

我一直在关注此文档以在 Blazor Web 应用程序中使用 Azure AD B2C 进行身份验证 https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/hosted-with-azure-active-directory-b2c?view=aspnetcore-5.0

按照本文档进行操作后,我们得到了一个包含服务器和客户端的解决方案,两者都 运行 在 https 端口 5001 上。现在,我想切换到使用外部 api,而不是端口 5001 上的 运行。

一切似乎都很好,当手动使用 blazor 检索到的访问令牌时,身份验证成功。但是 blazor 只会自动将身份验证 headers 附加到以 https://localhost:5001.

开头的请求

当我改为使用 https://localhost:5003 时,身份验证 header 留空。

我可以在我的 MsalAuthentication 的提供程序选项中添加一些东西,以便它可以将此访问令牌传递给我在 https://localhost:5003 上的 api 运行 吗?

builder.Services.AddHttpClient("{MyAssembly}.ServerAPI", client => client.BaseAddress = new Uri("https://localhost:5003"))
            .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("{MyAssembly}.ServerAPI"));

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://{myproject}.onmicrosoft.com/e3b857b7-df50-4633-ae02-df4d4b20e911/API.Access openid offline_access");
});

如果您想向不在应用的基本 URI 内的 URI 发出传出请求,您可以创建自定义 AuthorizationMessageHandler class 来实现它。详情请参考here

例如

创建自定义 AuthorizationMessageHandler class

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
    public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
        NavigationManager navigationManager)
        : base(provider, navigationManager)
    {
        ConfigureHandler(
            authorizedUrls: new[] { "https://localhost:44389/" },
            scopes: new[] { "https://<>.onmicrosoft.com/api/user_impersonation" });
    }
}

Program.cs中添加如下代码。

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace WebB2C
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");
          
            builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
            builder.Services.AddHttpClient("ServerAPI", client =>
              client.BaseAddress = new Uri("https://localhost:44389/"))
                    .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
             .CreateClient("ServerAPI"));

            builder.Services.AddMsalAuthentication(options =>
            {
                builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
                options.ProviderOptions.DefaultAccessTokenScopes.Add("https://<>.onmicrosoft.com/api/user_impersonation");
                options.ProviderOptions.DefaultAccessTokenScopes.Add("openid");
                options.ProviderOptions.DefaultAccessTokenScopes.Add("offline_access");
            });

            await builder.Build().RunAsync();
        }
    }
}