public async Task <ActionResult <TokenResult> > Refresh([FromForm] string token, [FromForm] string refreshToken) { ClaimsPrincipal principal = _tokenService.GetPrincipalFromExpiredToken(token); string name = GetNameFromClaimsPrincipal(principal); string email = GetEmailFromClaimsPrincipal(principal); User user = await _userManager.FindByEmailAsync(email); string savedRefreshToken = user.RefreshToken; if (savedRefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } string newJwtToken = _tokenService.BuildToken(name, email); string newRefreshToken = _tokenService.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await _userManager.UpdateAsync(user); return(Ok(new TokenResult { Token = newJwtToken, RefreshToken = newRefreshToken })); }
public async Task <ActionResult <TokenResult> > Refresh([FromForm] string token, [FromForm] string refreshToken) { ClaimsPrincipal principal = _tokenService.GetPrincipalFromExpiredToken(token); string email = GetEmailFromClaimsPrincipal(principal); User user = await _userManager.FindByEmailAsync(email); if (user == null) { return(NotFound()); } string savedRefreshToken = user.RefreshToken; if (savedRefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } var role = (await _userManager.GetRolesAsync(user)).First(); string newJwtToken = GenerateToken(user, role); string newRefreshToken = GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await _userManager.UpdateAsync(user); return(Ok(new TokenResult { Token = newJwtToken, RefreshToken = newRefreshToken })); }
public async Task <IActionResult> Refresh(string token, string refreshToken) { ClaimsPrincipal principal = _tokenService.GetPrincipalFromExpiredToken(token); string email = GetEmailFromClaimsPrincipal(principal); ApplicationUser user = await _userManager.FindByEmailAsync(email); string savedRefreshToken = user.RefreshToken; if (savedRefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } string newJwtToken = GenerateToken(user); string newRefreshToken = GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await _userManager.UpdateAsync(user); return(Ok(new { token = newJwtToken, refresh_token = newRefreshToken })); }
public async Task <IActionResult> Refresh(RefreshTokenModel requestModel) { var principal = _jwtTokenService.GetPrincipalFromExpiredToken(requestModel.Token); var username = principal.Claims.SingleOrDefault(x => x.Type == TokenClaims.UserName).Value; var user = await _userManager.FindByNameAsync(username).ConfigureAwait(false); if (user == null || user.RefreshToken != requestModel.RefreshToken) { return(BadRequest()); } var newJwtToken = _jwtTokenService.GenerateJwtToken(principal.Claims, null); var newRefreshToken = _jwtTokenService.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; await _userManager.UpdateAsync(user).ConfigureAwait(false); return(Ok(new { token = newJwtToken, refreshToken = newRefreshToken })); }
public async Task <Results <RefreshTokenContract> > RefreshToken(RefreshTokenContract token) { var principal = _jwtTokenService.GetPrincipalFromExpiredToken(token.Token); if (principal == null) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid refresh token")); } var email = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.Email); if (string.IsNullOrEmpty(email)) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim email")); } var userId = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.NameId); if (string.IsNullOrEmpty(userId)) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim userId")); } var tokenValid = await _userLogic.ValidateRefreshToken(email, token.RefreshToken); if (tokenValid.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(tokenValid.Errors.ToArray())); } var newJwtToken = _jwtTokenService.GenerateToken(email, userId); var newRefreshToken = _jwtTokenService.GenerateRefreshToken(); var updateRefreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(email, newRefreshToken); if (updateRefreshTokenResult.IsError()) { return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(updateRefreshTokenResult.Errors.ToArray())); } var result = PandaResponse.CreateSuccessResponse <RefreshTokenContract>( new RefreshTokenContract { Token = newJwtToken, RefreshToken = newRefreshToken }); return(result); }
public async Task <IActionResult> RefreshToken(string token, string refreshToken) { var principal = _jwtTokenService.GetPrincipalFromExpiredToken(token); var username = principal.Identity.Name; var savedRefreshToken = await _accountFacade.GetRefreshToken(username); //retrieve the refresh token from a data store if (savedRefreshToken != refreshToken) { throw new SecurityTokenException("Invalid refresh token"); } var newJwtToken = _jwtTokenService.GenerateToken(principal.Claims.ToList()); var newRefreshToken = _jwtTokenService.GenerateRefreshToken(); await _accountFacade.UpdateRefreshToken(username, newRefreshToken); var result = LinqExtensions.CreateSuccessResponse <RefreshTokenContract>( new RefreshTokenContract { Token = newJwtToken, RefreshToken = newRefreshToken }); return(Ok(result)); }
public async Task <AuthorizeTokenResponse> RefreshTokenAsync(RefreshTokenRequest request, CancellationToken cancellationToken) { var result = new AuthorizeTokenResponse(); try { var accessToken = request.AccessToken; var refreshToken = request.RefreshToken; var principal = _jwtTokenService.GetPrincipalFromExpiredToken(accessToken); // this is mapped to the Name claim by default var username = principal.Identity.Name; if (!await _userService.ValidateRefreshTokenAsync(username ?? string.Empty, refreshToken, cancellationToken)) { return(result); } result.Success = true; result.AccessToken = _jwtTokenService.GenerateAccessToken(principal.Claims); result.ExpiresIn = DateTimeOffset.UtcNow.AddMinutes(_jwtTokenOptions.AccessExpiration).Ticks; result.RefreshToken = _jwtTokenService.GenerateRefreshToken(); await _userService.UpdateRefreshTokenAsync( username ?? string.Empty, result.RefreshToken, DateTime.Now.Add(TimeSpan.FromMinutes(_jwtTokenOptions.RefreshExpiration)), cancellationToken); } catch (Exception ex) { result.Success = false; } return(result); }
public async Task Invoke(HttpContext context) { //var apiRoute = context.Request.Path.Value; //Enum.TryParse(context.Request.Method, out HttpMethod httpMethod); //Read the Header var request = context.Request; string authHeader = context.Request.Headers["Authorization"]; string pandaHeader = context.Request.Headers["Panda"]; if (string.IsNullOrEmpty(pandaHeader)) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Secure Key Not found'] }"); return; } var SecureKey = _configuration["SecureKey:Self"]; if (SecureKey != pandaHeader) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Secure Key Invalid'] }"); return; } ClaimsPrincipal pcp = null; if (!string.IsNullOrEmpty(authHeader)) { authHeader = authHeader.Replace("Bearer ", ""); pcp = _jwtTokenService.GetPrincipalFromExpiredToken(authHeader); if (pcp == null) { context.Response.StatusCode = 500; await context.Response.WriteAsync("{ errors : ['Token Invalid'] }"); return; } } #region BodyModified if (request.Path.Value.Contains("/api") && !request.Path.Value.ToLower().Contains("value")) { var stream = request.Body; var originalContent = new StreamReader(stream).ReadToEnd(); var notModified = true; try { dynamic dataSource = JsonConvert.DeserializeObject(originalContent); if (dataSource != null) { dataSource.Token = authHeader; var json = JsonConvert.SerializeObject(dataSource); var requestContent = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json"); stream = await requestContent.ReadAsStreamAsync(); notModified = false; } } catch { notModified = true; } if (notModified) { var requestData = Encoding.UTF8.GetBytes(originalContent); stream = new MemoryStream(requestData); } request.Body = stream; } #endregion await _next(context); }