예제 #1
0
        /// <summary>
        /// Generates an encrypted token with the given model.
        /// </summary>
        /// <param name="model"></param>
        public string GenerateToken(TokenModel tokenModel)
        {
            if (tokenModel is null || tokenModel.IsEmpty)
            {
                throw new ArgumentException("Provided arguments for token creation are invalid.");
            }

            var claimsBuilder   = new ClaimsBuilder();
            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claimsBuilder.GetClaims(tokenModel)),
                Expires            = DateTime.UtcNow.AddMinutes(_settings.ExpireMinutes),
                SigningCredentials = new SigningCredentials(GetSecurityKey(_settings.SecretKey), _settings.SecurityAlgorithm)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
예제 #2
0
        public ClaimsIdentity Build(string authenticationType, string userAccountName, AccountType accountType)
        {
            if (string.IsNullOrWhiteSpace(authenticationType))
            {
                throw new ArgumentException("Authentication type cannot be null or empty.", nameof(authenticationType));
            }
            if (string.IsNullOrWhiteSpace(userAccountName))
            {
                throw new ArgumentException("User account name cannot be null or empty.", nameof(userAccountName));
            }

            IUser user = userService.GetUser(userAccountName, accountType);

            if (user == null)
            {
                throw new AuthenticationException($"Invalid user '{userAccountName}'.");
            }
            if (user.IsDisabled)
            {
                throw new AuthenticationException($"User '{userAccountName}' is disabled.");
            }

            var claimsBuilder = new ClaimsBuilder();

            claimsBuilder
            .SetId(user.Id)
            .SetName(user.Name)
            .SetAccountName(userAccountName);

            SetUserCustomPropertyClaims(user, claimsBuilder);
            SetUserOrganizationClaims(user, claimsBuilder);
            SetUserGroupClaims(user, claimsBuilder);
            SetUserRoleAndPermissionClaims(user, claimsBuilder);

            var identity = new ClaimsIdentity(authenticationType);

            identity.AddClaims(claimsBuilder.GetClaims());

            return(identity);
        }