英文:
Swagger is not showing 'Authorize' icon
问题
我有一个使用Swagger的API项目。
我正在使用.NET Core Web API(版本6)。
没有授权,我无法测试我的端点。我可以使用POSTMAN,但更喜欢使用Swagger。
英文:
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.
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论