1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- using JWT;
- using JWT.Algorithms;
- using JWT.Exceptions;
- using JWT.Serializers;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace CollectInformation.Tools
- {
- public class JWTUtils
- {
- /// <summary>
- /// 创建token
- /// </summary>
- /// <returns></returns>
- public static string CreateJwtToken(IDictionary<string, object> payload, string secret, IDictionary<string, object> extraHeaders = null)
- {
- IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
- IJsonSerializer serializer = new JsonNetSerializer();
- IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
- IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
- var token = encoder.Encode(payload, secret);
- return token;
- }
- /// <summary>
- /// 校验解析token
- /// </summary>
- /// <returns></returns>
- public static string ValidateJwtToken(string token)
- {
- try
- {
- IJsonSerializer serializer = new JsonNetSerializer();
- IDateTimeProvider provider = new UtcDateTimeProvider();
- IJwtValidator validator = new JwtValidator(serializer, provider);
- IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
- IJwtAlgorithm alg = new HMACSHA256Algorithm();
- IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
- string json = decoder.Decode(token);
- //校验通过,返回解密后的字符串
- return json;
- }
- catch (TokenExpiredException)
- {
- //表示过期
- return "expired";
- }
- catch (SignatureVerificationException)
- {
- //表示验证不通过
- return "invalid";
- }
- catch (Exception)
- {
- return "error";
- }
- }
- /// <summary>
- /// 校验解析token
- /// </summary>
- /// <returns></returns>
- public static string ValidateJwtToken(string token, string secret)
- {
- try
- {
- IJsonSerializer serializer = new JsonNetSerializer();
- IDateTimeProvider provider = new UtcDateTimeProvider();
- IJwtValidator validator = new JwtValidator(serializer, provider);
- IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
- IJwtAlgorithm alg = new HMACSHA256Algorithm();
- IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
- var json = decoder.Decode(token, secret, true);
- //校验通过,返回解密后的字符串
- return json;
- }
- catch (TokenExpiredException)
- {
- //表示过期
- return "expired";
- }
- catch (SignatureVerificationException)
- {
- //表示验证不通过
- return "invalid";
- }
- catch (Exception)
- {
- return "error";
- }
- }
- }
- }
|