private static string GetToken() { var user = FormulaHelper.GetUserInfo(); var token = ""; var secretKey = String.IsNullOrEmpty(ConfigurationManager.AppSettings["SecretKey"]) ? String.Empty : ConfigurationManager.AppSettings["SecretKey"]; if (!String.IsNullOrEmpty(secretKey)) { var dic = new Dictionary <string, object>(); dic["systemName"] = user.Code; var expiredTimeSpan = 1; if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["ExpiredTimeSpan"])) { var timeSpan = ConfigurationManager.AppSettings["ExpiredTimeSpan"]; if (System.Text.RegularExpressions.Regex.IsMatch(timeSpan, "^[1-9]\\d*$")) { expiredTimeSpan = Convert.ToInt32(timeSpan); } } var jwtcreatedOver = Math.Round((DateTime.UtcNow.AddMinutes(expiredTimeSpan) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5); dic["exp"] = jwtcreatedOver;// 指定token的生命周期。unix时间戳格式 IJwtAlgorithm algorithm = new HMACSHA512Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); token = encoder.Encode(dic, secretKey); } return(token); }
public static string Encode(Dictionary <string, object> payload, string secret, JwtHashAlgorithm alg) { IJwtAlgorithm algorithm; switch (alg) { case JwtHashAlgorithm.HS256: algorithm = new HMACSHA256Algorithm(); break; case JwtHashAlgorithm.HS384: algorithm = new HMACSHA384Algorithm(); break; case JwtHashAlgorithm.HS512: algorithm = new HMACSHA512Algorithm(); break; default: algorithm = new HMACSHA256Algorithm(); break; } IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(payload, secret)); }
private void metroButtonGenerateJey_Click(object sender, EventArgs e) { try { if (metroTextBoxEncryptionKey.Text != string.Empty && metroTextBoxEncryptionKey.Enabled == true) { encryptionkey = metroTextBoxEncryptionKey.Text.ToString(); } else if (metroCheckBoxUseDefault.Checked) { encryptionkey = "KwkQ37eYtFJ94mpsuoWuyVph5vLpDmeX9FYFsSLqsUTzMvyeW2dZcN7PW2eQKJzQEDJ9JDL3LpKki9eDtDkDDHgiyroMNb7zcfysdXat"; } else { encryptionkey = null; } IJwtAlgorithm algorithm; if (metroComboBoxHashingAlgorithm.SelectedItem.ToString() == "HS256") { algorithm = new HMACSHA256Algorithm(); } else if (metroComboBoxHashingAlgorithm.SelectedItem.ToString() == "HS384") { algorithm = new HMACSHA384Algorithm(); } else if (metroComboBoxHashingAlgorithm.SelectedItem.ToString() == "HS512") { algorithm = new HMACSHA512Algorithm(); } else if (metroComboBoxHashingAlgorithm.SelectedItem.ToString() == "RS256") { algorithm = new HMACSHA256Algorithm(); } else { algorithm = new HMACSHA256Algorithm(); } var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(encryptionkey)); var secToken = new JwtSecurityToken( signingCredentials: new SigningCredentials(securityKey, metroComboBoxHashingAlgorithm.SelectedItem.ToString()), issuer: "JWT Manager (https://github.com/sajeebchandan/JWTManager)", audience: "JWT Manager (https://github.com/sajeebchandan/JWTManager)", claims: payload, expires: DateTime.UtcNow.AddDays(30)); var handler = new JwtSecurityTokenHandler(); JWT _JWT = new JWT(handler.WriteToken(secToken)); _JWT.ShowDialog(); } catch (Exception ex) { MetroFramework.MetroMessageBox.Show(this, "One or more field required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public JwTToken() { IJwtAlgorithm algorithm = new HMACSHA512Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider datetimeProvider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, datetimeProvider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); encoder = new JwtEncoder(algorithm, serializer, urlEncoder); decoder = new JwtDecoder(serializer, urlEncoder); SecretKey = ""; }
public Task <UserResolverResult> GetUserOrDefault(string authToken, Guid correlationId, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(authToken)) { return(Task.FromResult(new UserResolverResult(UserAuthStatus.NoUser))); } try { IJsonSerializer serializer = new JsonNetSerializer(); var provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtAlgorithm algorithm = new HMACSHA512Algorithm(); // symmetric IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); var userDict = decoder.DecodeToObject <Dictionary <string, object> >(authToken, _userResolverSecret.GetSecret(), verify: true); var user = new UserInformation { Username = userDict.GetValueOrDefault("sub")?.ToString(), Roles = ((JArray)userDict.GetValueOrDefault("roles")).Select(x => x.ToString()).ToArray(), Claims = userDict, UserIdentifier = userDict.GetValueOrDefault("uid")?.ToString(), Expiration = userDict.ContainsKey("exp") ? DateTimeOffset.FromUnixTimeSeconds((long)userDict["exp"]) : (DateTimeOffset?)null, AuthenticatedAt = DateTimeOffset.FromUnixTimeSeconds((long)userDict["iat"]) }; return(Task.FromResult(new UserResolverResult(UserAuthStatus.Valid, user))); } catch (TokenExpiredException) { _logger.LogInformation($"TokenExpired for CorrelationId:{correlationId}"); return(Task.FromResult(new UserResolverResult(UserAuthStatus.Expired))); } catch (SignatureVerificationException ex) { _logger.LogError($"SignatureVerificationException for CorrelationId:{correlationId}", ex); return(Task.FromResult(new UserResolverResult(UserAuthStatus.Invalid))); } catch (Exception ex) { _logger.LogError($"General Exception for CorrelationId:{correlationId}", ex); return(Task.FromResult(new UserResolverResult(UserAuthStatus.Invalid))); } }
public const string SECRETKEY = "jwttest"; //加密的密钥 /// <summary> /// 使用自定义密钥加密,HS512签名 /// </summary> /// <param name="strSecretKey">密钥</param> /// <param name="strJson">需要加密的JSON</param> /// <returns></returns> public static string EncodeByJwt(string strSecretKey, string strJson) { try { var payload = new Dictionary <string, object> { { "Crypt", strJson } }; IJwtAlgorithm algorithm = new HMACSHA512Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var token = encoder.Encode(payload, strSecretKey); return(token); } catch (Exception ex) { throw; } }