不记名令牌未包含在 SwaggerUI 中

Bearer token not getting included in SwaggerUI

我正在使用 AspNet Boilerplate 框架。我正在尝试在我的应用程序中通过 AzureAD 实施身份验证。我正在使用 ASP.NET core 3.0 并通过 swagger 测试我的应用程序。我看到令牌未包含在 header.

Startup.cs

的 ConfigureServices() 方法
                {
                    Type = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows()
                    {
                        Implicit = new OpenApiOAuthFlow()
                        {
                            TokenUrl = new Uri(My Token Url),
                            AuthorizationUrl = new Uri(My Authorization Url),
                            Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
                        }
                    }
                });

Startup.cs 的 Configure() 方法:

            {                
                options.OAuthClientId("22............");
                options.OAuthScopeSeparator(" ");
                
            });

如果我遗漏了什么,请告诉我。

您是否首先在进行身份验证时收到令牌?在我的回答中,我假设你是。

您并没有在您的代码段中完全显示,但您必须执行类似下面的操作来配置 Swagger 服务,对吗?

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc(...);

    options.AddSecurityDefinition(
        "oauth",
        new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Flows = new OpenApiOAuthFlows()
            {
                Implicit = new OpenApiOAuthFlow()
                {
                    TokenUrl = new Uri(My Token Url),
                    AuthorizationUrl = new Uri(My Authorization Url),
                    Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
                }
            }
    });
});

如果您是,只需在您的选项中添加安全要求,令牌将已包含在您的请求中:

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc(...);

    options.AddSecurityDefinition(
        "oauth",
        new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Flows = new OpenApiOAuthFlows()
            {
                Implicit = new OpenApiOAuthFlow()
                {
                    TokenUrl = new Uri(My Token Url),
                    AuthorizationUrl = new Uri(My Authorization Url),
                    Scopes = { { "api://357...../user_impersonation", "Access adt-service" } }
                }
            }
    });

    options.AddSecurityRequirement(
        new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                    Id = "oauth"
                }
            },
            oauthScopes.Keys.ToArray() // array with scopes' keys used above in the security definition
        }
    });
});

请注意 options.AddSecurityRequirement 的添加。 name/id "oauth" 只是安全定义的标识名称。

这些片段适用于 .net 5。我相信它们可能适用于 .net core 3