我使用ASP。NET Core&ASP。NET核心标识来生成JWT令牌。
在客户端,我的React(SPA)应用程序调用API来创建令牌,然后包括
Authorization: Bearer
token from API
在子请求中。
目前,我只是删除了
bear
参考
https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/
代码输入
Configure
中的部分
Startup.cs
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "MySite",
ValidAudience = "MySite",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE")),
ValidateLifetime = true
}
});
创建令牌的API
[HttpPost("Token")]
public async Task<IActionResult> CreateToken([FromBody] LoginModel model)
{
try
{
var user = await userManager.FindByNameAsync(model.Email);
if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
"MySite",
"MySite",
claims,
expires: DateTime.UtcNow.AddMinutes(45),
signingCredentials: creds);
return Ok(new
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
});
}
return BadRequest();
}
catch (Exception ex)
{
logger.LogError(ex.ToString());
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}