Update AuthController.cs (#43)

This commit is contained in:
Leendert de Borst
2024-06-23 17:22:17 +02:00
parent 4e2b10eeab
commit c07f0c33bb

View File

@@ -249,6 +249,33 @@ public class AuthController(AliasDbContext context, UserManager<AliasVaultUser>
return jwtKey;
}
/// <summary>
/// Get the principal from an expired token. This is used to validate the token and extract the user.
/// </summary>
/// <param name="token">The expired token as string.</param>
/// <returns>Claims principal.</returns>
/// <exception cref="SecurityTokenException">Thrown if provided token is invalid.</exception>
private static ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),
ValidateLifetime = false,
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
{
throw new SecurityTokenException("Invalid token");
}
return principal;
}
/// <summary>
/// Generate a Jwt access token for a user. This token is used to authenticate the user for a limited time
/// and is short-lived by design. With the separate refresh token, the user can request a new access token
@@ -293,27 +320,6 @@ public class AuthController(AliasDbContext context, UserManager<AliasVaultUser>
return Convert.ToBase64String(randomNumber);
}
private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey())),
ValidateLifetime = false,
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
{
throw new SecurityTokenException("Invalid token");
}
return principal;
}
/// <summary>
/// Generates a new access and refresh token for a user and persists the refresh token
/// to the database.