我正在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中看到一个额外的授权TextBox,您可以在其中以"Bearer {jwttoken}"格式添加您的令牌,并且您应该在您的招摇请求中获得授权.
目前,Swagger具有使用JWT-token进行身份验证的功能,并且可以自动将标记添加到标头中(我使用的是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) // Swashbuckle.AspNetCore 4.0.1 c.OAuthClientId("swagger-ui"); c.OAuthClientSecret("swagger-ui-secret"); c.OAuthRealm("swagger-ui-realm"); c.OAuthAppName("Swagger UI"); // Swashbuckle.AspNetCore 1.1.0 // c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI"); });
如果您通过令牌进行身份验证的端点遵循OAuth2标准,则所有端点都应该有效.但为了以防万一,我添加了此端点的示例:
public class AccountController : Controller { [ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] [ProducesResponseType((int)HttpStatusCode.Unauthorized)] [HttpPost("/token")] public async TaskToken([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; } }
为了扩展对我有用的HansVG答案(谢谢),并且由于我的贡献点不足,因此我无法直接回答emseetea问题。拥有“授权”文本框后,您将需要调用生成令牌的端点,该令牌将位于端点的必须[Authorize]区域之外。
调用该端点从端点生成令牌后,您可以将其复制到该端点的结果中。然后,您将拥有必须在[授权]的其他区域中使用的令牌。只需将其粘贴到文本框中即可。如HansVG所述,确保以正确的格式添加它,并且需要包含“ bearer”。格式=“ bearer {token}”。