Example #1
0
        public async Task <HttpResponseMessage> RefreshAsync(TokenApiInputModel model)
        {
            using (var httpClient = new HttpClient())
            {
                string data        = JsonConvert.SerializeObject(model);
                var    contentData = new StringContent(data, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await httpClient.AddHeader().PostAsync("/api/token/refresh", contentData);

                return(response);
            }
        }
Example #2
0
        public async Task <IActionResult> Refresh(TokenApiInputModel model)
        {
            if (model is null)
            {
                return(BadRequest("Invalid client request"));
            }

            string accessToken  = model.AccessToken;
            string refreshToken = model.RefreshToken;

            var principal = _tokenService.GetPrincipalFromExpiredToken(accessToken);
            var userName  = principal.Identity.Name; //this is mapped to the Name claim by default

            var user = await _userManager.FindByNameAsync(userName);

            //Exist tokens find
            var existTokens = await _context.ApplicationUserToken.Where(f => f.UserId == user.Id).ToListAsync();

            var existAccessToken  = existTokens.FirstOrDefault(f => f.Name == TokenTypes.AccessToken);
            var existRefreshToken = existTokens.FirstOrDefault(f => f.Name == TokenTypes.RefreshToken);

            if (user == null || existRefreshToken.Value != refreshToken || existRefreshToken.ExpireDate <= DateTime.Now)
            {
                return(Unauthorized("Refresh token expired"));
            }

            var newAccessToken  = _tokenService.GenerateAccessToken(principal.Claims);
            var newRefreshToken = _tokenService.GenerateRefreshToken();


            existAccessToken.Value      = newAccessToken;
            existAccessToken.ExpireDate = new JwtSecurityToken(newAccessToken).ValidTo.ConvertUtcToLocalTime();

            existRefreshToken.Value      = newRefreshToken;
            existRefreshToken.ExpireDate = DateTime.Now.AddMinutes(5);

            _context.SaveChanges();

            return(Ok(new TokenApiOutputModel()
            {
                AccessToken = newAccessToken, RefreshToken = newRefreshToken
            }));
        }