dfm*_*tro 3 c# jwt asp.net-core asp.net-core-webapi asp.net-core-identity
我在ASP.NET Core 2 Web应用程序中使用JWT令牌
如果JWT令牌失败,我仍然希望命中控制器方法,但ASP.NET Identity User对象将只为null.目前,如果身份验证失败,则不会输入控制器方法,因此我无法在方法中应用逻辑来处理我想要作为来宾处理的非身份验证用户,而不是阻止它们.
我的代码:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = _config["Tokens:Issuer"],
ValidAudience = _config["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]))
};
});
Run Code Online (Sandbox Code Playgroud)
用户登录时
private IActionResult CreateToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims.ToArray(),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: creds);
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
};
return Created("", results);
Run Code Online (Sandbox Code Playgroud)
我确保在经过身份验证后,各种API调用都会传递JWT令牌.
在我的控制器中,我使用了Authorize属性
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : Controller
{
Run Code Online (Sandbox Code Playgroud)
这允许我使用以下代码捕获登录用户以进行各种API调用
var loggedInUser = User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)
如果我删除authorize属性,User.Identity.Name即使用户已通过身份验证,也将始终为null.
如何使用authorize属性,但如果令牌无效,仍然允许输入控制器方法?我想对输入授权用户和非授权用户使用相同的方法.然后,我将使用它User.Identity.Name来确定它们是否未经过身份验证,并且在方法中包含guest用户逻辑.
它实际上比你想象的要容易.你可以只用两 Authorize和AllowAnonymous,就像这样:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[AllowAnonymous]
public class MyController : Controller
Run Code Online (Sandbox Code Playgroud)
如果授权成功,您将获得authenticated User(User.Identity.IsAuthenticated = true),否则您将拥有匿名User.
| 归档时间: |
|
| 查看次数: |
1477 次 |
| 最近记录: |