Thalhammer / jwt-cpp

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

[question] Why `jwt::verify().allow_algorithm.verify()` is void and make the runtime error exit? #188

Closed JerryCheng1 closed 2 years ago

JerryCheng1 commented 2 years ago

Here is my code:

auto decoded = jwt::decode("eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2Mzc0Njk2ODQsImlhdCI6MTYzNzQ2NjA4NCwiaXNzIjoidGVzdCIsImp0aSI6ImxvZ2luLWVzMjU2ay1mYXN0cGF5bWVudGFkbWluIiwibG9naW4iOiIxMjMifQ.Mt-e32zzIwaZEnmEdM6CRFNKmK8RfV8nEj256JCptqynEsF39RNw4rog-xiA3oNnnqOJhtQ9_1Eq_K8wwxT9eg");

auto verifier = jwt::verify().allow_algorithm(jwt::algorithm::es256k("", mainConfig::ec_priv_key, "", "")).with_issuer(row["username"].as<std::string>());
if (verifier.verify(decoded)){
    ret["message"] = "verify success";
} else {
    ret["message"] = "verify failed";
}

Thalhammer commented 2 years ago

verify throws an exception if the token is invalid, which you are probably not catching anywhere. If an exception is thrown but never caught the runtime calls std::terminate. What you need to do is either catch exceptions thrown by verify, or if you don't want to use exceptions for some reason use the overload that accepts std::error_code as an parameter (which you can them check if it had an error).

This design was made intentional, because the verification can fail for tons of reasons and a simple bool wouldn't give most applications enough information to handle the error correctly.

prince-chrismc commented 2 years ago

As mentioned you can avoid the runtimes cost and use the std::error_code overload.

https://github.com/Thalhammer/jwt-cpp/blob/66eea980b5b05ac47c09a178805f56e90568bc85/include/jwt-cpp/jwt.h#L3175

prince-chrismc commented 2 years ago

Closing as answered.

Feel free to reopen if it was unclear