public async Task <ActionResult <UserResponse> > Refresh(UserRefreshRequest request)
    {
        var refreshResponse = await _userService.RefreshTokenAsync(request);

        if (!refreshResponse.Success)
        {
            return(BadRequest(refreshResponse.Errors));
        }
        return(refreshResponse.Object);
    }
Exemple #2
0
    public async Task <ObjectResult <UserResponse> > RefreshTokenAsync(UserRefreshRequest request)
    {
        var validatedToken = GetPrincipalFromToken(request.JwtToken);

        if (validatedToken == null)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "Invalid token" }
            });
        }

        var expiryDateUnix = long.Parse(validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value);
        var expiryDateUtc  = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expiryDateUnix);

        if (expiryDateUtc > DateTime.UtcNow)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "This token hasn't expired yet" }
            });
        }

        var jti = validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value;

        var storedRefreshToken = await _refreshTokenRepository.GetRefreshToken(request.RefreshToken);

        if (storedRefreshToken == null)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "This refresh token doesn't exist" }
            });
        }

        if (DateTime.UtcNow > storedRefreshToken.ExpiryDate)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "Token Expired" }
            });
        }

        if (storedRefreshToken.Invalidated)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "This refresh token has been invalidated" }
            });
        }

        if (storedRefreshToken.Used)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "This refresh token has been used" }
            });
        }

        if (storedRefreshToken.JwtId != jti)
        {
            return(new ObjectResult <UserResponse> {
                Errors = new[] { "This refresh token does not match this JWT" }
            });
        }

        storedRefreshToken.Used = true;
        _refreshTokenRepository.UpdateRefreshToken(storedRefreshToken);

        await _userRepository.SaveChangesAsync();

        var user = await _userRepository.GetUserById(Int32.Parse(validatedToken.Claims.Single(x => x.Type == ClaimTypes.Name).Value));

        user = await RequestToken(user);

        return(new ObjectResult <UserResponse>
        {
            Success = true,
            Object = _mapper.Map <UserResponse>(user)
        });
    }