public async Task <IActionResult> Refresh(RefreshTokenInputModel input) { var response = new ResponseModel(); var headerToken = this.utilitiesService.GetAccessTokenHeader(HttpContext); if (headerToken == null) { response.AddErrorMessage("Missing access token header"); response.StatusCode = 400; return(Json(response)); } var accessToken = this.tokenService.GetAccessToken(headerToken, input.RefreshToken); if (accessToken == null) { response.AddErrorMessage("Invalid refresh token"); response.StatusCode = 400; return(Json(response)); } if (accessToken.RefreshExpirationDate < DateTime.UtcNow) { response.AddErrorMessage("Refresh token expired"); response.StatusCode = 400; return(Json(response)); } var user = this.usersService.GetById(accessToken.UserId); var tokens = await this.tokenService.GenerateTokensAsync(user); response.Data = tokens; return(Json(response)); }
public IActionResult RefreshToken([FromBody] RefreshTokenInputModel data) { RefreshStoreData refreshData; if (string.IsNullOrWhiteSpace(data.RefreshToken) || !refreshTokenTable.TryGetValue(data.RefreshToken, out refreshData)) { return(Unauthorized()); } refreshTokenTable.Remove(data.RefreshToken); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(configuration.GetSection("JWTBearer").GetValue <string>("ClientSeret")); var authTime = DateTime.UtcNow; var expiresAt = authTime.AddDays(7); var refreshToken = Guid.NewGuid().ToString().Replace("-", ""); refreshData.AuthorizeAt = new DateTimeOffset(authTime).ToUnixTimeSeconds(); refreshData.ExpiresAt = new DateTimeOffset(expiresAt).ToUnixTimeSeconds(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(JwtClaimTypes.Audience, "api"), new Claim(JwtClaimTypes.Issuer, "http://localhost:56325"), new Claim(JwtClaimTypes.Id, refreshData.MemberId.ToString()), new Claim(JwtClaimTypes.PhoneNumber, refreshData.MobilePhone), new Claim("refresh_token", refreshToken) }), Expires = expiresAt, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); refreshTokenTable.Add(refreshToken, refreshData); return(Ok(new { access_token = tokenString, token_type = "Bearer", profile = new { sid = refreshData.MemberId, refresh_token = refreshToken, auth_time = refreshData.AuthorizeAt, expires_at = refreshData.ExpiresAt } })); }