예제 #1
0
        public async Task <AccessTokenResponse> GenerateEncodedToken(User user, IList <string> roles = null)
        {
            string id       = user.Id;
            string userName = user.UserName;
            string name     = user.Name;

            var identity = GenerateClaimsIdentity(id, userName);
            var claims   = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim("name", name),
                new Claim("roles", roles.IsNullOrEmpty() ? "" : String.Join(",", roles)),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
            };

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new AccessTokenResponse(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #2
0
        public async Task <AccessToken> GenerateEncodedToken(string id, string userName, int?tenantId)
        {
            var identity = generateClaimsIdentity(id, userName);

            _unitOfWorkManager.Current.DisableFilter(HozaruDataFilters.MayHaveTenant);
            _unitOfWorkManager.Current.DisableFilter(HozaruDataFilters.MustHaveTenant);
            _unitOfWorkManager.Current.EnableFilter(HozaruDataFilters.MayHaveTenant);
            using (_unitOfWorkManager.Current.SetFilterParameter(HozaruDataFilters.MayHaveTenant, HozaruDataFilters.Parameters.TenantId, tenantId))
            {
                var user = await _userManager.FindByNameAsync(userName);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, userName),
                    new Claim(HozaruClaimTypes.TenantId, user.TenantId.ToString()),
                    new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                    new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                    identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Rol),
                    identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Id)
                };

                var jwt = new JwtSecurityToken(
                    _jwtOptions.Issuer,
                    _jwtOptions.Audience,
                    claims,
                    _jwtOptions.NotBefore,
                    _jwtOptions.Expiration,
                    _jwtOptions.SigningCredentials);

                return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
            }
        }
예제 #3
0
        public async Task <AccessToken> GenerateEncodedToken(string id, string userName, User user)
        {
            var identity = GenerateClaimsIdentity(id, userName);

            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
            };

            foreach (var role in user.Roles)
            {
                claims.Add(new Claim("role", role));
            }

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #4
0
파일: JwtFactory.cs 프로젝트: MSH/PViMS-2
        public async Task <AccessToken> GenerateEncodedToken(User userFromRepo, IList <string> roles)
        {
            var identity = GenerateClaimsIdentity(userFromRepo.IdentityId, userFromRepo.UserName, userFromRepo.UserType);

            List <Claim> claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, userFromRepo.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Email, userFromRepo.Email),
                new Claim(JwtRegisteredClaimNames.GivenName, $"{userFromRepo.FirstName} {userFromRepo.LastName}"),
                new Claim(JwtRegisteredClaimNames.UniqueName, userFromRepo.Id.ToString()),
                identity.FindFirst(JwtConstants.Strings.JwtClaimIdentifiers.Rol),
                identity.FindFirst(JwtConstants.Strings.JwtClaimIdentifiers.Id),
                identity.FindFirst(JwtConstants.Strings.JwtClaimIdentifiers.UserType)
            };

            roles.ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));
            userFromRepo.Facilities.ForEach(dto => claims.Add(new Claim(ClaimTypes.NameIdentifier, dto.Facility.FacilityName)));

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(_jwtOptions.Issuer, _jwtOptions.Audience,
                                           claims, _jwtOptions.NotBefore, _jwtOptions.Expiration,
                                           _jwtOptions.SigningCredentials);

            return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
        public async Task <AccessToken> GenerateEncodedTokenAsync(string id, string userName, string appUserId)
        {
            var identity = GenerateClaimsIdentity(id, userName, appUserId);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sid, id),
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtIssuerOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtIssuerOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(CustomClaimIdentifiers.Rol),
                identity.FindFirst(CustomClaimIdentifiers.Id),
                identity.FindFirst(CustomClaimIdentifiers.AppUserId)
            };

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtIssuerOptions.Issuer,
                _jwtIssuerOptions.Audience,
                claims,
                _jwtIssuerOptions.NotBefore,
                _jwtIssuerOptions.Expiration,
                _jwtIssuerOptions.SigningCredentials);

            return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtIssuerOptions.ValidFor.TotalSeconds));
        }
예제 #6
0
        public async Task <AccessTokenDTO> GenerateEncodedToken(string id, string userName, IList <string> userRoles)
        {
            var identity = GenerateClaimsIdentity(id, userName);

            var roleClaims = userRoles.Select(x => new Claim("roles", x)).ToArray();

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id),
            };

            var combinedClaims = new Claim[roleClaims.Length + claims.Length];

            Array.Copy(claims, combinedClaims, claims.Length);
            Array.Copy(roleClaims, 0, combinedClaims, claims.Length, roleClaims.Length);


            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                combinedClaims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);



            return(new AccessTokenDTO(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #7
0
        public async Task <AccessToken> GenerateEncodedToken(string id, string email)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Iss, _jwtOptions.Issuer),
                new Claim(JwtRegisteredClaimNames.Sub, id),
                new Claim(JwtRegisteredClaimNames.Aud, _jwtOptions.Audience),
                new Claim(JwtRegisteredClaimNames.Exp,
                          ToUnixExpDate(_jwtOptions.IssuedAt, _jwtOptions.ValidFor).ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                          ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Email, email),
                new Claim(Constants.Strings.JwtClaimIdentifiers.UserId, id),
                new Claim(ClaimTypes.NameIdentifier, id),
                new Claim(ClaimTypes.Email, email),
            };
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #8
0
        public string EncodeToken(string userName)
        {
            var claims = CreateJwtClaims(userName);
            var jwt    = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expires,
                _jwtOptions.SigningCredentials);
            var token = _jwtTokenHandler.WriteToken(jwt);

            return(token);
        }
