【问题标题】:Call Api from blazor and pass Auth token从 blazor 调用 Api 并传递 Auth 令牌
【发布时间】:2021-04-08 11:40:19
【问题描述】:

我有一个从 https://github.com/Azure-Samples/ms-identity-blazor-wasm/tree/main/WebApp-graph-user/Call-MSGraph 创建的 blazor webassembly 项目。

它基本上是在您将 .net 核心模板用于通过 AD B2B 使用身份验证的 Blazor 应用程序时创建的项目

dotnet new blazorwasm -au SingleOrg --client-id "{CLIENT ID}" -o {APP NAME} --tenant-id "{TENANT ID}"

然后,当用户登录时,我能够调用 graph.api。然后,我尝试使用 https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-3.1 中所述的身份验证调用我自己的 Api。

我用过

   builder.Services.AddHttpClient<ITestDataService, TestDataService>(
      client => client.BaseAddress = new Uri("https://localhost:44342/"))
        .AddHttpMessageHandler(x =>
        {
            var handler = x.GetRequiredService<AuthorizationMessageHandler>()
                .ConfigureHandler(new[] { "https://localhost:44342/" },
                    scopes: new[] { "https://graph.microsoft.com/User.Read" });

            return handler;
        });

我可以看到调用 Api 时附加了一个令牌,但身份验证失败 (401)。该 api 是从 B2B AD 的 Visual Studio 模板生成的,并使用也用于 Blazor 应用程序的配置。

这是它的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    services.AddControllers();
}


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

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

        app.UseCors(policy =>
            policy.WithOrigins("http://localhost:5000", 
                "https://localhost:5001")
            .AllowAnyMethod()
            .WithHeaders(HeaderNames.ContentType,
                HeaderNames.Authorization,
                "x-custom-header")
            .AllowCredentials());

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

你知道缺少什么吗?

完整的源代码在 github https://github.com/mathiasfritsch/blazor-calls-api

【问题讨论】:

    标签: azure-active-directory blazor-webassembly


    【解决方案1】:

    如果您想在一个 blazor webassembly 项目中调用 Microsoft graph 和您的自定义 API,我们可以通过创建不同的 HTTP 客户端来调用不同的 API 来实现它

    例如

    • 注册服务器 API 应用

      1. 为服务器 API 应用注册 AAD 应用
      2. Expose an API
    • 注册客户端应用

      1. 注册客户端应用
      2. Enable Implicit grant flow
      3. 添加 API 权限。 (图形 API 权限和 API 应用权限)
    • 配置 API 应用

    请在Startup.cs中添加以下代码

     public void ConfigureServices(IServiceCollection services)
     {
            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
            services.AddCors(options =>
                {
                    options.AddDefaultPolicy(
                        builder => builder.AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod());
                });
                   services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
                    .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    
                services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
                {
                    options.Authority += "/v2.0";
    
    
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        
                        ValidIssuers = new[] {
                          $"https://sts.windows.net/{Configuration["AzureAD:TenantId"]}/",
                          $"https://login.microsoftonline.com/{Configuration["AzureAD:TenantId"]}/v2.0"
    
                        },
                        RoleClaimType = "roles",
                        // The web API accepts as audiences both the Client ID (options.Audience) and api://{ClientID}.
                        ValidAudiences = new[]
                        {
                               options.Audience,
                               $"api://{options.Audience}"
                        }
    
                    };
    
                });
    ....
    }
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.OAuthClientId(Configuration["Swagger:ClientId"]);
                    c.OAuthScopeSeparator(" ");
                    c.OAuthAppName("Protected Api");
    
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                });
                app.UseHttpsRedirection();
    
                app.UseRouting();
                app.UseCors();
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
    
    • 配置客户端应用
    1. 为 Graph API 和自定义 API 创建自定义 AuthorizationMessageHandler
    // custom API
    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:44300/" },
                scopes: new[] { "the API app scope" });
        }
    }
    
    //Graph API
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
    
    public class GraphAuthorizationMessageHandler : AuthorizationMessageHandler
    {
        public GraphAuthorizationMessageHandler(IAccessTokenProvider provider,
            NavigationManager navigationManager)
            : base(provider, navigationManager)
        {
            ConfigureHandler(
                authorizedUrls: new[] { "https://graph.microsoft.com/" },
                scopes: new[] { "https://graph.microsoft.com/User.Read" });
        }
    }
    
    1. 将以下代码添加到 program.cs
    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.AddScoped<GraphAuthorizationMessageHandler>();
                // register HTTP client to call our own api
                builder.Services.AddHttpClient("MyAPI", client => client.BaseAddress = new Uri("https://localhost:44300/"))
                  .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
                // register HTTP client to call graph api
                builder.Services.AddHttpClient("GraphAPI", client => client.BaseAddress = new Uri("https://graph.microsoft.com/"))
                  .AddHttpMessageHandler<GraphAuthorizationMessageHandler>();
      
                builder.Services.AddMsalAuthentication(options =>
                {
                    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                    options.ProviderOptions.DefaultAccessTokenScopes.Add("<the API app scope>");
                    options.ProviderOptions.AdditionalScopesToConsent.Add("https://graph.microsoft.com/User.Read");
                });
    
                await builder.Build().RunAsync();
            }
        }
    
    1. 调用api
    @inject IHttpClientFactory _clientFactory
    
    var httpClient = _clientFactory.CreateClient("<the client name you register>");
    await apiClient.GetStringAsync("path");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 2022-08-24
      • 2018-07-18
      • 2018-10-23
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多