Thalhammer / jwt-cpp

A header only library for creating and validating json web tokens in c++
https://thalhammer.github.io/jwt-cpp/
MIT License
917 stars 243 forks source link

How to verify a jwt #340

Closed manishjha5410 closed 7 months ago

manishjha5410 commented 7 months ago

What's your question?

How to verify a jwt

Additional Context

As you can seen in the image there is an arrow for red mark which state as verified and int the blue mark there is field for Hmac hash which i got from https://jwt.io/ imageedit_4_4287978288

Is there any way to verify the signature in the current application, i got one of the solution from [prince-chrismc] where i suggested to use Screenshot from 2024-04-12 09-01-47 but in this example the verifier just verify the token but how could i know that the token is verified ?

manishjha5410 commented 7 months ago

For additional context here is my cpp function

bool verifyJwt(std::string &jwtToken)
{
    std::string hash = getHash(jwtToken);

    jwt::decoded_jwt<jwt::traits::boost_json> token = jwt::decode(jwtToken);

    auto verifier = jwt::verify()
            .allow_algorithm(jwt::algorithm::hs256("secret"))
            .with_issuer("auth0")
            .with_id(hash)
            .leeway(60UL);

    verifier.verify(token);

    // return true if the signature is valid else return false
}

Signature is valid if hash(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) of this is equal to the trailing characters after period in jwtToken

Thalhammer commented 7 months ago

verifier.verify(token); throws an exception when theres something wrong with the token. This includes things like wrong issuer, expired tokens as well as invalid signatures. You can either catch that exception and turn it into a simple bool return or use the std::error_code overload and check that.

EDIT: Keep in mind that your first example uses rsa signatures and the second one a simple hmac. Also please don't post screenshots of text, it makes it harder to replicate if needed.

manishjha5410 commented 7 months ago

Okay buddy i am closing this issue