Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Bearer Token with nswag in ASP.NET Core 2.2

I have an ASP.NET Core 2.2 Web Api and I added the swagger support with nswag. The web api is protected using a local IdentityServer4 that generates access tokens.

I found the code to add an authorization button and form and set the bearer token in the header. And it works!

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

Button in the swagger page

enter image description here

Form for copy/paste of the bearer token

enter image description here

I'm looking for a way to automate the flow and setting the access token without a copy/paste.

Is it possible to setup nswag to do this?

like image 668
Tonyc Avatar asked Nov 24 '19 20:11

Tonyc


1 Answers

You can enable authentication in generator and Swagger UI .To add OAuth2 authentication (OpenAPI 3) , in web 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"));
    }
);

Configure :

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

        AppName = "Demo API - Swagger",

    };
});

In identity server 4 , register the api :

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

And the client :

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

After clicking Authorize button in UI , you can authenticate with IDS4 and get api's access token , then token will automatically append to authorization request header when making api request .

like image 153
Nan Yu Avatar answered Sep 21 '22 19:09

Nan Yu