Пример #1
0
        public async Task <IActionResult> Refresh([FromBody] TokenRefreshRequest request)
        {
            var principal    = _tokenService.GetPrincipalFromExpiredToken(request.Token);
            var emailAddress = principal.Identity.Name; //this is mapped to the Name claim by default

            var user = await _userManager.FindByNameAsync(emailAddress);

            if (user == null)
            {
                return(BadRequest());
            }

            var refreshTokens = await _userManager.GetRefreshTokens(user);

            if (!refreshTokens.Contains(request.RefreshToken))
            {
                return(BadRequest());
            }

            string issuedTimeString = principal.Claims.FirstOrDefault(x => x.Type == "nbf")?.Value;

            if (issuedTimeString == null)
            {
                return(BadRequest("Invalid JWT."));
            }

            Instant issuedTime = Instant.FromUnixTimeSeconds(Convert.ToInt64(issuedTimeString));

            if (issuedTime < user.LastChangedCredentials)
            {
                return(StatusCode(401));
            }

            var roles = await _userManager.GetRolesAsync(user);

            var claims          = user.GetUserClaims(roles);
            var newJwtToken     = _tokenService.GenerateAccessToken(claims);
            var newRefreshToken = _tokenService.GenerateRefreshToken();

            await _userManager.RemoveRefreshToken(user, request.RefreshToken);

            await _userManager.AddRefreshToken(user, newRefreshToken);

            var newJwtString = new JwtSecurityTokenHandler().WriteToken(newJwtToken);

            return(new ObjectResult(new
            {
                token = newJwtString,
                refreshToken = newRefreshToken,
                expiration = newJwtToken.ValidTo
            }));
        }