在ASP.NET Core中使用Swagger中的JWT(授权:承载)

我正在ASP.NET Core 1.0中创建一个REST api。 我正在使用Swagger进行测试,但现在我为某些路线添加了JWT授权。 (使用UseJwtBearerAuthentication

是否可以修改Swagger请求的标头,以便可以测试具有[Authorize]属性的路由?

我在同一个问题上苦苦挣扎,并在这篇博文中找到了一个可行的解决方案: http : //blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField

它归结为在配置选项中添加它

 services.ConfigureSwaggerGen(options => { options.OperationFilter(); }); 

和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(); operation.Parameters.Add(new NonBodyParameter { Name = "Authorization", In = "header", Description = "access token", Required = true, Type = "string" }); } } } 

然后,您将在swagger中看到一个额外的授权文本框,您可以在其中以“Bearer {jwttoken}”格式添加您的令牌,并且您应该在您的招摇请求中获得授权。

为了扩展对我有用的HansVG答案(谢谢),由于我没有足够的贡献点,我不能直接回答emseetea问题。 获得授权文本框后,您将需要调用生成令牌的端点,该令牌将位于端点的必须[授权]区域之外。

一旦调用该端点以从端点生成令牌,您就可以将其从该端点的结果中复制出来。 然后你有令牌在你必须[授权]的其他区域使用。 只需将其粘贴到文本框中即可。 正如HansVG所提到的那样,确保以正确的格式添加它,其中需要包含“bearer”。 Format =“bearer {token}”。

目前,Swagger具有使用JWT-token进行身份validation的function,并且可以自动将标记添加到标头中(我使用的是Swashbuckle.AspNetCore 1.1.0)。

在此处输入图像描述

以下代码应该有助于实现这一目标。

在Startup.ConfigureServices()中:

 services.AddSwaggerGen(c => { // Your custom configuration c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); c.DescribeAllEnumsAsStrings(); // JWT-token authentication by password c.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "password", TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/token"), // Optional scopes //Scopes = new Dictionary //{ // { "api-name", "my api" }, //} }); }); 

如果您的端点不同,请检查并配置TokenUrl

在Startup.Configure()中:

 app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); // Provide client ID, client secret, realm and application name (if need) c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI"); }); 

如果您的令牌身份validation端点遵循OAuth2标准,那么所有端点都应该有效。 但为了以防万一,我添加了此端点的示例:

 public class AccountController : Controller { [ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Unauthorized)] [HttpPost("/token")] public async Task Token([FromForm] LoginModel loginModel) { switch (loginModel.grant_type) { case "password": var accessTokens = // Authentication logic if (accessTokens == null) return BadRequest("Invalid user name or password."); return new ObjectResult(accessTokens); case "refresh_token": var accessTokens = // Refresh token logic if (accessTokens == null) return Unauthorized(); return new ObjectResult(accessTokens); default: return BadRequest("Unsupported grant type"); } } } public class LoginModel { [Required] public string grant_type { get; set; } public string username { get; set; } public string password { get; set; } public string refresh_token { get; set; } // Optional //public string scope { get; set; } } public class AccessTokens { public string access_token { get; set; } public string refresh_token { get; set; } public string token_type { get; set; } public int expires_in { get; set; } }