JWT-校验

JWT就相当于自己定义的Token,JWT是在服务端根据秘钥加密后生成的字符串,然后经过BASE64加密输出,现在前后端分离的web项目用的挺多的,根据自己的项目情况来。

JWT字符串由三部分组成:header.payload.signature(header+payload+secret)

这里就不再详细介绍了,直接看代码:

安装JWT:Install-Package Jwt

    class Program
    {
        static void Main(string[] args)
        {
            string jwtStr = JwtHelper.Encode(new { Name = "xiaoqiu" });
            Console.WriteLine(jwtStr);
            Console.WriteLine(JwtHelper.DeCode(jwtStr));
            Console.ReadKey();
        }
    }
    public class JwtHelper
    {
        private static string secret = "Test123456";        //服务端秘钥,secret用于校验,不要泄露给客户端

        /// 
        /// Jwt编码
        /// 
        /// 认证依据
        /// Jwt签名
        public static string Encode(object payload)
        {
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, secret);
        }

        /// 
        /// Jwt解码
        /// 
        /// jwt令牌
        /// 
        public static string DeCode(string jwtStr)
        {
            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(jwtStr, secret, verify: true);
        }
    }

生成的JWT字符串:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJOYW1lIjoieGlhb3FpdSJ9.Cl7KGTCncjDUY2dISmy79A9NCDpPu87NmWIZY-hFN2Q

第二部分:eyJOYW1lIjoieGlhb3FpdSJ9 就是payload,就是经过Base64编码的信息,解析后是:{"Name":"xiaoqiu"}

所以登录信息,不要存放用户敏感信息,是不安全的。每次客户端携带JWT字符串来校验,

如果校验失败,会报异常:SignatureVerificationException 验证失败。


你可能感兴趣的:(.Net,Core)