jwt

using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jwt
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, object> payload = new Dictionary<string, object>
            {
                 {"userid",123 },{"username",123 }
            };            
            string secret = "dbhgfjdsgafuawfjdsgafjsaefg";
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//hash值加密

            IJsonSerializer serializer = new JsonNetSerializer();//序列化

            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();// 通过base64转义

            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//设置加密器

            var token = encoder.Encode(payload, secret);//生成jwt

            Console.WriteLine(token);
            decode();
            Console.ReadKey();
            //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOjEyMywidXNlcm5hbWUiOjEyM30.q7xXM72a6A4HoYlfkcvMWUe7tVxg6DPPGtBSiPqHdYU

        }
        public static void decode()
        {
            var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOjEyMywidXNlcm5hbWUiOjEyM30.q7xXM72a6A4HoYlfkcvMWUe7tVxg6DPPGtBSiPqHdYU";
            var secret = "dbhgfjdsgafuawfjdsgafjsaefg";
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                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, algorithm);
                var json = decoder.Decode(token, secret, verify: true);
                Console.WriteLine(json);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine(("Token 已经过期!"));
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine(("签名校验失败,数据可能被篡改!"));
            }
            catch
            {
                Console.WriteLine("??????");
            }
        }

    }
}

  

上一篇:序列化器-Serializer


下一篇:django rest framework中api view的两种写法