简体   繁体   中英

Add Bearer token option in swagger for particular version in web api

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,         
    });
});

在此处输入图像描述 在此处输入图像描述

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM