JWT加密解密

Nuget:Install-Package System.IdentityModel.Tokens.Jwt

加密:

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

//参数
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, "3"));
claims.Add(new Claim(ClaimTypes.Name, "zzz"));
claims.Add(new Claim(ClaimTypes.Role, "admin")); 
claims.Add(new Claim("company", "DosAuto"));


string key = "sd1a494dsa949dsa_*&*^4156dsa5e6";//服务器端秘钥

 DateTime expires=DateTime.Now.AddSeconds(30);//过期时间

//加密方法
byte[] secBytes=Encoding.UTF8.GetBytes(key);
var secKey = new SymmetricSecurityKey(secBytes);
var credentails = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
var tokenDescript = new JwtSecurityToken(claims:claims, expires:expires, signingCredentials:credentails);
string jwt=new JwtSecurityTokenHandler().WriteToken(tokenDescript);

//输出JWT
Console.WriteLine(jwt);
Console.ReadKey();

  

解密:

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

while (true)
{
    Console.WriteLine("input jwt code..");
    string? s = Console.ReadLine();
    if (s==null)
    {
        Console.WriteLine("input error, Please re-enter it");continue;
    }

    string key = "sd1a494dsa949dsa_*&*^4156dsa5e6";//秘钥

    //解密方法
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    TokenValidationParameters varParam = new TokenValidationParameters();
    var securityKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
    varParam.IssuerSigningKey= securityKey;
    varParam.ValidateIssuer = false;
    varParam.ValidateAudience = false; 
    ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(s, varParam, out SecurityToken secToken);
    //输出结果
    foreach (var item in claimsPrincipal.Claims)
    {
        Console.WriteLine($"{item.Type} = {item.Value}");
    } 
}

 

上一篇:Note -「模板」矩阵 - 行列式


下一篇:2021.10.19 离散化模板