[在ASP.NET Core 2.2中使用nswag设置承载令牌

问题描述 投票:0回答:1

我有一个ASP.NET Core 2.2 Web Api,并通过nswag添加了全面支持。Web api使用生成访问令牌的本地IdentityServer4保护。

我找到了添加授权按钮和表单的代码,并在标题中设置了承载令牌。而且有效!

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

招摇页面中的按钮

enter image description here

不记名令牌的复制/粘贴表格

enter image description here

我正在寻找一种自动化流程并设置访问令牌而无需复制/粘贴的方法。

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

swagger asp.net-core-webapi identityserver4 asp.net-core-2.2 nswag
1个回答
0
投票

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

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" }
},

在用户界面中单击Authorize按钮后,您可以通过IDS4进行身份验证并获取api的访问令牌,然后在进行api请求时,令牌将自动追加到授权请求标头中。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.