Authentication Swagger with JWT Bearer token
Update - The Swagger spec has changed. check answer by @nilay below for the correct solution.
I had the very same problem.
2 things are neccessary
You have to put
"bearer <token-here>"
like this. Putting only token will not work.
to get this to work in swagger 2.x, you need to accompany your scheme definition with a corresponding requirement to indicate that the scheme is applicable to all operations in your API:
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
Complete definition:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Some API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
});
I also face same issue, but I am using new version of Swagger which is based on OpenAPI. So, I have to use below snippet for same.
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"
};
var securityRequirement = new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "bearerAuth"
}
},
new string[] {}
}
};
options.AddSecurityDefinition("bearerAuth", securityScheme);
options.AddSecurityRequirement(securityRequirement);