JWE 简介
在前后端分离的项目中,我们经常使用JWT作为无状态身份认证的方式。然而,JWT中的payload是明文的,这意味着有可能泄露用户的信息。为了保护用户信息不被泄露,一些项目会对JWT的payload进行了加密,需要自己写一些加密的代码。实际上,还有一种更加简单的方法,那就是使用JWE, JWE 是对整个Token进行加密的,相对来说更加安全。
net中使用JWE
只要在JWT的基础之上稍作修改即可 代码下载
//产生Token
[HttpPost]
public IActionResult Login(string account, string pwd)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, account),
new Claim(ClaimTypes.Role, "a"),
new Claim(ClaimTypes.Role, "b"),
new Claim("test", "123")
};
var signingSecretBytes = Encoding.UTF8.GetBytes(Constant.SigningSecret);
var signingKey = new SymmetricSecurityKey(signingSecretBytes);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var secret = Encoding.ASCII.GetBytes(Constant.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = Constant.Issuer,
Audience = Constant.Audiance,
Expires = DateTime.Now.AddDays(1),
Subject = new ClaimsIdentity(claims),
SigningCredentials = signingCredentials,
EncryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(secret),
SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256) //JWE
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
var result = tokenHandler.WriteToken(token);
return Ok(result);
}
//验证
services.AddAuthentication().AddJwtBearer(Constant.JwtBearerAuthenticationScheme, options =>
{
var secretBytes = Encoding.UTF8.GetBytes(Constant.SigningSecret);
var key = new SymmetricSecurityKey(secretBytes);
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.Zero,
ValidateIssuer = true,
ValidIssuer = Constant.Issuer,
ValidateAudience = false,
IssuerSigningKey = key,
TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Constant.Secret)) //JWE
};
});