예제 #9
0
        public async Task <AccessToken> GenerateEncodedToken(string id, string userName)
        {
            // Create the JWT security token and encode it.
            var claims = await GetValidClaims(userName);

            var jwt = new JwtSecurityToken(
                jwtOptions.Issuer,
                jwtOptions.Audience,
                claims,
                jwtOptions.NotBefore,
                jwtOptions.Expiration,
                jwtOptions.SigningCredentials);

            return(new AccessToken(jwtTokenHandler.WriteToken(jwt), (int)jwtOptions.ValidFor.TotalSeconds));
        }
예제 #10
0
        public string GenerateEncodedToken(int userId)
        {
            var claims = new[]
            {
                // adding only id for simplicity
                new Claim(ClaimsEnum.userId.ToString(), userId.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
            };

            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(_jwtTokenHandler.WriteToken(jwt));
        }
예제 #11
0
        public async Task <AccessTokenDTO> GenerateEncodedToken(string id, string userName, string[] roles)
        {
            var identity = GenerateClaimsIdentity(id, userName);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                new Claim(ClaimTypes.Email, userName),
                new Claim(JwtRegisteredClaimNames.Iss, _jwtOptions.Issuer),
                identity.FindFirst(Constants.Strings.JwtClaimIdentifiers.Id)
            };

            List <string> audiences = new List <string>();

            // add role claims
            roles.ToList().ForEach(role =>
            {
                if (Enum.TryParse(value: role, ignoreCase: true, out Permission permission))
                {
                    claims.Add(new Claim(ClaimTypes.Role, permission.GetValue().ToString()));
                    audiences.Add(permission.GetAudience()); // separate audiences
                }
            });
            // add audience claims related to permissions
            claims.AddRange(audiences.Distinct()
                            .Select(audience => new Claim(JwtRegisteredClaimNames.Aud, audience)));

            claims.AddRange(roles.Where(d => Enum.TryParse <Permission>(d, ignoreCase: true, out _))
                            .Select(role => new Claim(ClaimTypes.Role, EnumInfo.GetValue <Permission>(role).ToString())));
            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            return(new AccessTokenDTO(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #12
0
        public async Task <AccessToken> GenerateEncodedToken(string userName)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64)
            };

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new AccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }
예제 #13
0
        public async Task <JwtAccessToken> GenerateEncodedAccessToken(User user)
        {
            var claims = await GenerateClaimsIdentity(user);

            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Key));
            var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
            var jwtSecurityToken     = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                notBefore: _jwtSettings.NotBefore,
                expires: _jwtSettings.AccessTokenExpiration,
                signingCredentials: signingCredentials);

            return(new JwtAccessToken()
            {
                ExpiredAt = (long)_jwtSettings.AccessTokenValidFor.TotalSeconds,
                Token = _jwtTokenHandler.WriteToken(jwtSecurityToken),
            });
        }
예제 #14
0
        public async Task <string> GenerateEncodedToken(User user)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtIssuerOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtIssuerOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                new Claim("rol", user.Role),
                new Claim("id", user.IdentityId)
            };

            var jwt = new JwtSecurityToken(
                _jwtIssuerOptions.Issuer,
                _jwtIssuerOptions.Audience,
                claims,
                _jwtIssuerOptions.NotBefore,
                _jwtIssuerOptions.Expiration,
                _jwtIssuerOptions.SigningCredentials);

            return(_jwtTokenHandler.WriteToken(jwt));
        }
예제 #15
0
        public string BuildToken(string user, string issuer, string audience)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (issuer == null)
            {
                throw new ArgumentNullException(nameof(issuer));
            }
            if (audience == null)
            {
                throw new ArgumentNullException(nameof(audience));
            }

            var credentials = _credentialHandler.SigningCredentials();

            var writeToken = _jwtTokenHandler.WriteToken(user, issuer, audience, credentials);

            return(writeToken);
        }
예제 #16
0
        public async Task <JwtAccessToken> GenerateEncodedToken(IEnumerable <JwtTokenClaim> userClaims, string refreshToken)
        {
            var claims = new List <Claim>
            {
                new Claim("rol", "sc_ms_api_access"),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                          ClaimValueTypes.Integer64)
            };

            claims.AddRange(userClaims.Select(userClaim => new Claim(userClaim.Name, userClaim.Value)));

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                //_jwtOptions.Audience,
                null,
                claims.ToArray(),
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new JwtAccessToken(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds, refreshToken));
        }
예제 #17
0
        public async Task <AccessTokenDto> GenerateEncodedToken(User user)
        {
            var identity = GenerateClaimsIdentity(user);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst(Helper.Constants.Strings.JwtClaimIdentifiers.Rol),
                identity.FindFirst(Helper.Constants.Strings.JwtClaimIdentifiers.Id),
                identity.FindFirst(Helper.Constants.Strings.JwtClaimIdentifiers.FullName),
            };

            var jwt = new JwtSecurityToken(
                _jwtOptions.Issuer,
                _jwtOptions.Audience,
                claims,
                _jwtOptions.NotBefore,
                _jwtOptions.Expiration,
                _jwtOptions.SigningCredentials);

            return(new AccessTokenDto(_jwtTokenHandler.WriteToken(jwt), (int)_jwtOptions.ValidFor.TotalSeconds));
        }