Ejemplo n.º 1
0
        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);
            }
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        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");
        }
Ejemplo n.º 4
0
        /// <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());
        }
Ejemplo n.º 5
0
        /// <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()));
            }
        }
Ejemplo n.º 6
0
        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());
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
0
        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());
        }
Ejemplo n.º 9
0
        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());
        }
Ejemplo n.º 10
0
        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());
        }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
        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());
        }
Ejemplo n.º 13
0
        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);
        }