Passing JWT token in header from Swagger UI as Bearer token not working
Asked Answered
V

1

7

I am developing an ASP.NET Core Web API application. I am using Swagger and have applied JWT Bearer token authentication, but when I try to pass the Bearer token from Swagger UI, I am getting a 401 error.

My code:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
});

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Versioned API v1.0");
    c.SwaggerEndpoint("/swagger/v2/swagger.json", "Versioned API v2.0");

    c.DocExpansion(DocExpansion.None);
});

Generated token:

Generated token

Adding token in Swagger:

Adding token in Swagger

Unauthorized response:

Unauthorized response

Vitia answered 1/6, 2020 at 3:55 Comment(0)
M
9

You have specified SecurityScheme that supported by your API, but did not specify that its required. So, swagger will not going to pass that in header.For this you need to use OpenApiSecurityRequirement and within that specify Id of SecurityDefinition that you have used.

Here is a snippet that I have used.

var securityScheme = new OpenApiSecurityScheme()
{
    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
    Name = "Authorization",
    In = ParameterLocation.Header,
    Type = SecuritySchemeType.Http,
    Scheme = "bearer",
    BearerFormat = "JWT" // Optional
};

var securityRequirement = new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "bearerAuth"
            }
        },
        new string[] {}
    }
};

options.AddSecurityDefinition("bearerAuth", securityScheme);
options.AddSecurityRequirement(securityRequirement);
Marlette answered 12/6, 2020 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.