JWT 初探
JWT全称是Json Web Token,是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的标准( RFC 7519 ),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信息。因为数字签名的存在,这些信息是可信的,JWT可以使用HMAC算法或者是RSA的公私秘钥对进行签名。
在VS 项目中
添加程序包 JWT 安装 引入命名空间
新建一个类JwtTools
#region using JWT; using JWT.Algorithms; using JWT.Serializers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Repository { public class JwtTools { public static string Encode(Dictionary<string, object> payload, string key) { IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return encoder.Encode(payload, key); } public static string Decode(string token, string key) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder Decoder = new JwtDecoder(serializer, validator, urlEncoder); return Decoder.Decode(token, key, verify: true); } catch (TokenExpiredException) { throw new Exception("Token has expired");// 令牌已过期 } catch (SignatureVerificationException) { throw new Exception("token has invalid signature");//令牌已过期 } } public static string valideLogined(string request, string key) { // string key = "123"; if (request == null )//|| request.Any() { throw new Exception(message: "请登录"); } return Decode(request, key); } } } #endregion
调用:
string key = "123"; //验证 //加密写入 返回值 //验证 解密 string str = JwtTools.Encode(new Dictionary<string, object> { { "UserId", userinfo.UserId },{ "UserName",userinfo.UserName} }, key); return str;
官网:https://jwt.io/
阮一峰的JSON web Token 入门教程