Example #1
0
        public async Task <AuthResult> RefreshTokenAsync(string token, string refreshToken)
        {
            var claimsPrincipal = GetClaimsPrincipalFromToken(token);

            if (claimsPrincipal == null)
            {
                return(new AuthResult
                {
                    Success = false,
                    ErrorMessages = new[] { "This token is invalid." }
                });
            }

            long expiryDateInSeconds = long.Parse(claimsPrincipal.FindFirstValue(JwtRegisteredClaimNames.Exp));

            var expiryDate = DateTime.UnixEpoch.AddSeconds(expiryDateInSeconds);

            if (expiryDate > DateTime.UtcNow)
            {
                return(new AuthResult
                {
                    Success = false,
                    ErrorMessages = new[] { "This token is still valid." }
                });
            }

            var storedRefreshToken = await RefreshTokenRepository.GetByTokenAsync(refreshToken);

            string jwtId = claimsPrincipal.FindFirstValue(JwtRegisteredClaimNames.Jti);

            if (storedRefreshToken == null ||
                DateTime.UtcNow > storedRefreshToken.ExpiryDate ||
                storedRefreshToken.Invalidated ||
                storedRefreshToken.Used ||
                storedRefreshToken.JwtId != jwtId)
            {
                return(new AuthResult
                {
                    Success = false,
                    ErrorMessages = new[] { "This refresh token is invalid." }
                });
            }

            await RefreshTokenRepository.SetUsedAsync(storedRefreshToken.Id);

            var user = await UserManager.FindByNameAsync(claimsPrincipal.FindFirstValue("username"));

            return(await GenerateAuthResultForUserAsync(user));
        }