Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
public bool VerifyJwt(string token, string secretKey, string audience, string issuer)
{
    try
    {
        byte[] certificateData = Convert.FromBase64String(secretKey);
        X509Certificate2 certificate = new X509Certificate2(certificateData);
        X509SecurityKey securityKey = new X509SecurityKey(certificate);        // Define token validation parameters
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = securityKey,
            ValidateIssuer = true, // Set to true if you want to validate the issuer
            ValidIssuer = issuer, // Replace with the expected issuer
            ValidateAudience = true, // Set to true if you want to validate the audience
            ValidAudience = audience, // Replace with the expected audience
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };        
        // Parse and validate the token
        SecurityToken validatedToken;
        var principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);        // You can access the claims in the token via the principal.Claims property if needed.
        // For example:
        // var userId = principal.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;        // If the token is valid, the validation process will not throw an exception.
        // So, if you reach this point, the token is valid.
        return true;
    }
    catch (Exception)
    {
        // If an exception is thrown, the token is not valid.
        return false;
    }
}

...