問題描述
我正在 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>();
});
以及操作過濾器的代碼
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"
});
}
}
}
然后你會在你的 swagger 中看到一個額外的 Authorization TextBox,你可以在其中以Bearer {jwttoken}"格式添加你的令牌,并且你應該在你的 swagger 請求中獲得授權.
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(授權:Bearer)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!