Esempio n. 1
0
        // Generate JWT [JSON Web Token]
        public static string GetToken(UserView user)
        {
            var config = BaseHelpers.GetService <IConfiguration>();
            // get the secret string
            var secret = GetSecretKey();
            // hashing the secret string
            var creds = new SigningCredentials(secret, SecurityAlgorithms.HmacSha256);
            // get the token Lifetime in hours
            int hours = config.GetValue <int>("JWT:Lifetime");
            // get all user properties excluding any [Type = Collection]
            // then return new Collection<Claims> [ holding KeyValue pair of each User Property ]
            var claims = user.GetProperties()
                         .Where(property => !property.PropertyType.FullName.Contains("Collections"))
                         .Select(property => new Claim(property.Name, (property.GetValue(user) != null) ? property.GetValue(user).ToString() : ""));
            // Create Token with Token Options
            var token = new JwtSecurityToken(
                issuer: config.GetValue <string>("JWT:Issuer"),
                audience: config.GetValue <string>("JWT:Audience"),
                claims: claims,
                expires: DateTime.UtcNow.AddHours(hours),
                signingCredentials: creds);

            // finally return the Token String
            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Esempio n. 2
0
        // A Function to return new TokenValidationParameters object
        public static TokenValidationParameters GetTokenValidationOptions(bool validateLifetime)
        {
            var config = BaseHelpers.GetService <IConfiguration>();

            return(new TokenValidationParameters
            {
                ValidateLifetime = validateLifetime,
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = config.GetValue <string>("JWT:Issuer"),
                ValidAudience = config.GetValue <string>("JWT:Audience"),
                IssuerSigningKey = GetSecretKey()
            });
        }
Esempio n. 3
0
        // get SecretKey from appsettings.json file
        public static SymmetricSecurityKey GetSecretKey()
        {
            string secret = BaseHelpers.GetService <IConfiguration>().GetValue <string>("SecretKey"); // "appsettings.json".GetJsonValue<AppSettings>("SecretKey");

            return(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)));
        }