question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NSwag.AspNetCore SwaggerUI: how to add JWT authorization headers?

See original GitHub issue

Hello, I’m successfully running my AspNetCore WebAPI project with JWT authorization and MS API versioning, but can’t understand how to properly configure NSWag middleware to expose the “Authorization: Bearer” token, so to properly generate a c# client library using NSWag Studio.

I’m actually getting a timeout when opening my API project /swagger endpoint: it shows Swagger page, but then it stands waiting for it to show my api methods (fetching resource list). No errors appear on server, and the json can be loaded at its url. Can’t even tell if this problem is related with the authorization header not being correctly generated.

My Configure method contains:

[...]
 app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters,
                Events = new MyCustomJWTEventHandler()
            });

            // Swagger
            SwaggerUiSettings options = new SwaggerUiSettings();
            options.Description = "My API";
            options.Version = "1.0.0";
            options.Title = "My API";
            options.ValidateSpecification = true;

           // add Authorization header to Swagger UI
            options.OperationProcessors.Add(new OperationSecurityScopeProcessor("apiKey"));
            options.DocumentProcessors.Add(new SecurityDefinitionAppender("apiKey", new NSwag.SwaggerSecurityScheme()
            {
                Type = NSwag.SwaggerSecuritySchemeType.ApiKey,
                Name = "Authorization",
                In = NSwag.SwaggerSecurityApiKeyLocation.Header,
                Description = "Bearer token"
            }));

            app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, options);

            app.UseMvc(routes =>
            {
                routes.MapRoute("default", "{controller}/{action}/{id?}");
            });

The produced json contains a security node for each method, but I’m not sure this is correct - and NSWag studio does not add code to handle the authorization header to the generated client library.

"security": [
          {
            "apiKey": []
          }
        ]

Can anybody help me taking the right direction? 😚

Thanks for any help,

al.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:44 (18 by maintainers)

github_iconTop GitHub Comments

9reactions
renepapecommented, Feb 27, 2018

Any success adding JWT tokens from SwaggerUI? I can make it work in Angular 5 with the nwag generated JS client, but can’t figure out how to successfully tweak the SwaggerUI through UseWaggerUI3 in the .Net Core server side settings. To be more precise, SwaggerUI2 is able to add the apiKey token on the request retrieving swagger.json definition, but they are not added to the “try it out” functionality, i.e. in the curl commands.

My bad, I confused the name and the ApiKey type, this does work:

            app.UseSwaggerUi3(typeof(Startup).GetTypeInfo().Assembly, new SwaggerUi3Settings()
            {
                Title = "Some title",
                Version = "v1",
                Description = "Some description",
                DefaultEnumHandling = NJsonSchema.EnumHandling.Integer,
                AddMissingPathParameters = false,
                IsAspNetCore = true,
                 
                OperationProcessors =
                {
                    new  OperationSecurityScopeProcessor("JWT token")
                },
                
                DocumentProcessors = {
                    new SecurityDefinitionAppender("JWT token", new SwaggerSecurityScheme
                    {
                        Type = SwaggerSecuritySchemeType.ApiKey,
                        Name = "Authorization",
                        Description = "Copy 'Bearer ' + valid JWT token into field",
                        In = SwaggerSecurityApiKeyLocation.Header
                        
                    })
                }
            });

Pay attention to the reference between the “JWT token” name in OperationSecurityScopeProcessor and the name in SecurityDefinitionAppender.

7reactions
yetanotherchriscommented, Feb 23, 2019

Here’s how you get JWT tokens working with v12.0.14 (.NET Core 2.2):

services.AddMvc();
services.AddSwaggerDocument(document =>
{
    // Add an authenticate button to Swagger for JWT tokens
    document.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT"));
    document.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT", new SwaggerSecurityScheme
    {
        Type = SwaggerSecuritySchemeType.ApiKey,
        Name = "Authorization",
        In = SwaggerSecurityApiKeyLocation.Header,
        Description = "Type into the textbox: Bearer {your JWT token}. You can get a JWT token from /Authorization/Authenticate."
    }));

    // Post process the generated document
    document.PostProcess = d => d.Info.Title = "Hello world!";
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Set Bearer Token with nswag in ASP.NET Core 2.2
To add OAuth2 authentication (OpenAPI 3) , in web api : ... then token will automatically append to authorization request header when making ......
Read more >
NSwag JWT Token Authorization OpenAPI Documentation ...
In this post, we will see how to enable JWT (JSON web token) authentication in Swagger/OpenAPI documentation in ASP.NET Core API using NSwag...
Read more >
How to JWT Authenticate with Angular to an ASP.NET Core ...
This guide focuses on the key aspects. · Edit Startup.cs · Start NSwag Studio · Select the “Angular” template · Select “transformOptions” ·...
Read more >
Configuring Swagger in .Net 6 with JWT and API Key ...
Configuring Swashbuckle. First, we want to install Swashbuckle so go to your project and add the NuGet package: Swashbuckle.AspNetCore.
Read more >
Swashbuckle vs. NSwag in ASP.NET Core
Both Swashbuckle and NSwag support Swagger UI customization. ... Description = "JWT Authorization header using the Bearer scheme.",.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found