Esempio n. 1
0
        public async Task <IdentityToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new ServiceException("refresh_token_not_found", $"Refresh token was not found.");
            }

            if (refreshToken.Revoked)
            {
                throw new ServiceException("refresh_token_not_revoked", $"Refresh token: '{refreshToken.Id.ToString()}' was revoked");
            }

            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user == null)
            {
                throw new ServiceException("user_not_found", $"User: '******' was not found.");
            }

            var jwt = _jwtHandler.CreateToken(user.Id, user.Role);

            return(new IdentityToken
            {
                AccessToken = jwt.AccessToken,
                Expires = jwt.Expires,
                RefreshToken = refreshToken.Token,
                Role = user.Role,
                UserId = user.Id
            });
        }
Esempio n. 2
0
        public async Task <AuthDto> UseAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Use(_dateTimeProvider.Now);
            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;

            var auth            = _jwtProvider.Create(token.UserId, user.Name, user.Role, claims: claims);
            var newRefreshToken = _refreshTokenFactory.Create(user.Id);
            await _refreshTokenRepository.AddAsync(newRefreshToken);

            await _refreshTokenRepository.UpdateAsync(token);

            auth.RefreshToken = newRefreshToken.Token;

            return(auth);
        }
Esempio n. 3
0
        public async Task <JsonWebToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken is null)
            {
                throw new ServiceException(ExceptionCode.RefreshTokenNotFound,
                                           "Refresh token was not found.");
            }

            if (refreshToken.Revoked)
            {
                throw new ServiceException(ExceptionCode.RefreshTokenAlreadyRevoked,
                                           "Refresh token: '{refreshToken.Id}' was revoked.");
            }

            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user is null)
            {
                throw new ServiceException(ExceptionCode.UserNotExists,
                                           $"User: '******' was not found.");
            }

            var claims = await _claimsProvider.GetAsync(user.Id);

            var jwt = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Role, claims);

            jwt.RefreshToken = refreshToken.Token;

            return(jwt);
        }
Esempio n. 4
0
        public async Task <IdentityToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new Exception("Refresh token was not found.");
            }
            if (refreshToken.Revoked)
            {
                throw new Exception($"Refresh token was revoked");
            }
            var account = await _accountRepository.GetAsync(refreshToken.UserId);

            if (account == null)
            {
                throw new Exception($"Account was not found.");
            }
            var jwt = _jwtHandler.Create(account.Username, account.Role, account.Id);



            return(new IdentityToken
            {
                AccessToken = jwt.AccessToken,
                Expires = jwt.Expires,
                RefreshToken = refreshToken.Token,
                Role = account.Role,
                UserId = account.Id
            });
        }
        public async Task <JsonWebToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new VirtualMarketException(Codes.RefreshTokenNotFound,
                                                 "Refresh token was not found.");
            }
            if (refreshToken.Revoked)
            {
                throw new VirtualMarketException(Codes.RefreshTokenAlreadyRevoked,
                                                 $"Refresh token: '{refreshToken.Id}' was revoked.");
            }
            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user == null)
            {
                throw new VirtualMarketException(Codes.UserNotFound,
                                                 $"User: '******' was not found.");
            }
            var claims = await _claimsProvider.GetAsync(user.Id);

            var jwt = _jwtHandler.CreateToken(user.Id.ToString("N"), user.Role, claims);

            jwt.RefreshToken = refreshToken.Token;
            await _busPublisher.PublishAsync(new AccessTokenRefreshed(user.Id), CorrelationContext.Empty);

            return(jwt);
        }
        public async Task <JsonWebToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new ServiceException(ErrorCodes.RefreshTokenNotFound,
                                           "Refresh token was not found.");
            }
            if (refreshToken.Revoked)
            {
                throw new ServiceException(ErrorCodes.RefreshTokenAlreadyRevoked,
                                           $"Refresh token: '{refreshToken.Id}' was revoked.");
            }
            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user == null)
            {
                throw new ServiceException(ErrorCodes.UserNotFound,
                                           $"User: '******' was not found.");
            }
            var jwt = _jwtHandler.CreateToken(user.SerialNumber, user.Role);

            jwt.RefreshToken = refreshToken.Token;

            return(jwt);
        }
        public async Task <JsonWebToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new ServiceException("refresh_token_not_found",
                                           "Refresh token was not found.");
            }
            if (refreshToken.Revoked)
            {
                throw new ServiceException("refresh_token_not_revoked",
                                           $"Refresh token: '{refreshToken.Id}' was revoked.");
            }
            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user == null)
            {
                throw new ServiceException("user_not_found",
                                           $"User: '******' was not found.");
            }
            var jwt = _jwtHandler.CreateToken(user.Id, user.Role);

            jwt.RefreshToken = refreshToken.Token;

            return(jwt);
        }
