public static string BuildJwt(this object obj, string secret = null, long minutes = 60) { if (secret.IsNullOrWhiteSpace()) { secret = Secret; } try { var jwt = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret); foreach (var propertyInfo in obj.GetType().GetProperties()) { jwt.AddClaim(propertyInfo.Name.ToLower(), propertyInfo.GetValue(obj)); } jwt.AddClaim("expire", DateTime.Now.AddMinutes(minutes)); var token = jwt.Build(); return(token); } catch { return(null); } }
public AccessToken GenerateAccessToken(string userId, string clientId, string scope, double expiresInSeconds) { JwtBuilder encoder = new JwtBuilder().WithAlgorithm(new HMACSHA256Algorithm()).WithSecret(_secret).AddClaim("scope", scope); DateTimeOffset now = DateTimeOffset.UtcNow; encoder = encoder.AddClaim("iat", now.ToUnixTimeSeconds()); encoder = encoder.AddClaim("exp", now.AddSeconds(expiresInSeconds).ToUnixTimeSeconds()); if (!String.IsNullOrWhiteSpace(userId)) { encoder = encoder.AddClaim("sub", userId); } if (!String.IsNullOrWhiteSpace(clientId)) { encoder = encoder.AddClaim("cid", clientId); } AccessToken accessToken = new AccessToken(); accessToken.ExpiresIn = (long)expiresInSeconds; accessToken.Scope = scope; accessToken.TokenType = "bearer"; accessToken.Token = encoder.Build(); return(accessToken); }
public void Build_WithoutDependencies_Should_Throw_Exception() { var builder = new JwtBuilder(); Action buildWithoutDependencies = () => builder.Build(); buildWithoutDependencies.Should() .Throw <InvalidOperationException>("because a JWT can't be built without dependencies"); }
/// <summary> /// 获取jwtToken /// </summary> /// <param name="data"></param> /// <returns></returns> public static string GetJwtToken(Dictionary <string, string> data) { var tokenBuilder = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret); foreach (var keyValuePair in data) { tokenBuilder.AddClaim(keyValuePair.Key, keyValuePair.Value); } return(tokenBuilder.Build()); }
/// <summary> /// Encode object with secret /// </summary> /// <param name="secretToken"></param> /// <param name="objectToEncode"></param> /// <returns></returns> public OutputDto <string> Encode(string secretToken, object objectToEncode, DateTime?tokenExpireDate = null, IJwtAlgorithm algorithm = null) { try { //Add 1 hour of token expiration by default DateTimeOffset expireDate = DateTimeOffset.UtcNow.AddHours(1); //Add default algorithm if (algorithm == null) { algorithm = new HMACSHA256Algorithm(); } //Encode token var tokenBuilder = new JwtBuilder() .WithAlgorithm(algorithm) .WithSecret(secretToken) .AddClaim("content", objectToEncode); //Validate expire date if (tokenExpireDate.HasValue) { //Parse date to UTC expireDate = tokenExpireDate.Value.Kind != DateTimeKind.Utc ? tokenExpireDate.Value.ToUniversalTime() : tokenExpireDate.Value; tokenBuilder = tokenBuilder.AddClaim("exp", expireDate.ToUnixTimeSeconds()); } //Build token var token = tokenBuilder.Build(); //Validate token if (string.IsNullOrWhiteSpace(token)) { return(new OutputDto <string>(HttpStatusCode.Unauthorized, "The generated token is empty", null)); } if (tokenExpireDate.HasValue) { //Return converted Object return(new OutputDto <string>(token, HttpStatusCode.OK, ToUtc(expireDate.DateTime))); } else { return(new OutputDto <string>(token)); } } catch (Exception ex) { return(new OutputDto <string>(HttpStatusCode.Unauthorized, ex.ToString())); } }
private string Create(Dictionary <string, object> claims) { var tokenBuilder = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(_secret); foreach (var claim in claims) { tokenBuilder.AddClaim(claim.Key, claim.Value.ToString()); } return(tokenBuilder.Build()); }
public string BuildToken(IEnumerable <Claim> claims, int ExpireMinutes = 20) { var jb = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(Secret); foreach (var claim in claims) { jb.AddClaim(claim.Type, claim.Value); } var token = jb.Build(); return(token); }
public static string Generate(object _o, DateTime _exp) { var _builder = new JwtBuilder().WithAlgorithm(new HMACSHA256Algorithm()).WithSecret(m_secret); _builder = _builder.AddClaim("exp", new DateTimeOffset(_exp).ToUnixTimeSeconds()); foreach (var(_key, _val) in _o.json()) { if (_key == "exp") { throw new Exception("field name \"exp\" is invalid"); } _builder = _builder.AddClaim(_key, _val.to_str()); } return(_builder.Build()); }
public string Serialize(IDictionary <string, string> claims) { var exp = (DateTimeOffset.UtcNow + duration).ToUnixTimeSeconds(); var builder = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret) .AddClaim("exp", exp); foreach (var claim in claims) { builder = builder.AddClaim(claim.Key, claim.Value); } return(builder.Build()); }
private string GenerateToken(IDictionary <string, object> payload, string secret) { Guard.NotNull(payload, nameof(payload)); Guard.NotNullOrWhiteSpace(secret, nameof(secret)); var builder = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret); foreach (var claim in payload) { builder.AddClaim(claim.Key, claim.Value); } return(builder.Build()); }
public string CreateJwtToken(Dictionary <string, object> payloadItems, string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk") { var builder = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret) ; foreach (var item in payloadItems) { builder.AddClaim(item.Key, item.Value); } var token = builder.Build(); return(token); }
public static string CreateToken(List <ClaimModel> claims) { string secret = ConfigurationManager.AppSettings["token::salt"].ToString(); string tokenExp = ConfigurationManager.AppSettings["token::exp"].ToString(); var token = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(secret) .AddClaim("exp", DateTimeOffset.UtcNow.AddSeconds(Int32.Parse(tokenExp)).ToUnixTimeSeconds()); foreach (var claim in claims) { token.AddClaim(claim.Name, claim.Value); } return(token.Build()); }
public static string Encode(string secret, IDictionary <string, object> payload, JwtHashAlgorithm type = JwtHashAlgorithm.HS256) { HMACSHAAlgorithmFactory factory = new HMACSHAAlgorithmFactory(); IJwtAlgorithm algorithm = factory.Create(type); JWT.IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var builder = new JwtBuilder() .WithAlgorithm(algorithm) .WithSecret(secret); if (payload != null) { foreach (var key in payload.Keys) { builder = builder.AddClaim(key, payload[key]); } } var token = builder.Build(); return(token); }