To decode and validate a JWT, use the l8w8jwt_decode function. This function returns a status code indicating if the parsing succeeded, while a separate enum l8w8jwt_validation_result variable provides details on signature verification and claim validation (like expiration).
Mandatory parameters for decoding:
alg: The algorithm used by the token.jwt: The JWT string to decode.jwt_length: Length of the JWT string.verification_key: The key used to verify the signature.verification_key_length: Length of the verification key.
Validation Options:
validate_iss: Validate the Issuer claim (use NUL-terminated strings).validate_sub: Validate the Subject claim.validate_exp: Validate the Expiration claim (set to 0 to disable).exp_tolerance_seconds: Allowed clock skew for expiration.validate_iat: Validate the Issued At claim.iat_tolerance_seconds: Allowed clock skew for iat.
Retrieving Claims:
To access the claims within the token, pass an array of struct l8w8jwt_claim to the l8w8jwt_decode function instead of NULL. If you allocate this array on the heap, you are responsible for freeing it.
#include "l8w8jwt/decode.h"
static const char KEY[] = "YoUR sUpEr S3krEt 1337 HMAC kEy HeRE";
static const char JWT[] = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1ODA5MzczMjksImV4cCI6MTU4MDkzNzkyOSwic3ViIjoiR29yZG9uIEZyZWVtYW4iLCJpc3MiOiJCbGFjayBNZXNhIiwiYXVkIjoiQWRtaW5pc3RyYXRvciJ9.7oNEgWxzs4nCtxOgiyTofP2bxZtL8dS7hgGXRPPDmwQWN1pjcwntsyK4Y5Cr9035Ro6Q16WOLiVAbj7k7TeCDA";
int main(void)
{
struct l8w8jwt_decoding_params params;
l8w8jwt_decoding_params_init(¶ms);
params.alg = L8W8JWT_ALG_HS512;
params.jwt = (char*)JWT;
params.jwt_length = strlen(JWT);
params.verification_key = (unsigned char*)KEY;
params.verification_key_length = strlen(KEY);
params.validate_iss = "Black Mesa";
params.validate_sub = "Gordon Freeman";
params.validate_exp = 0;
params.exp_tolerance_seconds = 60;
params.validate_iat = 1;
params.iat_tolerance_seconds = 60;
enum l8w8jwt_validation_result validation_result;
int decode_result = l8w8jwt_decode(¶ms, &validation_result, NULL, NULL);
if (decode_result == L8W8JWT_SUCCESS && validation_result == L8W8JWT_VALID)
{
printf("\n Example HS512 token validation successful! \n");
}
else
{
printf("\n Example HS512 token validation failed! \n");
}
return 0;
}