Esempio n. 8
0
        public async Task <JwtDTO> RefreshAccessToken(string refreshToken)
        {
            var token = await _refreshTokens.GetAsync(refreshToken);

            if (token == null)
            {
                throw new NewException("Token was not found.");
            }
            if (token.Revoked)
            {
                throw new NewException("Token was revoked.");
            }
            var user = await _userRepository.GetAsync(token.UserId);

            if (user == null)
            {
                throw new NewException("User was not found.");
            }
            var jwt    = _jwtHandler.CreateToken(user.Id);
            var jwtDto = new JwtDTO()
            {
                AccessToken = jwt.AccessToken, Expires = jwt.Expires, RefreshToken = token.Token
            };

            return(jwtDto);
        }
Esempio n. 9
0
        public async Task UseAsync_ShouldReturnJwtDto_WhenRefreshTokenExists(int id, string userName, string role)
        {
            var token        = "randomTestToken";
            var refreshToken = _fixture.Build <RefreshToken>()
                               .With(t => t.UserId, id)
                               .Create();

            var user = _fixture.Build <UserDto>()
                       .With(u => u.Id, id)
                       .With(u => u.UserName, userName)
                       .With(u => u.Role, role)
                       .Create();

            var jwtDto = _fixture.Build <JwtDto>()
                         .With(j => j.UserId, id)
                         .With(j => j.Username, userName)
                         .With(j => j.Role, role)
                         .Create();

            _refreshTokenRepository.GetAsync(token).Returns(refreshToken);

            _userService.GetAsync(id).Returns(user);

            _jwtHandler.CreateToken(id, userName, role).Returns(jwtDto);

            var jwt = await _sut.UseAsync(token);

            jwt.ShouldNotBeNull();
            jwt.UserId.ShouldBe(id);
            jwt.Username.ShouldBe(userName);
            jwt.Role.ShouldBe(role);
            await _refreshTokenRepository.Received(1).AddAsync(Arg.Any <RefreshToken>());

            await _refreshTokenRepository.Received(1).UpdateAsync(Arg.Any <RefreshToken>());
        }
Esempio n. 10
0
        public async Task RevokeAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Revoke(DateTime.UtcNow);
            await _refreshTokenRepository.UpdateAsync(token);
        }
        public async Task HandleAsync(UseRefreshToken command)
        {
            var token = await _refreshTokenRepository.GetAsync(command.RefreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            if (token.Revoked)
            {
                throw new RevokedRefreshTokenException();
            }

            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(token.UserId, user.Name, user.Role, claims: claims);

            auth.RefreshToken = command.RefreshToken;
            _storage.Set(command.Id, auth);
        }
Esempio n. 12
0
        public async Task <Result <object> > Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            var cacheKey = $"User-{request.UserId}";

            if (!await _cacheService.IsExistsAsync(cacheKey))
            {
                var userInDb = await _userRepository.GetAsync(u => u.Id == request.UserId);

                userInDb.CheckForNull();
            }

            var token = await _tokenRepository.GetAsync(t => t.Id == request.UserId);

            if (token is not null)
            {
                await _tokenRepository.DeleteAsync(t => t.Id == token.Id);

                await _sender.PublishAsync(token, cancellationToken);
            }

            await _userRepository.DeleteAsync(u => u.Id == request.UserId);

            await _cacheService.RemoveAsync(cacheKey);

            return(Result <object> .Success());
        }
        public async Task <AuthDto> HandleAsync(UseRefreshToken request)
        {
            var token = await _refreshTokenRepository.GetAsync(request.RefreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            if (token.Revoked)
            {
                throw new RevokedRefreshTokenException();
            }

            var user = await _userRepository.GetAsync(token.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(token.UserId);
            }

            var auth = _jwtProvider.Create(token.UserId, user.Role);

            auth.RefreshToken = request.RefreshToken;

            return(auth);
        }
Esempio n. 14
0
        public async Task <JsonWebToken> HandleAsync(AccessTokenQuery query)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(query.Token);

            if (refreshToken == null)
            {
                throw new DomainException(Codes.RefreshTokenNotFound, MessagesCode.RefreshTokenNotFound);
            }

            if (refreshToken.Revoked)
            {
                throw new DomainException(Codes.RefreshTokenAlreadyRevoked, string.Format(MessagesCode.RefreshTokenAlreadyRevoked, refreshToken.Id));
            }

            var user = await _userRepository.GetAsync(refreshToken.UserId);

            if (user == null)
            {
                throw new DomainException(Codes.UserNotFound, string.Format(MessagesCode.UserNotFound, refreshToken.UserId));
            }

            var rolesName = user.UserRoles.Select(x => x.Role.RoleName).ToList();
            var jwt       = _jwtHandler.CreateToken(user.Id.ToString("N"), rolesName);

            jwt.RefreshToken = refreshToken.Token;

            return(jwt);
        }
