不记名令牌未包含在 SwaggerUI 中

时间:2020-12-29 17:52:22

标签: asp.net-core swagger-ui aspnetboilerplate

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

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

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

1 个答案:

答案 0 :(得分:5)

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

您没有在代码片段中完全显示这一点,但您必须执行如下操作才能配置 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。名称/ID "oauth" 只是安全定义的标识名称。

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