public AuthenticationResponse Refresh(RefreshCred refreshCred) { var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; var principal = tokenHandler.ValidateToken(refreshCred.AccessToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(refreshKey), ValidateIssuer = false, ValidateAudience = false }, out validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token passed!"); } var userName = principal.Identity.Name; //if (refreshCred.RefreshToken != jwtAuthenticationManager.UsersRefreshTokens[userName]) //{ // throw new SecurityTokenException("Invalid token passed!"); //} return(jwtAuthenticationManager.Authenticate(userName, principal.Claims.ToArray(), refreshCred.RefreshToken)); }
public async Task <AuthenticationResponse> Refresh(RefreshCred refreshCred) { var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(refreshCred.Token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(_key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false //here we are saying that we don't care about the token's expiration date }, out var validatedToken); if (validatedToken is not JwtSecurityToken jwtToken || !jwtToken.Header.Alg.Equals( SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { return(new AuthenticationResponse { Code = (int)ActionResult.InvalidTokenPassed, Message = ActionResult.InvalidTokenPassed.ToDescription() }); } //var userName = principal.Identity?.Name ?? ""; return(await _jWtAuthenticationManager.Authenticate(principal.Identity?.Name ?? "", principal.Claims.ToArray(), refreshCred.RefreshToken)); }
public AuthenticationResponse Refresh(RefreshCred refreshCred) { var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; var pricipal = tokenHandler.ValidateToken(refreshCred.JwtToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false //here we are saying that we don't care about the token's expiration date }, out validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token passed!"); } var userName = pricipal.Identity.Name; // var role = pricipal.Identity.Role; if (refreshCred.RefreshToken != jWTAuthenticationManager.UsersRefreshTokens[userName]) { throw new SecurityTokenException("Invalid token passed!"); } return(jWTAuthenticationManager.Authenticate(userName, pricipal.Claims.ToArray())); }
public IActionResult Refresh([FromBody] RefreshCred refreshCred) { var token = tokenRefresher.Refresh(refreshCred); if (token == null) { return(Unauthorized()); } return(Ok(token)); }
public AuthenticationResponse <Login> Refresh([FromBody] RefreshCred refreshCred) { var token = tokenRefresher.Refresh(refreshCred); if (!token.IsSuccess) { return(new AuthenticationResponse <Login>(false, $"{token.Message}", token, null)); } return(new AuthenticationResponse <Login>(true, $"{token.Message}", token, null)); }
public IActionResult Refresh([FromBody] RefreshCred refreshCred) { var authResult = _tokenRefresher.Refresh(refreshCred); if (authResult == null) { return(Unauthorized()); } return(Ok(authResult.Result)); }
public AuthenticationResponse Refresh(RefreshCred refreshCred) { var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(refreshCred.JwtToken, new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)), ValidateIssuer = false, ValidateAudience = false }); }
public TokenResponse Refresh(RefreshCred refreshCred) { try { var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; var pricipal = tokenHandler.ValidateToken(refreshCred.JwtToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, }, out validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { return(new TokenResponse { IsSuccess = false, Message = "Failure: Invalid token passed. Therefore, unable to refresh token.", }); } var userName = pricipal.Identity.Name; if (refreshCred.RefreshToken != jWTAuthenticationManager.UsersRefreshTokens[userName]) { return(new TokenResponse { IsSuccess = false, Message = "Failure: Invalid token passed. Therefore, unable to refresh token.", }); } return(jWTAuthenticationManager.Authenticate(userName, pricipal.Claims.ToArray())); } catch (Exception exception) { return(new TokenResponse { IsSuccess = false, Message = $"Server Failure: {exception.Message}", }); } }
public AuthenticateResponse Refresh(RefreshCred refreshCred, string ipAddress) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var pricipal = tokenHandler.ValidateToken(refreshCred.JwtToken, new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false //here we are saying that we don't care about the token's expiration date // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) // ClockSkew = TimeSpan.Zero }, out SecurityToken validatedToken); var jwtToken = validatedToken as JwtSecurityToken; var lifeTime = new JwtSecurityTokenHandler().ReadToken(refreshCred.JwtToken).ValidTo; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token passed"); } var userName = pricipal.Identity.Name; var userId = Convert.ToInt32(pricipal.FindFirst("id").Value); var Users = userBs.GetAll(); var user = Users.SingleOrDefault(x => x.Id == userId); var sessionrefreshtoken = user?.RefreshTokens?.Where(x => x.Token.Trim().Equals(refreshCred?.RefreshToken?.Trim()))?.FirstOrDefault()?.Token; //_session?.GetString(userName)?.ToString(); if (sessionrefreshtoken == null) { throw new SecurityTokenException("Invalid token passed!"); } ///jWTAuthenticationManager.UsersRefreshTokens[userName] need to fix why not working //if ( user.RefreshTokens.Single(x => x.Token.Trim().Equals(refreshCred.RefreshToken.Trim()) //{ // // throw new SecurityTokenException("Invalid token passed!") //} return(jWTAuthenticationManager.Authenticate(userName, pricipal.Claims.ToArray(), ipAddress, refreshCred)); }
public AuthenticationResponse Refresh(RefreshCred refreshCred) { AuthenticationResponse response = new AuthenticationResponse(); var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken; try { var pricipal = tokenHandler.ValidateToken(refreshCred.JwtToken, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false }, out validatedToken); var jwtToken = validatedToken as JwtSecurityToken; if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token passed!"); } var userName = pricipal.Identity.Name; if (refreshCred.RefreshToken != jWTAuthenticationManager.UsersRefreshTokens[userName]) { throw new SecurityTokenException("Invalid token passed!"); } response = jWTAuthenticationManager.Authentication(userName, pricipal.Claims.ToArray()); response.IsSuccess = true; response.Message = "Success"; } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; } return(response); }
public IActionResult Refresh(RefreshCred refreshCred) { //var refreshTokenfromCookie = Request.Cookies["refreshToken"]; var response = _tokenRefresher.Refresh(refreshCred, ipAddress()); if (response == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(response)); //var refreshToken = Request.Cookies["refreshToken"]; //var response = _userService.RefreshToken(refreshToken, ipAddress()); //if (response == null) // return Unauthorized(new { message = "Invalid token" }); //setTokenCookie(response.RefreshToken); //return Ok(response); }
// overload method public AuthenticateResponse Authenticate(string userName, Claim[] claims, string ipAddress, RefreshCred refreshCred) { var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var jwtSecurityToken = new JwtSecurityToken( claims: claims, expires: DateTime.UtcNow.AddMinutes(5), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) ); var Users = _userBs.GetAll(); var user = Users.SingleOrDefault(x => x.Username == userName); // return null if user not found if (user == null) { return(null); } var Usermodal = new WebApi.Models.User() { Username = user.Username, Id = user.Id, Password = user.Password, FirstName = user.FirstName, LastName = user.LastName }; var token = GenerateJwtToken(Usermodal, claims); // var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); var refreshToken = user.RefreshTokens.Single(x => x.Token.Trim().Equals(refreshCred.RefreshToken.Trim())); // this is to change the expired and active conditions // pending using automapper var refrshtokenMod = new Models.RefreshToken() { Revoked = DateTime.UtcNow, Expires = (DateTime)refreshToken.Expires, }; var newrefreshToken = refreshTokenGenerator.generateRefreshToken(ipAddress); // subsequesnt tokens _session.SetString(user.Username, newrefreshToken.Token); refreshToken.Expires = refrshtokenMod.Expires; refreshToken.Revoked = DateTime.UtcNow; refreshToken.RevokedByIp = ipAddress; refreshToken.ReplacedByToken = newrefreshToken.Token; refreshToken.IsActive = refrshtokenMod.IsActive; user.RefreshTokens.Add(new DAL.Models.RefreshToken() { Token = newrefreshToken.Token, Expires = newrefreshToken.Expires, IsExpired = newrefreshToken.IsExpired, Created = newrefreshToken.Created, CreatedByIp = newrefreshToken.CreatedByIp, Revoked = newrefreshToken.Revoked, RevokedByIp = newrefreshToken.RevokedByIp, ReplacedByToken = newrefreshToken.ReplacedByToken, IsActive = newrefreshToken.IsActive, UserId = user.Id }); var success = _userBs.Update(user); return(new AuthenticateResponse(Usermodal, token, newrefreshToken.Token)); }