示例#1
0
        /// <summary>
        /// Create a Jwt with user information
        /// </summary>
        /// <param name="user"></param>
        /// <param name="dbUser"></param>
        /// <returns></returns>
        public static string CreateToken(User user, int tokenExpirationMinutes = 60)
        {
            var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var expiry    = Math.Round((DateTime.UtcNow.AddMinutes(tokenExpirationMinutes) - 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>
            {
                { "email", user.email },
                { "userId", user.id },
                { "role", string.Join(",", user.Roles.Select(r => r.name)) },
                { "sub", user.id },
                { "nbf", notBefore },
                { "iat", issuedAt }
            };

//#if !DEBUG
            payload.Add("exp", expiry);
//#endif

            var secret = Properties.Settings.Default.jwtKey;             //secret key
            //dbUser = new { user.email, user.id };
            var token = JWTUtilities.Encode(payload, secret, JwtHashAlgorithm.HS256);

            return(token);
        }
示例#2
0
        /// <summary>
        /// Get the userid from the token if the token is not expired
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public int?GetUserIdFromToken(string token)
        {
            string key = Properties.Settings.Default.jwtKey;

            var    decodedToken = JWTUtilities.Decode(token, key);
            var    data = JsonConvert.DeserializeObject <Dictionary <string, object> >(decodedToken);
            object userId, exp;

            data.TryGetValue("userId", out userId);
            data.TryGetValue("exp", out exp);
            if (exp != null)
            {
                var validTo = FromUnixTime(long.Parse(exp.ToString()));
                if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                {
                    return(null);
                }
            }
            return(Convert.ToInt32(userId));
        }
示例#3
0
        private static ClaimsPrincipal ValidateToken(string token, string secret, bool checkExpiration)
        {
            var payloadJson = JWTUtilities.Decode(token, secret);
            var payloadData = JsonConvert.DeserializeObject <Dictionary <string, object> >(payloadJson);


            object exp;

            if (payloadData != null && (checkExpiration && payloadData.TryGetValue("exp", out exp)))
            {
                var validTo = FromUnixTime(long.Parse(exp.ToString()));
                //Disable token expiration check

                /*if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                 * {
                 *      throw new Exception(
                 *              string.Format("Token is expired. Expiration: '{0}'. Current: '{1}'", validTo, DateTime.UtcNow));
                 * }*/
            }

            var subject = new ClaimsIdentity("Federation", ClaimTypes.Name, ClaimTypes.Role);

            var claims = new List <Claim>();

            if (payloadData != null)
            {
                foreach (var pair in payloadData)
                {
                    var claimType = pair.Key;

                    var source = pair.Value as ArrayList;

                    if (source != null)
                    {
                        claims.AddRange(from object item in source
                                        select new Claim(claimType, item.ToString(), ClaimValueTypes.String));

                        continue;
                    }

                    switch (pair.Key)
                    {
                    case "name":
                        claims.Add(new Claim(ClaimTypes.Name, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    case "surname":
                        claims.Add(new Claim(ClaimTypes.Surname, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    case "email":
                        claims.Add(new Claim(ClaimTypes.Email, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    case "role":
                        claims.Add(new Claim(ClaimTypes.Role, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    case "userId":
                        claims.Add(new Claim(ClaimTypes.UserData, pair.Value.ToString(), ClaimValueTypes.Integer));
                        break;

                    default:
                        claims.Add(new Claim(claimType, pair.Value.ToString(), ClaimValueTypes.String));
                        break;
                    }
                }
            }

            subject.AddClaims(claims);
            return(new ClaimsPrincipal(subject));
        }