在 ASP.NET Core 2.2 中使用 nswag 设置 Bearer Token

Set Bearer Token with nswag in ASP.NET Core 2.2

我有一个 ASP.NET Core 2.2 Web Api 并且我使用 nswag 添加了 swagger 支持。 使用生成访问令牌的本地 IdentityServer4 保护网络 api。

我在 header 中找到了添加授权按钮和表单并设置不记名令牌的代码。并且有效!

public void ConfigureServices(IServiceCollection services)
{
//...   
            services.AddSwaggerDocument(config =>
            {
                config.DocumentName = "OpenAPI 2";
                config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT Token"));
                config.AddSecurity("JWT Token", Enumerable.Empty<string>(),
                    new OpenApiSecurityScheme()
                    {
                        Type = OpenApiSecuritySchemeType.ApiKey,
                        Name = "Authorization",
                        In = OpenApiSecurityApiKeyLocation.Header,
                        Description = "Copy this into the value field: Bearer {token}"
                    }
                );
            });
//...
}

swagger页面中的按钮

不记名令牌 copy/paste 的表格

我正在寻找一种无需 copy/paste 即可自动执行流程和设置访问令牌的方法。

是否可以设置 nswag 来执行此操作?

您可以在生成器和 Swagger 中启用身份验证 UI。要添加 OAuth2 身份验证 (OpenAPI 3),在网络中 api :

services.AddOpenApiDocument(document =>
    {
        document.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
        {
            Type = OpenApiSecuritySchemeType.OAuth2,
            Description = "My Authentication",
            Flow = OpenApiOAuth2Flow.Implicit,
            Flows = new OpenApiOAuthFlows()
            {
                Implicit = new OpenApiOAuthFlow()
                {
                    Scopes = new Dictionary<string, string>
                    {
                        {"api1", "My API"}

                    },
                    TokenUrl = "http://localhost:5000/connect/token",
                    AuthorizationUrl = "http://localhost:5000/connect/authorize",

                },
            }
        });

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

配置:

app.UseOpenApi();
app.UseSwaggerUi3(settings =>
{
    settings.OAuth2Client = new OAuth2ClientSettings
    {
        ClientId = "demo_api_swagger",

        AppName = "Demo API - Swagger",

    };
});

在身份服务器 4 中,注册 api :

public static IEnumerable<ApiResource> GetApis()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API")
    };
}

而客户:

new Client {
    ClientId = "demo_api_swagger",
    ClientName = "Swagger UI for demo_api",
    AllowedGrantTypes = GrantTypes.Implicit,
    AllowAccessTokensViaBrowser = true,
    RedirectUris = {"https://localhost:44304/swagger/oauth2-redirect.html"},
    AllowedScopes = { "api1" }
},

点击UI中的Authorize按钮后,您可以使用IDS4进行身份验证并获得api的访问令牌,然后令牌将在[=时自动附加到授权请求头中25=] 请求。