internal static Tuple <bool, TokenStatus, int> DecodeToken(string token) { 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); try { var json = decoder.Decode(token, secret, verify: true); var payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); return(Tuple.Create(true, TokenStatus.Valid, int.Parse(payload["user_id"].ToString()))); } catch (TokenExpiredException) { var json = decoder.Decode(token, secret, false); var payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); return(Tuple.Create(false, TokenStatus.Expired, int.Parse(payload["user_id"].ToString()))); } catch (SignatureVerificationException) { return(Tuple.Create(false, TokenStatus.Invalid, 0)); } }
public Token(String secretKey, IAdviceDateTimeProvider dateProvider, String token) : this(secretKey, dateProvider) { IJsonSerializer serializer = new JsonNetSerializer(); IJwtValidator validator = new JwtValidator(serializer, this.DateTime); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); try { var json = decoder.Decode(token, this.SecretKey, verify: true); var jsonObject = JObject.Parse(json); this.UserId = Guid.Parse(jsonObject["userId"].Value <String>()); this.UserName = jsonObject["userName"].Value <String>(); this.IssuedAt = ConvertFromUnixTimestamp(jsonObject["iat"].Value <Int64>()); this.ExpiresAt = ConvertFromUnixTimestamp(jsonObject["exp"].Value <Int64>()); foreach (var child in jsonObject.Children()) { if (child.Path.Equals("userId") || child.Path.Equals("userName") || child.Path.Equals("iat") || child.Path.Equals("exp")) { continue; } //JProperty childProperty = child as JProperty; //if(childProperty != null) // this.CustomClaims.Add(childProperty.Name, childProperty.Value<String>()); if (child.Type == JTokenType.Property) { var childProperty = (JProperty)child; this.CustomClaims.Add(childProperty.Name, child.First.Value <String>()); } else { this.CustomClaims.Add(child.Path, child.First.Value <String>()); } } this.Valid = true; } catch (TokenExpiredException) { this.Error = "Token Expired"; var json = decoder.Decode(token, this.SecretKey, false); var jsonObject = JObject.Parse(json); this.UserId = Guid.Parse(jsonObject["userId"].Value <String>()); this.UserName = jsonObject["userName"].Value <String>(); } catch (SignatureVerificationException) { this.Error = "Token Signature Failure"; } }
public static bool CheckToken(string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); IJwtValidator validator = new JwtValidator(serializer, new UtcDateTimeProvider()); IJwtDecoder decoder = new JwtDecoder(serializer, validator, new JwtBase64UrlEncoder(), new HMACSHA256Algorithm()); var json = decoder.Decode(token, AuthenticationController.secret, verify: true); return(true); } catch (Exception) { return(false); } /*catch (TokenExpiredException) * { * return "Token has expired"; * } * catch (SignatureVerificationException) * { * return "Token has invalid signature"; * }*/ }
public VarlikResult <TokenUser> Decode(string token) { var result = new VarlikResult <TokenUser>(); try { 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); var json = decoder.Decode(token, secret, verify: true); var res = JsonConvert.DeserializeObject <TokenUser>(json); /* if ((DateTime.Now -res.CreatedAt).Minutes >3 ) * { * result.Status = ResultStatus.TokenTimedOut; * return result; * }*/ result.Data = res; result.Success(); return(result); } catch (Exception e) { } return(result); }
public string DecodeHS256(string token, string secretKey) { try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, secretKey, verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(null); }
public static string Jwtdecoder(string token) { try { 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); //var json = decoder.Decode(token, secret, verify: true); string json = decoder.Decode(token); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(""); }
/// <summary> /// 验证token是否有效 /// </summary> /// <param name="token">token</param> public static void ValidateToken(string token) { string secret = ConfigHelper.GetConfigString("JWTSecret");; try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, secret, verify: true); } catch (TokenExpiredException) { //TODO:Token验证返回信息 Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { //TODO:Token验证返回信息 Console.WriteLine("Token has invalid signature"); } }
/// <summary> /// Jwt 解密 /// </summary> /// <returns></returns> public static Dictionary <string, object> Decode(string secret, string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, secret, verify: true); var payload = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); // 去除超时时间 if ((DateTime)payload["timeOut"] < DateTime.Now) { throw new Exception("登录超时,请重新登录"); } payload.Remove("timeOut"); return(payload); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); throw; } catch (SignatureVerificationException) { Console.WriteLine("签名验证失败,数据可能被篡改"); throw; } }
public static Token extractPaylod(string _token) { string jsonPayload = ""; Token tokenPayload = null; try { 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); string secret = ConfigurationManager.AppSettings["key"].ToString(); jsonPayload = decoder.Decode(_token, secret, verify: true); tokenPayload = serializer.Deserialize <Token>(jsonPayload); //Console.WriteLine(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(tokenPayload); }
public static bool ValidateToken(string token, out Employee employee) { employee = null; try { var keySec = _secret; if (string.IsNullOrWhiteSpace(AppGlobal.NexusConfig.Secret)) { keySec = AppGlobal.NexusConfig.Secret; } JWT.IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm();// symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var stringToken = decoder.Decode(token, keySec, verify: true); var payLoad = JsonConvert.DeserializeObject <Dictionary <string, object> >(stringToken); var userInfoPayload = payLoad["Employee"]; employee = JsonConvert.DeserializeObject <Employee>(userInfoPayload.ToString()); return(true); } catch (TokenExpiredException) { Logger.Write("Token has expired: " + token, true); } catch (SignatureVerificationException) { Logger.Write("Token has invalid signature: " + token, true); } return(false); }
private bool IsTokenValid() { try { var secret = WebConfigurationManager.AppSettings.Get("JwtSecretKey"); var serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); var validator = new JwtValidator(serializer, provider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var json = decoder.Decode(token, secret, verify: true); return(true); } catch (TokenExpiredException) { return(false); } catch (SignatureVerificationException) { return(false); } }
/// <summary> /// jwt解密 /// </summary> /// <returns></returns> public static T JwtDecrypt <T>(HttpControllerContext context) { IEnumerable <string> values; context.Request.Headers.TryGetValues("token", out values); string token = values.First(); try { 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); var json = decoder.Decode(token, secret, verify: true); return(serializer.Deserialize <T>(json)); } catch (TokenExpiredException) { return(default(T)); } catch (SignatureVerificationException) { return(default(T)); } }
public string CheckToken(string Token, string KeySecret) { string[] arrToken = Token.Split("."); int lengthSalt = _appsettings.Salt.Length; string tokenSecond = arrToken[1].Substring(lengthSalt); string token = string.Format("{0}.{1}.{2}", arrToken[0], tokenSecond, arrToken[2]); string secret = KeySecret; try { 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); var json = decoder.Decode(token, secret, verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); return("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); return("Token has invalid signature"); } }
public static bool Decrypt <T>(string token, out T obj) where T : class { try { 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); var json = decoder.Decode(token, secret, verify: true); obj = JsonConvert.DeserializeObject <T>(json); return(true); } catch (TokenExpiredException) { obj = null; return(false); } catch (SignatureVerificationException) { obj = null; return(false); } catch (Exception) { obj = null; return(false); } }
protected void Page_Load(object sender, EventArgs e) { string token = Request.Params.Get("token"); if (String.IsNullOrEmpty(token)) { lbLoginError.Text = "Invalid Token!"; lbLoginError.Visible = true; lbNewPass.Visible = false; tbNewPassword.Visible = false; btnReset.Visible = false; } else { try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, System.Configuration.ConfigurationManager.AppSettings["JWT_KEY"], verify: true); Verify.Token tokenObj = JsonSerializer.Deserialize <Verify.Token>(json); if (tokenObj.type == "reset") { userId = tokenObj.id.ToString(); if (Page.IsPostBack) { validate_190704d(); } } else { lbLoginError.Text = "Invalid Token!"; lbLoginError.Visible = true; lbNewPass.Visible = false; tbNewPassword.Visible = false; btnReset.Visible = false; } } catch (TokenExpiredException) { lbLoginError.Text = "Expired Token!"; lbLoginError.Visible = true; lbNewPass.Visible = false; tbNewPassword.Visible = false; btnReset.Visible = false; } catch (SignatureVerificationException) { lbLoginError.Text = "Invalid Token!"; lbLoginError.Visible = true; lbNewPass.Visible = false; tbNewPassword.Visible = false; btnReset.Visible = false; } } }
public static bool VaildateToken(string tokenkey, out TokenInfo json) { if (!string.IsNullOrEmpty(tokenkey)) { try { string token = DESEncrypt.DesDecrypt(tokenkey); byte[] key = Encoding.UTF8.GetBytes(secret); 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); string result = decoder.Decode(token, key, true); json = decoder.DecodeToObject <TokenInfo>(token, key, true); if (json != null) { return(true); } } catch (Exception e) { // ignored } } json = null; return(false); }
public static DecodedToken DecodeToken(string token) { try { 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); var json = decoder.Decode(token, _secret, verify: true); var payload = decoder.DecodeToObject <UserViewModel>(token, _secret, true); return(new DecodedToken { IsValid = true, TokenJson = payload, TokenString = json }); } catch (TokenExpiredException) { return(new DecodedToken { IsValid = false, ErrorMsg = "Token has expired" }); } catch (SignatureVerificationException) { return(new DecodedToken { IsValid = false, ErrorMsg = "Token has invalid signature" }); } }
public static Dictionary <string, object> Decode(string jwtStr, string key = null) { if (string.IsNullOrWhiteSpace(key)) { key = Key; } try { IJsonSerializer jsonSerializer = new JsonNetSerializer(); IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider(); IJwtValidator jwtValidator = new JwtValidator(jsonSerializer, dateTimeProvider); IAlgorithmFactory algorithmFactory = new HMACSHAAlgorithmFactory(); IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm(); IBase64UrlEncoder base64UrlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder jwtDecoder = new JwtDecoder(jsonSerializer, jwtValidator, base64UrlEncoder, algorithmFactory); var json = jwtDecoder.Decode(token: jwtStr, key, verify: true); var result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if (Convert.ToDateTime(result["timeout"]) < DateTime.Now) { throw new Exception(message: "token已过期请重新登录"); } else { result.Remove(key: "timeout"); } return(result); } catch (TokenExpiredException) { throw; } }
public bool validateToken(string _token) { bool verified = false; try { 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); string secret = ConfigurationManager.AppSettings["key"].ToString(); string jsonPayload = decoder.Decode(_token, secret, verify: true); //string jsonPayload = JWT.JsonWebToken.Decode(_token, ConfigurationManager.AppSettings["key"].ToString()); verified = true; } catch (JWT.SignatureVerificationException) { verified = false; Console.WriteLine("Invalid token!"); } return(verified); }
public static ActionOutput ValidateToken(string token) { var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; try { 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); var json = decoder.Decode(token, secret, verify: true); return(new ActionOutput { Message = json, Status = ActionStatus.Successfull }); } catch (TokenExpiredException ex) { return(new ActionOutput { Message = "Token has been expired", Status = ActionStatus.Error }); } catch (SignatureVerificationException) { return(new ActionOutput { Message = "Token has invalid signature", Status = ActionStatus.Error }); } }
public Object FuncaoRetornoJWT(string token) { try { var publicKey = new X509Certificate2("my-key.p12", "password"); 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); var json = decoder.Decode(token, publicKey.ToString(), verify: true); return(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(""); }
public bool Validate(string validingJwt, string encoded64Secret) { if (string.IsNullOrEmpty(validingJwt)) { throw new MyAuthorizationException(ErrorMessage.JwtEmpty, ErrorCodeCategory.CrmAuthorization.ToString()); } var base64Decode = Base64Decode(encoded64Secret); try { 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); decoder.Decode(validingJwt, base64Decode, verify: true); } catch (TokenExpiredException) { throw new MyAuthorizationException(ErrorMessage.JwtExpired, ErrorCodeCategory.CrmAuthorization.ToString()); } catch (SignatureVerificationException) { throw new MyAuthorizationException(ErrorMessage.JwtInvalid, ErrorCodeCategory.CrmAuthorization.ToString()); } catch (System.Exception ex) { throw new MyAuthorizationException(ErrorMessage.JwtUnexpectedException, ErrorCodeCategory.CrmAuthorization.ToString(), ex.InnerException); } return(true); }
public static rs Decode(string token = "") { rs r; var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; try { 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); // var json = decoder.Decode(token, secret, verify: true); JwtLoginModel model = JsonConvert.DeserializeObject <JwtLoginModel>(json); r = rs.T("Ok", model); } catch (TokenExpiredException) { r = rs.F("Token has expired"); } catch (SignatureVerificationException) { r = rs.F("Token has invalid signature"); } return(r); }
private 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); //校验通过,返回解密后的字符串 return(json); } catch (TokenExpiredException) { //表示过期 return("expired"); } catch (SignatureVerificationException) { //表示验证不通过 return("invalid"); } catch (Exception) { return("error"); } }
public static Dictionary <string, object> EnDecode(string jwtStr, string key = null) { if (string.IsNullOrEmpty(key)) { key = Key; } try { 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); var json = decoder.Decode(jwtStr, key, verify: true); //把一个字符串反向生成对应的对象内容 var reslut = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if ((DateTime)reslut["timeout"] < DateTime.Now) { throw new Exception("jwt已经过期,请重新登陆"); } reslut.Remove("timeout"); return(reslut); } catch (TokenExpiredException) { throw; } catch (SignatureVerificationException) { throw; } }
// Verifica public Object DecodingToken(string token) { try { 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); var json = decoder.Decode(token, secret, verify: false); Token tokenObj = new Token(); JObject obj = JObject.Parse(json); var aux = ((string)obj.SelectToken("exp")).Split(' '); var fecha = aux[0].Split('/'); var horas = aux[1].Split(':'); var exp = new DateTime(int.Parse(fecha[2]), int.Parse(fecha[0]), int.Parse(fecha[1]), int.Parse(horas[0]), int.Parse(horas[1]), int.Parse(horas[2])); tokenObj.IdUsuario = (int)obj.SelectToken("IdUsuario"); tokenObj.IdEscuela = (int)obj.SelectToken("IdEscuela"); return(tokenObj); } catch (TokenExpiredException) { return("Token has expired"); } catch (SignatureVerificationException) { return("Token has invalid signature"); } }
/// <summary> /// 用JWT套件解碼Token /// </summary> /// <param name="token"></param> /// <returns></returns> public static Token DecodeToken(string token) { try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, cKey, verify: true); var payload = serializer.Deserialize <Token>(json); return(payload); } catch (TokenExpiredException ex) { Log.Error(new Exception("Token has expired", ex)); } catch (SignatureVerificationException ex) { Log.Error(new Exception("Token has invalid signature", ex)); } return(null); }
/// <summary> /// 解密 /// </summary> public static Dictionary <string, object> Decode(string token, string key = null) { try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); var algorithm = new HMACSHA256Algorithm(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var json = decoder.Decode(token, key, verify: true); //json >> 轉dictionary Dictionary <string, object> res = JsonConvert.DeserializeObject <Dictionary <string, object> >(json); if ((DateTime)res["timeout"] < DateTime.Now) { throw new Exception("超過期限,需重新登入"); } res.Remove("timeout"); return(res); } catch (TokenExpiredException) { throw new Exception("超過期限"); } catch (SignatureVerificationException) { throw new Exception("驗證不符,可能被竄改"); } }
public static string Decode(string token) { try { token = NetCryptoHelper.DecryptAes(token, NetCryptoHelper.AesKey); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); var data = decoder.Decode(token, Secret, true); return(data); } catch (TokenExpiredException ex) { throw new Exception("登陆超时"); } catch (SignatureVerificationException ex) { throw new Exception("用户未登录"); } }
public HttpResponseMessage JieMi(string token) { var ajaxResult = new AjaxResult(); ajaxResult.State = "200"; ajaxResult.Message = "1获取数据成功!"; try { 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); var json = decoder.Decode(token, secret, verify: true);//token为之前生成的字符串 Console.WriteLine(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } return(new HttpResponseMessage { Content = new StringContent(ajaxResult.SerializeJson(), System.Text.Encoding.UTF8, "application/json") }); }