Swagger 无法向 Azure AD B2C 进行身份验证

Dan*_*ook 3 swagger swagger-ui azure-ad-b2c

我有一个带有 Swagger 的 Web API 和一个 Azure AD B2C 租户。

React 应用程序能够从 B2C 获取令牌,例如:

          msalInstance.loginRedirect({
            scopes: ["openid", "offline_access", process.env.MY_CLIENT_ID],
          });
Run Code Online (Sandbox Code Playgroud)

然而 Swagger Authorize 函数返回AADB2C90205This+application+does+not+have+sufficient+permissions+against+this+web+resource+to+perform+the+operation

AddSwagger中的代码是Startup.cs

        private void AddSwagger(IServiceCollection services)
        {
            var azureAdB2C = new AzureAdB2CSettings();
            this.Configuration.Bind("AzureAdB2C", azureAdB2C);
            var authUrl = $"https://{azureAdB2C.TenantName}.b2clogin.com/{azureAdB2C.TenantName}.onmicrosoft.com/{azureAdB2C.SignUpSignInPolicyId}/oauth2/v2.0";

            services.AddOpenApiDocument(
                document =>
                    {
                        document.AddSecurity(
                            "bearer",
                            Enumerable.Empty<string>(),
                            new OpenApiSecurityScheme
                                {
                                    Type = OpenApiSecuritySchemeType.OAuth2,
                                    Description = "Azure AAD Authentication",
                                    
                                    Flow = OpenApiOAuth2Flow.Implicit,
                                    Flows = new OpenApiOAuthFlows()
                                                {
                                                    Implicit = new OpenApiOAuthFlow()
                                                                   {
                                                                       Scopes = new Dictionary<string, string>
                                                                                    {
                                                                                        {
                                                                                            $"{azureAdB2C.Instance}/{azureAdB2C.ClientId}/user_impersonation",
                                                                                            "Access Application"
                                                                                        },
                                                                                        {
                                                                                            $"{azureAdB2C.Instance}/{azureAdB2C.ClientId}/access_as_user",
                                                                                            "Access as User"
                                                                                        },
                                                                                    },
                                                                       AuthorizationUrl = $"{authUrl}/authorize",
                                                                       TokenUrl = $"{authUrl}/token",
                                                    },
                                                },
                                });

                        document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer"));
                    });
        }
Run Code Online (Sandbox Code Playgroud)

B2C配置如下:

在此输入图像描述

在此输入图像描述

我在这里遗漏了任何明显的东西吗?

Jim*_* Xu 8

如果您想调用Azure AD B2C投射的Web api,请参考以下步骤

A。在 Azure AD B2C 中注册 Web api 应用程序 在此输入图像描述

b. 定义范围

C。在 Azure AD B2C 中注册 SPA 应用程序 在此输入图像描述

在此输入图像描述

d. 授予权限

e. 应用

  1. 包裹
Microsoft.AspNetCore.Authentication.AzureADB2C.UI
NSwag.AspNetCore
Run Code Online (Sandbox Code Playgroud)
  1. 应用程序设置.json
{
  "AzureAdB2C": {
    "Instance": "https://<>.b2clogin.com/tfp/",
    "ClientId": "<web api clinet id>",
    "Domain": "<>.onmicrosoft.com",
    "SignUpSignInPolicyId": "B2C_1_test"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Run Code Online (Sandbox Code Playgroud)
public void ConfigureServices(IServiceCollection services)
{
    // snip
      services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
                .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

    // Add security definition and scopes to document
    services.AddOpenApiDocument(document =>
    {
        document.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
        {
            Type = OpenApiSecuritySchemeType.OAuth2,
            Description = "B2C authentication",
            Flow = OpenApiOAuth2Flow.Implicit,
            Flows = new OpenApiOAuthFlows()
            {
                Implicit = new OpenApiOAuthFlow()
                {
                    Scopes = new Dictionary<string, string>
                        {
                            { "https://<b2c_tenant_name>.onmicrosoft.com/your-api/user_impersonation", "Access the api as the signed-in user" },
                            { "https://<b2c_tenant_name>.onmicrosoft.com/your-api/read", "Read access to the API"},
                            { "https://<b2c_tenant_name>.onmicrosoft.com/your-api/mystery_scope", "Let's find out together!"}
                        },
                    AuthorizationUrl = "https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/oauth2/v2.0/authorize?p=<policy_name>",
                    TokenUrl = "https://<b2c_tenant_name>.b2clogin.com/<b2c_tenant_name>.onmicrosoft.com/oauth2/v2.0/token?p=<policy_name>"
                },
            }
        });

        document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer"));
    });

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

            app.UseHttpsRedirection();

            app.UseRouting();

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

            app.UseOpenApi();
            app.UseSwaggerUi3(settings =>
            {
                settings.OAuth2Client = new OAuth2ClientSettings
                {
                    ClientId = "<spa client id>",
                    AppName = "swagger-ui-client"
                };
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    
Run Code Online (Sandbox Code Playgroud)

f.检验 在此输入图像描述 在此输入图像描述

欲了解更多详情,请参阅博客