I am implementing the Conduit spec. For JWT, it requires the header for JWT tokens to be:
Authorization: Token jwt.token.here
With Microsoft.AspNetCore.Authentication.JwtBearer
, the default header is "Authorization: Bearer {token goes here}". I've added an OnMessageReceived event that replaces the default "Bearer" with "Token".
However, for Swashbuckle, when adding a security scheme to Swashbuckle, I can't figure out a way to change the headers it generates to use "Token" instead of "Bearer". So, while I can fall back to Postman to make API requests, I'd really like to use Swashbuckle/OpenAPI/SwaggerUI instead.
Is there a setting or some way to override its use of "Bearer"? Or is this hardcoded and a new feature would need to be added to support that? Below is what I've tried, and it's not working. It falls back to "Bearer". If I set Scheme
to "Token", it causes a runtime error.
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
// Configure JWT authentication
var securityScheme = new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "JWT Authorization header using the Bearer scheme",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
BearerFormat = "JWT"
};
c.AddSecurityDefinition("Token", securityScheme);
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Token"
}
},
Array.Empty<string>()
}
});
});
Update:
Here's a screenshot of the prompt I get when I click the "Authorize🔓" button in the Swagger UI:
Note that it says "Token", probably from AddSecurityDefinition
or AddSecurityRequirement
, but it actually generates "Bearer". After I enter a value and click:
The OpenAPI specification does allow you to define alternative schemes for the Authorization header, though technically they should be well-known schemes registered here: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml. "Token" is not in the list.
That said, you can probably extend Swashbuckle to output it. I believe the method would be to use DocumentFilter<T>()
on the SwaggerGenOptions
when registering Swashbuckle on your DI container. You can then add a filter that mutates the generated Swagger spec immediately after it is generated but before it is consumed. You should be able to adjust the security schemes, something like this:
private class DocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Components.SecuritySchemes["SchemeName"].Scheme = "Token";
}
}