예제 #1
0
        public string GenerateToken(ContextUserDTO user, double?minutesExpiration = null)
        {
            try
            {
                TokenConfigurationsDTO _tokenConfigurations =
                    _configuration.GetSection("TokenConfigurations")
                    ?.Get <TokenConfigurationsDTO>();

                if (_tokenConfigurations == null)
                {
                    throw new ArgumentNullException("Não foi possível encontrar as configurações do Token JWT.");
                }

                JwtSecurityTokenHandler _tokenHandler = new JwtSecurityTokenHandler();
                byte[] _key = Encoding.ASCII.GetBytes(_tokenConfigurations.Secret);

                SecurityTokenDescriptor _tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = _serviceAuth.GetClaimsIdentityByContextUser(user),
                    Expires            = DateTime.UtcNow.AddMinutes(minutesExpiration ?? _tokenConfigurations.ExpiresIn),
                    NotBefore          = DateTime.UtcNow,
                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(_key),
                        SecurityAlgorithms.HmacSha256Signature)
                };

                SecurityToken _generatedToken = _tokenHandler.CreateToken(_tokenDescriptor);

                return(_tokenHandler.WriteToken(_generatedToken));
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #2
0
        public async Task AlterarSenha(AlterarSenhaUsuarioViewModel alterarSenha)
        {
            ContextUserDTO _loggedUser   = _facadeAuth.GetLoggedUser();
            Usuario        _autenticacao = _repository.GetByUserName(_loggedUser.UserName);

            if (!_autenticacao.IsExpiredPassword())
            {
                SignInResult _senhaAntigaResult = await _signInManager.CheckPasswordSignInAsync(_autenticacao, alterarSenha.SenhaAntiga, false);

                if (!_senhaAntigaResult.Succeeded)
                {
                    throw new ApiException(ApiErrorCodes.SENANTINV, nameof(alterarSenha.SenhaAntiga));
                }
            }

            await ValidatePassword(alterarSenha.NovaSenha, alterarSenha.ConfirmacaoNovaSenha, _autenticacao);

            IdentityResult changePasswordResult = await _userManager.ChangePasswordAsync(_autenticacao,
                                                                                         alterarSenha.SenhaAntiga,
                                                                                         alterarSenha.NovaSenha);

            _autenticacao.SetUnexpirablePassword();

            if (!changePasswordResult.Succeeded || !_uow.Commit())
            {
                throw new ApiException(ApiErrorCodes.ERALTSEIDNT);
            }
        }
예제 #3
0
        public void SetLoggedUserAllowedInHasPermissionPolicyChallenge()
        {
            ContextUserDTO _loggedUser = GetLoggedUser();

            _loggedUser.IsAllowedInHasPermissionPolicyChallenge = true;

            SetUserToCurrentHTTPContext(_loggedUser);
        }
예제 #4
0
        public void SetUserToCurrentHTTPContext(ContextUserDTO user, string authenticationType = null)
        {
            if (user == null)
            {
                throw new ApiException(ApiErrorCodes.INVUSU);
            }

            _httpContextAccessor.HttpContext.User =
                new GenericPrincipal(GetClaimsIdentityByContextUser(user, authenticationType), new string[] { "" });
        }
예제 #5
0
        private string GenerateTokenByAutenticacao(Usuario autenticacao)
        {
            ContextUserDTO _contextUser = new ContextUserDTO(id: autenticacao.Id.ToString(),
                                                             userName: autenticacao.UserName,
                                                             name: autenticacao.Nome,
                                                             profile: string.Join(";", autenticacao.Perfil.Key));

            string _generatedToken = _facadeToken.GenerateToken(_contextUser);

            return(_generatedToken);
        }
예제 #6
0
        public ClaimsIdentity GetClaimsIdentityByContextUser(ContextUserDTO contextUser, string authenticationType = "Bearer")
        {
            ClaimsIdentity _claims = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.PrimarySid, contextUser.Id ?? string.Empty),
                new Claim(ClaimTypes.NameIdentifier, contextUser.UserName ?? string.Empty),
                new Claim(ClaimTypes.Name, contextUser.Name ?? string.Empty),
                new Claim(ClaimTypes.Role, contextUser.Profile ?? string.Empty),
                new Claim(CustomClaimTypes.IsAllowedInHasPermissionPolicyChallenge, contextUser.IsAllowedInHasPermissionPolicyChallenge.ToString()),
                new Claim(CustomClaimTypes.OriginalUserName, contextUser.OriginalUserName ?? string.Empty),
            }, authenticationType);

            return(_claims);
        }
예제 #7
0
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            HasPermissionRequirement requirement)
        {
            string _profile = requirement.Profile;

            ContextUserDTO _loggedUser = _facadeAuth.GetLoggedUser();

            if (string.IsNullOrEmpty(_profile) || _loggedUser.HasPermisson(_profile))
            {
                // Pode haver o mesmo attribute na Controller e nos métodos.
                // Então definimos o usuário logado Para que caso passe nesse mesmo
                // handler novamente não retorne Forbidden em um recurso já permitido.
                if (!_loggedUser.IsAllowedInHasPermissionPolicyChallenge)
                {
                    _facadeAuth.SetLoggedUserAllowedInHasPermissionPolicyChallenge();
                }

                context.Succeed(requirement);

                // Segue a pipeline de middlewares.
                return(Task.CompletedTask);
            }

            // Como o middleware de ExceptionHandler foi registrado primeiro,
            // ao lançarmos a Exception, o response da request sairá no formato esperado.
            if (!_loggedUser.IsAuthenticated)
            {
                throw new ApiException(ApiErrorCodes.NOTALLW);
            }

            if (!context.PendingRequirements.Any(pending => pending.GetType() == typeof(HasPermissionRequirement) &&
                                                 _loggedUser.HasPermisson(((HasPermissionRequirement)pending).Profile)))
            {
                context.Fail();
                throw new ApiException(ApiErrorCodes.NOTALLW);
            }

            context.Succeed(requirement);
            return(Task.CompletedTask);
        }