Example #1
0
        // Generate JWT [JSON Web Token]
        public static string GetToken(_VUser user)
        {
            var config = 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));
        }
Example #2
0
        // Read accessToken Claims and convert it to its Type [VUser]
        public static _VUser ToVUser(string accessToken)
        {
            // get claims from the access token string
            IEnumerable <Claim> claims = new JwtSecurityTokenHandler().ReadJwtToken(accessToken).Claims;
            _VUser vUser = new _VUser();
            // get all vUser Propperties
            var props = vUser.GetProperties();

            // loop through vUser props and set each prop value with the corresponding claim value
            foreach (var prop in props)
            {
                vUser.SetValue(prop.Name, claims.FirstOrDefault(c => c.Type == prop.Name).Value);
            }
            // finally return the fulfilled vUser object
            return(vUser);
        }