在ASP.NET Core的Swagger中使用JWT(授权:承载) [英] Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core
问题描述
我正在ASP.NET Core 1.0中创建REST api.我当时使用Swagger进行测试,但现在我为某些路由添加了JWT授权. (使用UseJwtBearerAuthentication
)
I'm creating a REST api in ASP.NET Core 1.0. I was using Swagger to test but now I added JWT authorization for some routes. (with UseJwtBearerAuthentication
)
是否可以修改Swagger请求的标头,以便可以测试具有[Authorize]
属性的路由?
Is it possible to modify the header of the Swagger requests so the routes with the [Authorize]
attribute can be tested?
推荐答案
我也遇到了同样的问题,并在此博客文章中找到了可行的解决方案: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField
I struggled with the same problem and found a working solution in this blogpost: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField
归结为将其添加到您的配置选项中
It comes down to adding this in your configurationoptions
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
以及operationfilter的代码
and the code for the operationfilter
public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);
if (isAuthorized && !allowAnonymous)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "Authorization",
In = "header",
Description = "access token",
Required = true,
Type = "string"
});
}
}
}
然后,您会在招摇中看到一个额外的授权文本框,您可以在其中以承载者{jwttoken}"的格式添加令牌,并且应该在招摇请求中获得授权.
Then you will see an extra Authorization TextBox in your swagger where you can add your token in the format 'Bearer {jwttoken}' and you should be authorized in your swagger requests.
这篇关于在ASP.NET Core的Swagger中使用JWT(授权:承载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!