如何让SwaggerUI/Swashbuckle在针对Azure AD B2C进行授权后将正确的令牌发送到我的API?

4urapxun  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(105)

我正在尝试为我的应用程序实现Azure AD B2C,我想使用SwaggerUI进行一些测试。使用SwaggerUI和OAuth2进行身份验证,我登录到Azure AD B2C,并收到几个令牌作为回报。(我使用PKCE的授权代码流)

{
    "id_token": "<valid token>",
    "token_type": "Bearer",
    "not_before": 1702649151,
    "id_token_expires_in": 3600,
    "profile_info": "<valid token>",
    "scope": "openid",
    "refresh_token": "<valid token>",
    "refresh_token_expires_in": 86400
}

字符串
然而,当我尝试调用我的端点时,它们仍然不起作用。我可以从devtools中看到它没有在请求中正确发送令牌。它将“Authorization”-header设置为“Bearer undefined”。我已经测试了其他类似问题的几个解决方案,但它们不起作用。
这是我目前使用的安全需求:

private static OpenApiSecurityRequirement Oauth2SecurityRequirement =>
        new()
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "oauth2"
                    },
                    Scheme = "oauth2",
                    Name = "oauth2",
                    In = ParameterLocation.Header
                },
                new List<string>()
            }
        };


(yes我也尝试过以“bearer”作为scheme/id的变体,没有区别)
在我的AddSwaggerGen()配置中,我有以下内容

c.AddSecurityRequirement(Oauth2SecurityRequirement);
c.OperationFilter<GenericOperationFilter>(Oauth2SecurityRequirement);


其中cSwaggerGenOptions对象。
为了完整起见,这是操作过滤器:

public class GenericOperationFilter : IOperationFilter
{
    private readonly OpenApiSecurityRequirement _defaultRequirement;

    public GenericOperationFilter(OpenApiSecurityRequirement defaultRequirement)
    {
        _defaultRequirement = defaultRequirement;
    }
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any())
        {
            operation.Security = new List<OpenApiSecurityRequirement>
            {
                //same security requirment defined in AddSecurityRequirement
                _defaultRequirement
            };
        }
    }
}


所以总结一下

  • 针对Azure AD B2C进行身份验证有效,我获得了几个令牌
  • 我在SwaggerUI中的“授权”按钮和端点上都有一个小的锁图标
  • 当我尝试执行一个端点时,它不会在Authorization头中发送令牌。x1c 0d1x

/utility/claims只是一个将用户声明转储到json的端点)

7cwmlq89

7cwmlq891#

您是否在Program.cs文件中配置了安全定义?您应该有如下内容:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "API Title", Version = "v1" });
    c.AddSecurityDefinition("oauth2", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "Azure AD Login using OAuth2",
        Name = "AD Login",
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.OAuth2,
        Flows = new Microsoft.OpenApi.Models.OpenApiOAuthFlows
        {
            Implicit = new Microsoft.OpenApi.Models.OpenApiOAuthFlow()
            {
                AuthorizationUrl = new Uri("https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
                TokenUrl = new Uri("https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string>
                {
                    { "{scope}", "{name}" }
                }
            }
        }
    });
    c.OperationFilter<AuthRequirementOperationFilter>();
});

字符串
此外,您还需要确保将以下内容添加到Program.csapp部分

app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "API Name");
        c.OAuthClientId("{clientId});
        c.OAuthUsePkce();
        c.OAuthScopeSeparator(" ");
    });

相关问题