Rub*_*nov 26 c# jwt swagger asp.net-core
我正在ASP.NET Core 1.0中创建一个REST api.我正在使用Swagger进行测试,但现在我为某些路线添加了JWT授权.(带UseJwtBearerAuthentication)
是否可以修改Swagger请求的标头,以便[Authorize]可以测试具有该属性的路由?
Han*_*sVG 32
我努力解决同样的问题,并在这篇博文中找到了一个可行的解决方案:http: //blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField
它归结为在配置选项中添加它
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});
Run Code Online (Sandbox Code Playgroud)
和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"
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您将在swagger中看到一个额外的授权TextBox,您可以在其中以"Bearer {jwttoken}"格式添加您的令牌,并且您应该在您的招摇请求中获得授权.
Pav*_* K. 13
目前,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<string, string>
//{
// { "api-name", "my api" },
//}
});
});
Run Code Online (Sandbox Code Playgroud)
如果您的端点不同,请检查并配置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");
});
Run Code Online (Sandbox Code Playgroud)
如果您通过令牌进行身份验证的端点遵循OAuth2标准,则所有端点都应该有效.但为了以防万一,我添加了此端点的示例:
public class AccountController : Controller
{
[ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.Unauthorized)]
[HttpPost("/token")]
public async Task<IActionResult> 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; }
}
Run Code Online (Sandbox Code Playgroud)
感谢Pavel K. 的回答,这就是我最终在 ASP.NET Core 2.2 和 Swagger 4.0.1 中解决这个问题的方法。
在 Startup.cs ConfigureServices() 中:
public void ConfigureServices(IServiceCollection services)
{
.
.
.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "...", Version = "v1" });
.
.
.
c.AddSecurityDefinition("Bearer", new OAuth2Scheme
{
Flow = "password",
TokenUrl = "/token"
});
// It must be here so the Swagger UI works correctly (Swashbuckle.AspNetCore.SwaggerUI, Version=4.0.1.0)
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }}
});
});
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
在 Startup.cs Configure() 中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.
.
.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "...");
// Provide client ID, client secret, realm and application name (if need)
c.OAuthClientId("...");
c.OAuthClientSecret("...");
c.OAuthRealm("...");
c.OAuthAppName("...");
});
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
下面是我如何制作一个端点来发出 JWT 令牌:
[ApiController, Route("[controller]")]
public class TokenController : ControllerBase
{
[HttpPost, AllowAnonymous]
public async Task<ActionResult<AccessTokensResponse>> RequestToken([FromForm]LoginRequest request)
{
var claims = await ValidateCredentialAndGenerateClaims(request);
var now = DateTime.UtcNow;
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_setting.SecurityKey));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _setting.Issuer,
audience: _setting.Audience,
claims: claims,
notBefore: now,
expires: now.AddMinutes(_setting.ValidDurationInMinute),
signingCredentials: signingCredentials);
return Ok(new AccessTokensResponse(token));
}
}
Run Code Online (Sandbox Code Playgroud)
您验证用户名和密码(和/或 client_id 和 clinet_secret)的所有规则和逻辑都将在ValidateCredentialAndGenerateClaims().
如果你只是想知道,这些是我的请求和响应模型:
/// <summary>
/// Encapsulates fields for login request.
/// </summary>
/// <remarks>
/// See: https://www.oauth.com/oauth2-servers/access-tokens/
/// </remarks>
public class LoginRequest
{
[Required]
public string grant_type { get; set; }
public string username { get; set; }
public string password { get; set; }
public string refresh_token { get; set; }
public string scope { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
}
/// <summary>
/// JWT successful response.
/// </summary>
/// <remarks>
/// See: https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/
/// </remarks>
public class AccessTokensResponse
{
/// <summary>
/// Initializes a new instance of <seealso cref="AccessTokensResponse"/>.
/// </summary>
/// <param name="securityToken"></param>
public AccessTokensResponse(JwtSecurityToken securityToken)
{
access_token = new JwtSecurityTokenHandler().WriteToken(securityToken);
token_type = "Bearer";
expires_in = Math.Truncate((securityToken.ValidTo - DateTime.UtcNow).TotalSeconds);
}
public string access_token { get; set; }
public string refresh_token { get; set; }
public string token_type { get; set; }
public double expires_in { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
为了扩展对我有用的HansVG答案(谢谢),并且由于我的贡献点不足,因此我无法直接回答emseetea问题。拥有“授权”文本框后,您将需要调用生成令牌的端点,该令牌将位于端点的必须[Authorize]区域之外。
调用该端点从端点生成令牌后,您可以将其复制到该端点的结果中。然后,您将拥有必须在[授权]的其他区域中使用的令牌。只需将其粘贴到文本框中即可。如HansVG所述,确保以正确的格式添加它,并且需要包含“ bearer”。格式=“ bearer {token}”。
您可以使用此swagger 配置通过 API 调用添加任何其他标头
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Core API",
Description = "ASP.NET Core API",
TermsOfService = "None",
Contact = new Contact
{
Name = "Raj Kumar",
Email = ""
},
License = new License
{
Name = "Demo"
}
});
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer",new string[]{}}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27916 次 |
| 最近记录: |