Esempio n. 15
0
        public async Task <JsonWebToken> CreateAccessTokenAsync(string token)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null)
            {
                throw new ToolBoxException(Codes.RefreshTokenNotFound,
                                           "Refresh token was not found.");
            }
            //var user = await _userRepository.GetAsync(refreshToken.UserId);
            if (refreshToken.User == null || refreshToken.UserId == null || refreshToken.UserId == Guid.Empty)
            {
                throw new ToolBoxException(Codes.UserNotFound,
                                           $"User: '******' was not found.");
            }

            var claims = await _claimsProvider.GetAsync(refreshToken.User);

            var jwt = _jwtHandler.CreateToken(refreshToken.UserId.ToString(), null, claims);

            jwt.RefreshToken = refreshToken.Token;
            await _busClient.PublishAsync(new AccessTokenRefreshed(Guid.NewGuid(), refreshToken.UserId));

            // await _busClient.PublishAsync(new AccessTokenRefreshed(user.Id), CorrelationContext.Empty);

            return(jwt);
        }
Esempio n. 16
0
        public async Task <RefreshTokenDTO> GetAsync(string refreshToken)
        {
            var result = await _refreshTokenRepository.GetAsync(item => item.RefreshToken == refreshToken);

            if (result == null)
            {
                throw new HttpStatusCodeException(
                          HttpStatusCode.NotFound, "Such refresh token doesn't exist");
            }

            return(new RefreshTokenDTO
            {
                Id = result.Id,
                UserId = result.UserId,
                IsActive = result.IsActive,
                RefreshToken = result.RefreshToken,
                DaysToExpire = result.DaysToExpire
            });
        }
        public async Task HandleAsync(RevokeRefreshToken command)
        {
            var token = await _refreshTokenRepository.GetAsync(command.RefreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Revoke(DateTime.UtcNow);
            await _refreshTokenRepository.UpdateAsync(token);
        }
        public async Task HandleAsync(RevokeRefreshTokenCommand command, ICorrelationContext context)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(command.Token);

            if (refreshToken == null || refreshToken.UserId != command.UserId)
            {
                throw new DomainException(Codes.RefreshTokenNotFound, MessagesCode.RefreshTokenNotFound);
            }

            refreshToken.Revoke();
            await _refreshTokenRepository.UpdateAsync(refreshToken);
        }
Esempio n. 19
0
        // Refreshing token

        public async Task <JwtDto> UseAsync(string refreshToken)
        {
            var token = await _refreshTokenRepository.GetAsync(refreshToken);

            if (token is null)
            {
                throw new InvalidRefreshTokenException();
            }

            token.Use(_dateTimeProvider.Now);
            var user = await _userService.GetAsync(token.UserId);

            var jwt             = _jwtHandler.CreateToken(token.UserId, user.UserName, user.Role);
            var newRefreshToken = _refreshTokenFactory.Create(user.Id);
            await _refreshTokenRepository.AddAsync(newRefreshToken);

            await _refreshTokenRepository.UpdateAsync(token);

            jwt.RefreshToken = newRefreshToken.Token;

            return(jwt);
        }
Esempio n. 20
0
        public async Task RevokeAsync(string token, Guid userId)
        {
            var refreshToken = await _refreshTokenRepository.GetAsync(token);

            if (refreshToken == null || refreshToken.UserId != userId)
            {
                throw new MinotaurException(Codes.RefreshTokenNotFound,
                                            "Refresh token was not found.");
            }
            refreshToken.Revoke();
            await _refreshTokenRepository.UpdateAsync(refreshToken);

            await _busPublisher.PublishAsync(new RefreshTokenRevoked(refreshToken.UserId), CorrelationContext.Empty);
        }
        public async Task <IActionResult> RequestToken([FromBody] Login credenciais)
        {
            // https://medium.com/@renato.groffe/asp-net-core-2-0-jwt-implementando-refresh-tokens-7fa525ffb461

            Usuario userData           = null;
            bool    credenciaisValidas = false;

            if (credenciais != null && !string.IsNullOrWhiteSpace(credenciais.Email))
            {
                userData = await _userRepository.GetByEmailAsync(credenciais.Email);

                if (credenciais.GrantType == "password")
                {
                    credenciaisValidas = (userData != null && credenciais.Password.Encrypt() == userData.Senha);
                }
                else if (credenciais.GrantType == "refresh_token" && !string.IsNullOrWhiteSpace(credenciais.RefreshToken) && userData != null)
                {
                    // verificar se o token é válido
                    var refreshTokenData = await _refreshTokenRepository.GetAsync(userData.Id, credenciais.RefreshToken);

                    credenciaisValidas = (refreshTokenData != null && credenciais.RefreshToken == refreshTokenData.Token);

                    if (credenciaisValidas)
                    {
                        _refreshTokenRepository.Del(refreshTokenData);
                        await _uow.CommitAsync();
                    }
                }
            }

            if (credenciaisValidas)
            {
                // Add o token no header também
                // Request.HttpContext.Response.Headers.Add("x-access-token", new JwtSecurityTokenHandler().WriteToken(token));
                return(await GenerateToken(userData.Id, userData.Nome, userData.Email));
            }
            else
            {
                return(BadRequest("Credenciais inválidas..."));
            }
        }
