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

时间:2021-03-31 19:57:37

标签: swagger azure-ad-b2c swagger-ui

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

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

          msalInstance.loginRedirect({
            scopes: ["openid", "offline_access", process.env.MY_CLIENT_ID],
          });

但是 Swagger Authorize 函数返回 AADB2C90205, This+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"));
                    });
        }

B2C配置如下:

enter image description here

enter image description here

我在这里遗漏了什么明显的东西吗?

1 个答案:

答案 0 :(得分:0)

如果要调用 Azure AD B2C 投射的 web api,请参考以下步骤

一个。 Register web api application in Azure AD B2C enter image description here

B.定义范围

c. Register SPA application in Azure AD B2C enter image description here

enter image description here

d。 Grant Permissions

e.申请

  1. 包装
Microsoft.AspNetCore.Authentication.AzureADB2C.UI
NSwag.AspNetCore
  1. appsettings.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": "*"
}

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();
            });
        }
    

f.test enter image description here enter image description here

有关详细信息,请参阅blog