JWT

介绍什么的都不说了,直接捞干的

 

 //首先NuGet 安装JWT
            var payload = new Dictionary<string, object>
            {
                //这里面你可以自己定义任何你要验证的字段
                {"name","Bob" },
                {"appid","zqs"},
                //Exp是过期时期,一定是时间戳,其他的不行。其他的在验证token的时候会报错
               //这个就是此次生成token的过期时间是8个小时后  (DateTime.UtcNow.AddHours(8) - new DateTime(1970, 1, 1)).TotalSeconds;
                {"exp",(DateTime.UtcNow.AddMinutes(10)-new DateTime(1970,1,1)).TotalSeconds}
            };
            //时间戳可以访问这个网址:https://tool.lu/timestamp/

            //密钥,不可外泄,你自己只要久行了
            var secsert = "bfdgfdabgifhgfnbibiutbfajbvufafg";

            IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(jwtAlgorithm, serializer, urlEncoder);
            var token = encoder.Encode(payload, secsert);
            //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQm9iIiwiYXBwaWQiOiJ6cXMiLCJleHAiOjE1OTkyODU0NjcuMTAxNDM0N30.T8xkbhQ8upx1RdxRLv5xprBb-ASGK8qn1hkOuo38__k
            Console.WriteLine(token);

https://jwt.io/

接下来是验证token

//解析token
            IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer1 = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer1, provider);
            IBase64UrlEncoder urlEncoder1 = new JwtBase64UrlEncoder();
            IJwtDecoder decoder = new JwtDecoder(serializer1, validator, urlEncoder1, jwtAlgorithm);

            //密钥,不可外泄
            var secsert1 = "bfdgfdabgifhgfnbibiutbfajbvufafg";
            string Itoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQm9iIiwiYXBwaWQiOiJ6cXMiLCJleHAiOjE1OTkyODU0NjcuMTAxNDM0N30.T8xkbhQ8upx1RdxRLv5xprBb-ASGK8qn1hkOuo38__k";

            //解析token有两种
            //第一种,直接Decode token的值,这个只要是你符合JWT的合适就会解析出来,无论你是张三李四,我都可以解析json,然后取值对比
            //var json = decoder.Decode(token);

            //第二种,加入verify和secsert1
            //verify:检查数据的合法性(这样如果你自己的密钥或者token被改变了,就会报错的,这样使得验证更加严格)
            //JWT.Exceptions.SignatureVerificationException:“Invalid 
            var json2 = decoder.Decode(Itoken, secsert1, verify: true);
            Console.WriteLine(json2);

 

posted @ 2020-09-05 14:14  ProZkb  阅读(144)  评论(0编辑  收藏  举报