学习jwt的简单使用

install-package jwt

 

        protected void ButtonLogin_Click(object sender, EventArgs e)
        {
            var secret = "abc123";
            var exp = (DateTime.UtcNow.AddSeconds(10) - new DateTime(1970, 1, 1)).TotalSeconds;
            var payload = new Dictionary<string, object> {
                {"Name",TextBoxName.Text },
                { "Pwd",TextBoxPwd.Text },
                { "exp",exp }
            };
            var algorithm = new HMACSHA256Algorithm();
            var jsonSerializer = new JsonNetSerializer();
            var urlEncoder = new JwtBase64UrlEncoder();
            var encoder = new JwtEncoder(algorithm, jsonSerializer, urlEncoder);
            var token = encoder.Encode(payload, secret);
            TextBox1.Text = token;
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            var secret = "abc123";
            var token = TextBox1.Text;
            try
            {
                var algorithm = new HMACSHA256Algorithm();
                var jsonSerializer = new JsonNetSerializer();
                var dateTimeProvider = new UtcDateTimeProvider();
                var jwtValidator = new JwtValidator(jsonSerializer, dateTimeProvider);
                var urlEncoder = new JwtBase64UrlEncoder();
                var decoder = new JwtDecoder(jsonSerializer, jwtValidator, urlEncoder, algorithm);
                var json = decoder.Decode(token, secret, true);
                Label1.Text = json;
            }
            catch (TokenExpiredException)
            {
                Label1.Text = "过期";
            }
            catch (SignatureVerificationException)
            {
                Label1.Text = "篡改";
            }
        }

 

 

 

 

 

posted @ 2020-12-21 14:47  毛毛虫!  阅读(117)  评论(0编辑  收藏  举报