using System; using System.Text; using JWT; using JWT.Serializers; using JWT.Algorithms; using JWT.Exceptions; using GTech.Solution.Api.Domain.Model.SystemSettings; namespace GTech.Solution.Api.Common.Common { public static class TokenGenerator { private static string secret = "yokogawa"; public static string GetToken(Userbasic u) { JWT.Algorithms.IJwtAlgorithm Algorithm = new JWT.Algorithms.HMACSHA256Algorithm(); JWT.IJsonSerializer json = new JsonNetSerializer(); JWT.IBase64UrlEncoder Base64 = new JWT.JwtBase64UrlEncoder(); JwtEncoder en = new JwtEncoder(Algorithm, json, Base64); byte[] keyBytes = Encoding.UTF8.GetBytes(secret); return en.Encode(u, keyBytes); } public static Userbasic GetUserbasic(string token) { IJsonSerializer js = new JsonNetSerializer(); JWT.IBase64UrlEncoder Base64 = new JWT.JwtBase64UrlEncoder(); JwtDecoder en = new JwtDecoder(js, Base64); return en.DecodeToObject(token); } 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); var json = decoder.Decode(token, secret, true); //校验通过,返回解密后的字符串 return json; } catch (TokenExpiredException) { throw new Exception("Session is expired, access is denied!"); } catch (SignatureVerificationException) { throw new Exception("Signature verification has error, access is denied!"); } catch (Exception) { throw new Exception("Unauthorized user, Access is denied!"); } } } }