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 string EndcodeTokenWithJWT(User User, byte[] secretKey) { try { IDateTimeProvider provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var secondsSinceEpoch = UnixEpoch.GetSecondsSince(now.AddMinutes(30)); var payload = new Dictionary <string, object> { { "UserID", User.UserID }, { "RoleID", User.RoleID }, { "exp", secondsSinceEpoch } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // SHA256 Algorithm IJsonSerializer serializer = new JsonNetSerializer(); // Convert JSON IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); // Endcode Base 64 IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, secretKey); return(token); } catch { return(null); } }
private static string CreateToken(User user, out object dbUser) { var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var secondsSinceEpoch = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); var expiry = Math.Round((DateTime.UtcNow.AddYears(10) - unixEpoch).TotalSeconds); var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); var notBefore = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "username", user.UserName }, { "userId", user.User_Id }, { "nbf", notBefore }, { "iat", issuedAt }, { "exp", expiry } }; //var secret = ConfigurationManager.AppSettings.Get("jwtKey"); var secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; 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); dbUser = new { user.User_Id, user.UserName }; return(token); }
public static string GenerateToken() { var tokenInfo = new TokenInfo(); var payload = new Dictionary <string, object> { { "iss", tokenInfo.iss }, { "iat", tokenInfo.iat }, { "exp", tokenInfo.exp }, { "aud", tokenInfo.aud }, { "sub", tokenInfo.sub }, { "jti", tokenInfo.jti }, { "userName", "Tim" }, { "userID", "001" }, { "level", 18 } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, SecretKey); return(token); }
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); }
/// <summary> /// 创建token /// </summary> /// <param name="dic">用户信息</param> /// <returns></returns> public static string GenerateToken(Dictionary <string, object> dic, int timeout) { JWT.Builder.JwtBuilder b = new JWT.Builder.JwtBuilder(); string secret = ConfigHelper.GetConfigString("JWTSecret"); if (string.IsNullOrEmpty(secret)) { throw new Exception("Token密钥未设置!"); } if (timeout == 0) { timeout = 60; } //用户信息 var payload = dic; //过期时间 dic.Add("exp", UnixTimeStampUTC(DateTime.UtcNow.AddMinutes(timeout))); IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string token = encoder.Encode(payload, secret); return(token); }
public void TryValidate_Should_Return_False_And_Exception_Not_Null_When_Crypto_Matches_Signature() { var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new UtcDateTimeProvider(); var jwt = new JwtParts(TestData.Token); var payloadJson = JwtValidator.GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = JwtValidator.GetBytes(String.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(JwtValidator.GetBytes("ABC"), bytesToSign); signatureData[0]++; // malformed signature var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider); var isValid = jwtValidator.TryValidate(payloadJson, decodedCrypto, decodedSignature, out var ex); Assert.False(isValid); Assert.NotNull(ex); }
public string Generate(int userId, bool withLimitDate) { var secret = ConfigurationProvider.Get().TokenSecret; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJsonSerializer serializer = new JsonNetSerializer(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(new { idUsuario = userId, fechaCreacion = DateTime.Now }, secret); DateTime?limitDate = null; if (withLimitDate) { limitDate = DateTime.Now.AddHours(1); } Insert(new Model.Entity.UserToken() { Data = token, UserId = userId, LimitDate = limitDate, }); return(token); }
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); }
public void TryValidate_Should_Return_False_And_Exception_Not_Null_When_Token_Is_Expired() { var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new StaticDateTimeProvider(DateTimeOffset.FromUnixTimeSeconds(TestData.TokenTimestamp)); var jwt = new JwtParts(TestData.TokenWithExp); var payloadJson = GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = GetBytes(String.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(GetBytes(TestData.Secret), bytesToSign); var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider); var isValid = jwtValidator.TryValidate(payloadJson, decodedCrypto, decodedSignature, out var ex); isValid.Should() .BeFalse("because token should be invalid"); ex.Should() .NotBeNull("because invalid token should thrown exception"); ex.Should() .BeOfType(typeof(TokenExpiredException), "because expired token should thrown TokenExpiredException"); }
public void TryValidate_Should_Return_True_And_Exception_Null_When_Token_Is_Not_Yet_Usable_But_Validator_Has_Time_Margin() { var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new StaticDateTimeProvider(DateTimeOffset.FromUnixTimeSeconds(TestData.TokenTimestamp - 1)); var jwt = new JwtParts(TestData.TokenWithNbf); var payloadJson = GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = GetBytes(String.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(GetBytes(TestData.Secret), bytesToSign); var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider, timeMargin: 1); var isValid = jwtValidator.TryValidate(payloadJson, decodedCrypto, decodedSignature, out var ex); isValid.Should() .BeTrue("because token should be valid"); ex.Should() .BeNull("because valid token should not throw exception"); }
public void TryValidate_Should_Return_False_And_Exception_Not_Null_When_Signature_Is_Not_Valid() { var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new UtcDateTimeProvider(); var jwt = new JwtParts(TestData.Token); var payloadJson = GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = GetBytes(String.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(GetBytes(TestData.Secret), bytesToSign); ++signatureData[0]; // malformed signature var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider); var isValid = jwtValidator.TryValidate(payloadJson, decodedCrypto, decodedSignature, out var ex); isValid.Should() .BeFalse("because token should be invalid"); ex.Should() .NotBeNull("because invalid token should thrown exception"); }
/// <summary> /// 根据jwtToken 获取实体 /// </summary> /// <param name="token">jwtToken</param> /// <returns></returns> public static string GetJwtDecode(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); //token为之前生成的字符串 var userInfo = decoder.DecodeToObject(token, secret, verify: true); //此处json为IDictionary<string, object> 类型 string username = userInfo["username"].ToString(); //可获取当前用户名 DateTime timeout = (DateTime)userInfo["timeout"]; //获取token过期时间 if (timeout < DateTime.Now) { throw new TokenExpiredException("Token过期,请重新登陆"); } userInfo.Remove("timeout"); return("OK"); } catch (TokenExpiredException tokenEx) { return("[Error]Token过期:--" + tokenEx.Message); } catch (SignatureVerificationException tokenEx) { return("[Error] 无效的Token:--" + tokenEx.Message); } catch (Exception ex) { return("[Error]:" + ex.Message); } }
public void ProcessRequest(HttpContext context) { TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); int timestamp = (int)t.TotalSeconds; var payload = new Dictionary <string, object>() { { "iat", timestamp }, { "jti", System.Guid.NewGuid().ToString() } // { "name", currentUser.name }, // { "email", currentUser.email } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string token = encoder.Encode(payload, SHARED_KEY); string redirectUrl = "https://" + SUBDOMAIN + ".zendesk.com/access/jwt?jwt=" + token; string returnTo = context.Request.QueryString["return_to"]; if (returnTo != null) { redirectUrl += "&return_to=" + HttpUtility.UrlEncode(returnTo); } context.Response.Redirect(redirectUrl); }
public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim() { const string key = TestData.Key; const int timeDelta = -1; var algorithm = new HMACSHA256Algorithm(); var dateTimeProvider = new UtcDateTimeProvider(); var serializer = new JsonNetSerializer(); var validator = new JwtValidator(serializer, dateTimeProvider); var urlEncoder = new JwtBase64UrlEncoder(); var decoder = new JwtDecoder(serializer, validator, urlEncoder); var now = dateTimeProvider.GetNow(); var exp = UnixEpoch.GetSecondsSince(now.AddHours(timeDelta)); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(new { exp }, key); Action decodeExpiredJwt = () => decoder.DecodeToObject <Customer>(token, key, verify: true); decodeExpiredJwt.Should() .Throw <TokenExpiredException>("because decoding an expired token should raise an exception when verified"); }
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; } }
/// <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; } }
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"); } }
/// <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"); } }
public void TryValidate_Should_Return_True_And_Exception_Null_When_Crypto_Matches_Signature() { var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new UtcDateTimeProvider(); var jwt = new JwtParts(TestData.Token); var payloadJson = GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = GetBytes(string.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(GetBytes("ABC"), bytesToSign); var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider); var isValid = jwtValidator.TryValidate(payloadJson, decodedCrypto, decodedSignature, out var ex); isValid.Should() .BeTrue("because the token should have been validated"); ex.Should() .BeNull("because a valid token verified should not raise any exception"); }
public string encodeToken(string secret_key) { try { DateTimeOffset now = (DateTimeOffset)DateTime.UtcNow; var my_jsondata = new Dictionary <string, string> { { "TimeStamp", now.ToUnixTimeSeconds().ToString() } }; //Tranform it to Json object string json_data = JsonConvert.SerializeObject(my_jsondata); JObject json_object = JObject.Parse(json_data); var algorithm = new HMACSHA256Algorithm(); var urlEncoder = new JwtBase64UrlEncoder(); var serializer = new JsonNetSerializer(); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string token = encoder.Encode(json_object, secret_key); return(token); } catch (Exception ex) { return(ex.Message); } }
public void Validate_Should_Throw_Exception_When_Crypto_Does_Not_Match_Signature() { const string token = TestData.Token; var urlEncoder = new JwtBase64UrlEncoder(); var jsonNetSerializer = new JsonNetSerializer(); var utcDateTimeProvider = new UtcDateTimeProvider(); var jwt = new JwtParts(token); var payloadJson = GetString(urlEncoder.Decode(jwt.Payload)); var crypto = urlEncoder.Decode(jwt.Signature); var decodedCrypto = Convert.ToBase64String(crypto); var alg = new HMACSHA256Algorithm(); var bytesToSign = GetBytes(string.Concat(jwt.Header, ".", jwt.Payload)); var signatureData = alg.Sign(GetBytes("ABC"), bytesToSign); ++signatureData[0]; // malformed signature var decodedSignature = Convert.ToBase64String(signatureData); var jwtValidator = new JwtValidator(jsonNetSerializer, utcDateTimeProvider); Action validateJwtWithBadSignature = () => jwtValidator.Validate(payloadJson, decodedCrypto, decodedSignature); validateJwtWithBadSignature.Should() .Throw <SignatureVerificationException>("because the signature does not match the crypto"); }
public IHttpActionResult login([FromBody] LoginRequest request) { try { if ((request != null) && repository.checkUser(request.userName)) { if (repository.checkPass(request.userName, request.password)) { AuthInfo info = new AuthInfo { userName = request.userName, role = "admin", id = 1 }; const string secret = "easy clinic managemet system"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(info, secret); return(Ok(token)); } else { return(Content(HttpStatusCode.Unauthorized, "Password or username is not correct")); } } else { return(Content(HttpStatusCode.Unauthorized, "User cannot be found.")); } } catch (Exception exc) { return(Content(HttpStatusCode.InternalServerError, exc.Message)); } }
public Token CreateToken(Usuario usuario) { var today = DateTime.Now; var payload = new Dictionary <string, object> { { "IdUsuario", usuario.Id }, { "IdEscuela", usuario.IdEscuela }, { "exp", today.AddHours(12) } }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var tokenString = encoder.Encode(payload, secret); Token token = new Token(); token.Nombre = tokenString; token.IdEscuela = usuario.IdEscuela; token.IdUsuario = usuario.Id; token.FechaCrea = today; token.Id = usuario.Id; db.Token.Add(token); db.SaveChanges(); return(token); }
/// <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("驗證不符,可能被竄改"); } }
/// <summary> /// Generate GWT token /// </summary> /// <returns></returns> private string GetJwt() { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var payLoad = new Dictionary <string, object> { { "iss", "" }, { "aud", "" }, { "iat", DateTime.UtcNow.AddSeconds(-_jwtDelay) }, { "nbf", DateTime.UtcNow.AddSeconds(-_jwtDelay) }, //Add 2 hours of expiration { "exp", Math.Round(new TimeSpan(DateTime.UtcNow.AddSeconds(_jwtDelay).Ticks).TotalSeconds - new TimeSpan(epoch.Ticks).TotalSeconds) }, { "jti", _publicKey } }; if (!string.IsNullOrWhiteSpace(EncryptKey)) { payLoad.Add("file_encryption_key", EncryptKey); } IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payLoad, _privateKey); return(token); }
public HttpResponseMessage GetToken() { var ajaxResult = new AjaxResult(); ajaxResult.State = "200"; var payload = new Dictionary <string, object> { { "claim1", 0 }, { "claim2", "claim2-value" }, { "userName", "admin" }, { "roles", "model1,model2,btn1,btn2" }, { "timeout", "2018-08-03" } }; 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); ajaxResult.Message = token; return(new HttpResponseMessage { Content = new StringContent(ajaxResult.SerializeJson(), System.Text.Encoding.UTF8, "application/json") }); }
public JArray getAsset() { string url = ac.BASE_URL + "accounts"; var payload = new Dictionary <string, object> { { "access_key", access_key }, { "nonce", Guid.NewGuid().ToString() }, }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); string token = encoder.Encode(payload, secret_key); string authorize_token = "Bearer " + token; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Headers.Add(string.Format("Authorization:{0}", authorize_token)); try { WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); return(JArray.Parse(reader.ReadToEnd())); } catch { return(null); } }
public static string CreateToken(User user) { var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expiry = Math.Round((DateTime.UtcNow.AddHours(2) - unixEpoch).TotalSeconds); var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); var notBefore = Math.Round((DateTime.UtcNow.AddMonths(6) - unixEpoch).TotalSeconds); var payload = new Dictionary <string, object> { { "username", user.UserName }, { "nbf", notBefore }, { "iat", issuedAt }, { "exp", expiry } }; //var secret = ConfigurationManager.AppSettings.Get("jwtKey"); const string apikey = "secretKey"; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, apikey); //var token = JsonWebToken.Encode(payload, apikey, JwtHashAlgorithm.HS256); return(token); }