Swagger没有显示’Authorize’图标

huangapple go评论90阅读模式
英文:

Swagger is not showing 'Authorize' icon

问题

我有一个使用Swagger的API项目。

我正在使用.NET Core Web API(版本6)。

没有授权,我无法测试我的端点。我可以使用POSTMAN,但更喜欢使用Swagger。

Swagger没有显示’Authorize’图标

英文:

I have an API Project which uses Swagger.

I am using .NET Core Web API (version 6)

Without Authorization, I can not test my end points. I can use POSTMAN but would prefer using Swagger.

Swagger没有显示’Authorize’图标

答案1

得分: 1

API项目添加Swashbuckle.AspNetCore包。为Program类添加以下配置:

builder.Services.AddSwaggerGen(option =>
{
    option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
    option.AddSecurityDefinition(
        "Bearer",
        new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Description = "请输入有效的令牌",
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            BearerFormat = "JWT",
            Scheme = "Bearer"
        }
    );
    option.AddSecurityRequirement(
        new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[] { }
            }
        }
    );
});

现在你可以在Swagger首页看到Authorize选项,如果你使用jwt令牌,授权将会生效。

更多信息请参考博客链接。

英文:

Add Swashbuckle.AspNetCore package to API project. Add the below configuration for to Program class

builder.Services.AddSwaggerGen(option =>
{
    option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
    option.AddSecurityDefinition(
        "Bearer",
        new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Description = "Please enter a valid token",
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            BearerFormat = "JWT",
            Scheme = "Bearer"
        }
    );
    option.AddSecurityRequirement(
        new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[] { }
            }
        }
    );
});

Now you can see the Authorize option on swagger home page and authorization works if you are using jwt tokens.

For more info refer this blog

huangapple
  • 本文由 发表于 2023年6月5日 21:55:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76407156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定