예제 #1
0
        /// <summary>
        /// Generate a token for a user based on a known user
        /// </summary>
        /// <param name="identity">the user's identity and roles</param>
        /// <returns>a JWT token</returns>
        public static string GenerateTokenForUser(JWTAuthenticationIdentity identity)
        {
            var now = DateTime.UtcNow;
            var signingCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256Signature);

            var claimsIdentity = new ClaimsIdentity(new List <Claim>
            {
                new Claim("firstName", identity.FirstName),
                new Claim("lastName", identity.LastName),
                new Claim("userName", identity.UserName)
            }, identity.AuthenticationType);

            foreach (var role in identity.Roles)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));
            }

            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Audience           = Audience,
                Issuer             = Issuer,
                Subject            = claimsIdentity,
                SigningCredentials = signingCredentials,
                Expires            = now.AddMinutes(Timeout),
                IssuedAt           = now
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var plainToken            = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
예제 #2
0
        public static void SetUserIdentity(JWTAuthenticationIdentity identity)
        {
            var genericPrincipal = new GenericPrincipal(identity, identity.Roles.ToArray());

            Thread.CurrentPrincipal = genericPrincipal;
            var authenticationIdentity = Thread.CurrentPrincipal.Identity as JWTAuthenticationIdentity;

            if (!string.IsNullOrEmpty(authenticationIdentity?.UserName))
            {
                authenticationIdentity.UserName = identity.UserName;
                authenticationIdentity.Roles    = identity.Roles;
            }

            HttpContext.Current.User = authenticationIdentity;
        }