Last active
March 24, 2021 11:28
-
-
Save changhuixu/9582e465646108138df14f59474edaa9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public JwtAuthResult Refresh(string refreshToken, string accessToken, DateTime now) | |
{ | |
var (principal, jwtToken) = DecodeJwtToken(accessToken); | |
if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature)) | |
{ | |
throw new SecurityTokenException("Invalid token"); | |
} | |
var userName = principal.Identity.Name; | |
if (!_usersRefreshTokens.TryGetValue(refreshToken, out var existingRefreshToken)) | |
{ | |
throw new SecurityTokenException("Invalid token"); | |
} | |
if (existingRefreshToken.UserName != userName || existingRefreshToken.ExpireAt < now) | |
{ | |
throw new SecurityTokenException("Invalid token"); | |
} | |
return GenerateTokens(userName, principal.Claims.ToArray(), now); // need to recover the original claims | |
} | |
public (ClaimsPrincipal, JwtSecurityToken) DecodeJwtToken(string token) | |
{ | |
if (string.IsNullOrWhiteSpace(token)) | |
{ | |
throw new SecurityTokenException("Invalid token"); | |
} | |
var principal = new JwtSecurityTokenHandler() | |
.ValidateToken(token, | |
new TokenValidationParameters | |
{ | |
ValidateIssuer = true, | |
ValidIssuer = _jwtTokenConfig.Issuer, | |
ValidateIssuerSigningKey = true, | |
IssuerSigningKey = new SymmetricSecurityKey(_secret), | |
ValidAudience = _jwtTokenConfig.Audience, | |
ValidateAudience = true, | |
ValidateLifetime = true, | |
ClockSkew = TimeSpan.FromMinutes(1) | |
}, | |
out var validatedToken); | |
return (principal, validatedToken as JwtSecurityToken); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment