Exemplo n.º 1
0
        public async Task <ActionResult <Person> > RefreshToken(TokenPairDTO tokenPairDto)
        {
            ClaimsPrincipal principles;

            try
            {
                principles = _jwtService.GetPrincipalFromExpiredToken(tokenPairDto.AccessToken);
                if (principles == null)
                {
                    throw new ArgumentNullException();
                }
            }
            catch (Exception)
            {
                return(BadRequest(BadRequestJsonResult("Invalid token. Sign in for a new one.")));
            }

            var user = _repository.GetByID(Convert.ToDecimal(principles.Claims.First(x => x.Type == "UserId").Value));

            if (user == null)
            {
                return(NotFound(NotFoundEmptyJsonResult));
            }

            if (!await _jwtService.IsRefreshTokenValid(user.Id, tokenPairDto.RefreshToken))
            {
                return(Unauthorized(UserMadeErrorJsonResult(401, "Refresh token expired or invalid. Sign in for a new one.")));
            }

            try
            {
                var refreshToken = _jwtService.GenerateRefreshToken();
                await UpdateRefreshToken(user, refreshToken);

                return(Accepted(new TokenPairDTO()
                {
                    AccessToken = await _jwtService.GenerateAccessTokenWithDefaultRole(user),
                    RefreshToken = refreshToken
                }));
            }
            catch (DBConcurrencyException e)
            {
                return(Conflict(ConflictJsonResult(e.Message)));
            }
        }