diff --git a/include/jwt/error_codes.hpp b/include/jwt/error_codes.hpp index 6b63a9b..13af452 100644 --- a/include/jwt/error_codes.hpp +++ b/include/jwt/error_codes.hpp @@ -11,6 +11,7 @@ enum class AlgorithmErrc { SigningErr = 1, VerificationErr, + KeyNotFoundErr, NoneAlgorithmUsed, // Not an actual error! }; diff --git a/include/jwt/impl/error_codes.ipp b/include/jwt/impl/error_codes.ipp index d3bda2d..a1ad64a 100644 --- a/include/jwt/impl/error_codes.ipp +++ b/include/jwt/impl/error_codes.ipp @@ -22,6 +22,8 @@ struct AlgorithmErrCategory: std::error_category return "signing failed"; case AlgorithmErrc::VerificationErr: return "verification failed"; + case AlgorithmErrc::KeyNotFoundErr: + return "key not provided"; case AlgorithmErrc::NoneAlgorithmUsed: return "none algorithm used"; }; diff --git a/include/jwt/impl/jwt.ipp b/include/jwt/impl/jwt.ipp index 500e282..f85f8f5 100644 --- a/include/jwt/impl/jwt.ipp +++ b/include/jwt/impl/jwt.ipp @@ -338,6 +338,15 @@ jwt_object& jwt_object::remove_claim(const string_view name) std::string jwt_object::signature(std::error_code& ec) const { ec.clear(); + + //key/secret should be set for any algorithm except NONE + if (header().algo() != jwt::algorithm::NONE) { + if (secret_.length() == 0) { + ec = AlgorithmErrc::KeyNotFoundErr; + return {}; + } + } + jwt_signature jws{secret_}; return jws.encode(header_, payload_, ec); } diff --git a/tests/test_jwt_encode b/tests/test_jwt_encode index 18266aa..0b412ca 100755 Binary files a/tests/test_jwt_encode and b/tests/test_jwt_encode differ diff --git a/tests/test_jwt_encode.cc b/tests/test_jwt_encode.cc index fdda646..396c2e3 100644 --- a/tests/test_jwt_encode.cc +++ b/tests/test_jwt_encode.cc @@ -138,9 +138,7 @@ TEST (EncodeTest, StrEncodeHS512WithKey) jwt::string_view key = "00112233445566778899"; - //TODO: map of jwt::string_view not working - - std::map p; + std::map p; p["aud"] = "rift.io"; p["sub"] = "nothing much"; @@ -180,6 +178,43 @@ TEST (EncodeTest, StrEncodeChangeAlg) EXPECT_EQ (expected_none_sign, enc_str); } +TEST (EncodeTest, StrEncodeNoKey) +{ + using namespace jwt::params; + + jwt::jwt_object obj{algorithm(jwt::algorithm::HS512), + payload({{"iss", "arn-ml"}}) + }; + + std::error_code ec; + std::string enc_str = obj.signature(ec); + + ASSERT_TRUE (ec); + EXPECT_EQ (ec.value(), static_cast(jwt::AlgorithmErrc::KeyNotFoundErr)); +} + +TEST (EncodeTest, StrEncodeNoneAlgWithKey) +{ + using namespace jwt::params; + + const jwt::string_view secret1 = "abcdefghijklmnopqrstuvwxyz"; + const jwt::string_view secret2 = "0123456789qwertybabe"; + + jwt::jwt_object obj{algorithm("NONE"), + payload({{"iss", "arn-ml"}}), + secret(secret1)}; + + std::error_code ec; + std::string enc_str1 = obj.signature(ec); + ASSERT_FALSE (ec); + + obj.secret(secret2); + std::string enc_str2 = obj.signature(ec); + ASSERT_FALSE (ec); + + EXPECT_EQ (enc_str1, enc_str2); +} + int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv);