.net core 3.1 jwt token授权
.net core 3.1 引入jwt 授权,在这篇文章“ASP.Net Core 3.1 中使用JWT认证” 已经做了总结,只是复制粘贴自己跑一遍
首先安装 Microsoft.AspNetCore.Authentication.JwtBearer
核心代码是这段:
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) 接口做验证
LoginRequestDTO 类定义request传参
public class LoginRequestDTO
{
[Required]
[JsonProperty("username")]
public string Username { get; set; }
[Required]
[JsonProperty("password")]
public string Password { get; set; }
}
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; }
}
tokenManagement 配置在appsettings.json
"tokenManagement": {
"secret": "123456123456123456",
"issuer": "webapi.cn",
"audience": "WebApi",
"accessExpiration": 30,
"refreshExpiration": 60
},
此外,修改Startup.cs 文件
在ConfigService方法中增加这段代码
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
在Configure 方法中增加 这段授权代码
app.UseAuthentication();
最后,在要调用的方法中,添加属性 [Authorize],就可以增加token验证了;也可以在控制器上添加,那么该控制器下所有接口都要验证。