Esempio n. 22
0
        public async Task <Result <object> > Handle(LogoutCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetAsync(u => u.Id == request.UserId);

            if (user == null)
            {
                throw Result <User> .Failure("id", "Invalid id");
            }

            user.SessionId = null;

            var token = await _tokenRepository.GetAsync(t => t.User.Id == request.UserId);

            await _tokenRepository.DeleteAsync(t => t.Id == token.Id);

            await _sender.PublishAsync(new UpdatedUser(user), cancellationToken);

            await _sender.PublishAsync(new DeletedToken(token.Id), cancellationToken);

            return(Result <object> .Success());
        }
        public async Task <Result <UserAuthenticatedDto> > Handle(RefreshTokenCommand request,
                                                                  CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetAsync(u => u.Id == request.UserId);

            user.SessionId = Guid.NewGuid().ToString();
            var userDto = _mapper.Map <UserDto>(user);

            var refreshTokenInDb = await
                                   _tokenRepository.GetAsync(t => t.User.Id == request.UserId && t.Token == request.Token.Name);

            refreshTokenInDb.CheckForNull();
            IsValid(refreshTokenInDb);

            var jwtToken     = JwtExtensions.GenerateJwtToken(userDto, _tokenConfiguration);
            var tokenString  = JwtExtensions.GenerateRefreshToken();
            var userInDb     = _mapper.Map <User>(user);
            var refreshToken = new RefreshToken
            {
                Id          = Guid.NewGuid().ToString(),
                DateCreated = DateTime.UtcNow,
                DateExpires = DateTime.UtcNow.AddMinutes(_tokenConfiguration.RefreshTokenExpirationMinutes),
                Token       = tokenString,
                User        = userInDb
            };

            await _tokenRepository.CreateAsync(refreshToken);

            await _tokenRepository.DeleteAsync(t => t.Id == refreshTokenInDb.Id);

            await _sender.PublishAsync(new UpdatedUser(user), cancellationToken);

            await _sender.PublishAsync(new CreatedToken(refreshToken), cancellationToken);

            UserAuthenticatedDto authenticatedDto = new(userDto, jwtToken, refreshToken.Token);

            return(Result <UserAuthenticatedDto> .Success(authenticatedDto));
        }
Esempio n. 24
0
        public async Task <Result <UserDto> > Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            var  cacheKey = $"User-{request.UserId}";
            User userInDb;

            if (!await _cacheService.IsExistsAsync(cacheKey))
            {
                userInDb = await _userRepository.GetAsync(u => u.Id == request.UserId);

                userInDb.CheckForNull();
            }

            var userDto = _mapper.Map <UserDto>(request.User) with {
                Id = request.UserId
            };

            userInDb = _mapper.Map <User>(userDto);
            var token = await _tokenRepository.GetAsync(t => t.User.Id == request.UserId);

            LogDto log =
                new(Guid.NewGuid().ToString(), request.UserName, "edited user", JsonSerializer.Serialize(userDto,
                                                                                                         CommandExtensions.JsonSerializerOptions), DateTime.UtcNow);

            if (token is not null)
            {
                token.User = userInDb;
                await _tokenRepository.UpdateAsync(t => t.Id == token.Id, token);
            }

            await _userRepository.UpdateAsync(u => u.Id == userInDb.Id, userInDb);

            await _cacheService.UpdateAsync(cacheKey, userInDb, _userSettings);

            await _sender.PublishAsync(log, cancellationToken);

            return(Result <UserDto> .Success(userDto));
        }
    }
Esempio n. 25
0
 public async Task <RefreshToken> FindRefreshTokenAsync(string hashedTokenId)
 {
     return(await _repository.GetAsync(hashedTokenId));
 }