I am using Swagger in the Web API application. I have multiple versions of API, but I want to apply Bearer token option to version 2 only. There is no authentication for both versions. Here is 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,
});
});
Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.
In the Swagger Editor (the right pane), click the Authorize button, paste the sample API key shown in the description into the Value field (or use your own OpenWeatherMap API key), and click Authorize. Then click Close to close the authorization modal.
Another way of solving this, I assume you have a prefix for controller version v1 as prefix, then what you can do is:
public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
if (context.ApiDescription.RelativePath.StartsWith("v2"))
{
operation.Parameters.Add(new OpenApiParameter()
{
@In = ParameterLocation.Header,
Description =
"JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
});
}
}
}
and use it
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
This will only add Bearer field to v2 end points.
You can install NSwag.AspNetCore and add different options with different versions.
services.AddSwaggerDocument(a =>
{
a.DocumentName = "v1";
a.Version = "v1";
});
services.AddSwaggerDocument(a =>
{
a.DocumentName = "v2";
a.Version = "v2";
a.AddSecurity("bearer", new NSwag.OpenApiSecurityScheme
{
Description = "jwt",
In = NSwag.OpenApiSecurityApiKeyLocation.Header,
Type = NSwag.OpenApiSecuritySchemeType.ApiKey,
Scheme = "bearer"
});
});
app.UseOpenApi();
app.UseSwaggerUi3();
You can read more about it in Microsoft Docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With