.net core 3.1 引入jwt 授权,在这篇文章“ASP.Net Core 3.1 中使用JWT认证” 已经做了总结,只是复制粘贴自己跑一遍
核心代码是这段:
public class AuthenticationService : IAuthenticateService
{
private readonly ITestService _testService;
private readonly TokenManagement _tokenManagement;
public AuthenticationService(ITestService testService, IOptions<TokenManagement> tokenManagement)
{
_testService = testService;
_tokenManagement = tokenManagement.Value;
}
public bool IsAuthenticated(LoginRequestDTO request, out string token)
{
token = string.Empty;
//此处做验证
if (!_testService.IsValid(request))
return false;
var claims = new[]
{
new Claim(ClaimTypes.Name,request.Username)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer, _tokenManagement.Audience, claims, expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration), signingCredentials: credentials);
token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return true;
}
}
可以结合request参数,在 _testService.IsValid(request) 接口做验证
TokenManagement 类定义 jwt 相关参数
public class TokenManagement
{
[JsonProperty("secret")]
public string Secret { get; set; }
[JsonProperty("issuer")]
public string Issuer { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("accessExpiration")]
public int AccessExpiration { get; set; }
[JsonProperty("refreshExpiration")]
public int RefreshExpiration { get; set; }
}
此外,在Startup.cs 文件的Configure 方法中增加 这段授权代码
app.UseAuthentication();
最后,在要调用的方法中,添加属性 [Authorize],就可以增加token验证了;也可以在控制器上添加,那么该控制器下所有接口都要验证。
原文:https://www.cnblogs.com/redo/p/12513934.html