其他分享
首页 > 其他分享> > JWT加密解密

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}");
    } 
}

 

标签:claims,加密,JWT,System,Console,解密,new,var,using
来源: https://www.cnblogs.com/Zingu/p/15825141.html