Esempio n. 1
0
        public JsonWebToken Create(JwtUserDto userDto, string[] userRole)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey));

            var now = DateTime.UtcNow;

            var genericIdentity = BuildClaims(userDto, userRole);

            var expires = now.AddMinutes(_jwtOptions.ExpiryMinutes);

            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                claims: genericIdentity.Claims,
                notBefore: now,
                expires: expires,
                audience: _jwtOptions.Audience,
                signingCredentials: _signingCredentials
                );

            var token = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new JsonWebToken
            {
                AccessToken = token,
                Identity = genericIdentity.Identity,
                Claims = genericIdentity.Claims.ToDictionary(p => p.Type, p => p.Value),
                Expires = ToTimestamp(expires),
                Id = userDto.Id,
                RefreshToken = string.Empty,
            });
        }
Esempio n. 2
0
        private static GenericPrincipal BuildClaims(JwtUserDto userDto, string[] userRole)
        {
            var claimsIdentity = new ClaimsIdentity("password", ClaimTypes.Name, "AuthApiPolicy");
            var now            = DateTime.UtcNow;

            claimsIdentity.AddClaims(new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, userDto.Id),
                new Claim(JwtRegisteredClaimNames.GivenName, userDto.FirstName),
                new Claim(JwtRegisteredClaimNames.FamilyName, userDto.LastName),
                new Claim(JwtRegisteredClaimNames.UniqueName, userDto.Id),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, ToTimestamp(now).ToString()),
            });

            if (userRole != null)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, string.Join(",", userRole)));
            }

            var genericPrincipal = new GenericPrincipal(claimsIdentity, userRole);

            return(genericPrincipal);
        }