4 #ifndef JWT_DISABLE_PICOJSON
5 #ifndef PICOJSON_USE_INT64
6 #define PICOJSON_USE_INT64
11 #ifndef JWT_DISABLE_BASE64
15 #include <openssl/ec.h>
16 #include <openssl/ecdsa.h>
17 #include <openssl/err.h>
18 #include <openssl/evp.h>
19 #include <openssl/hmac.h>
20 #include <openssl/pem.h>
21 #include <openssl/rsa.h>
22 #include <openssl/ssl.h>
32 #include <system_error>
33 #include <type_traits>
34 #include <unordered_map>
38 #if __cplusplus > 201103L
42 #if __cplusplus >= 201402L
44 #if __has_include(<experimental/type_traits>)
45 #include <experimental/type_traits>
50 #if OPENSSL_VERSION_NUMBER >= 0x30000000L // 3.0.0
51 #define JWT_OPENSSL_3_0
52 #elif OPENSSL_VERSION_NUMBER >= 0x10101000L // 1.1.1
53 #define JWT_OPENSSL_1_1_1
54 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L // 1.1.0
55 #define JWT_OPENSSL_1_1_0
56 #elif OPENSSL_VERSION_NUMBER >= 0x10000000L // 1.0.0
57 #define JWT_OPENSSL_1_0_0
60 #if defined(LIBRESSL_VERSION_NUMBER)
61 #if LIBRESSL_VERSION_NUMBER >= 0x3050300fL
62 #define JWT_OPENSSL_1_1_0
64 #define JWT_OPENSSL_1_0_0
68 #if defined(LIBWOLFSSL_VERSION_HEX)
69 #define JWT_OPENSSL_1_1_1
72 #ifndef JWT_CLAIM_EXPLICIT
73 #define JWT_CLAIM_EXPLICIT explicit
87 using date = std::chrono::system_clock::time_point;
94 using system_error::system_error;
97 using system_error::system_error;
100 using system_error::system_error;
103 using system_error::system_error;
106 using system_error::system_error;
127 class rsa_error_cat :
public std::error_category {
129 const char* name()
const noexcept
override {
return "rsa_error"; };
130 std::string message(
int ev)
const override {
142 default:
return "unknown RSA error";
146 static rsa_error_cat cat;
168 class ecdsa_error_cat :
public std::error_category {
170 const char* name()
const noexcept
override {
return "ecdsa_error"; };
171 std::string message(
int ev)
const override {
178 return "at least one of public or private key need to be present";
182 default:
return "unknown ECDSA error";
186 static ecdsa_error_cat cat;
210 class verification_error_cat :
public std::error_category {
212 const char* name()
const noexcept
override {
return "signature_verification_error"; };
213 std::string message(
int ev)
const override {
218 return "failed to verify signature: could not create context";
220 return "failed to verify signature: VerifyInit failed";
222 return "failed to verify signature: VerifyUpdate failed";
224 return "failed to verify signature: VerifyFinal failed";
226 return "failed to verify signature: Could not get key";
228 return "failed to verify signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
230 return "failed to verify signature: i2d_ECDSA_SIG failed";
231 default:
return "unknown signature verification error";
235 static verification_error_cat cat;
267 class signature_generation_error_cat :
public std::error_category {
269 const char* name()
const noexcept
override {
return "signature_generation_error"; };
270 std::string message(
int ev)
const override {
275 return "failed to create signature: could not create context";
277 return "failed to create signature: SignInit failed";
279 return "failed to create signature: SignUpdate failed";
281 return "failed to create signature: SignFinal failed";
284 return "failed to create signature: DigestInit failed";
286 return "failed to create signature: DigestUpdate failed";
288 return "failed to create signature: DigestFinal failed";
290 return "failed to create signature: EVP_PKEY_CTX_set_rsa_padding failed";
292 return "failed to create signature: RSA_private_encrypt failed";
294 return "failed to generate signature: Could not get key";
296 return "failed to create signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
298 return "failed to create signature: d2i_ECDSA_SIG failed";
299 default:
return "unknown signature generation error";
303 static signature_generation_error_cat cat = {};
327 class token_verification_error_cat :
public std::error_category {
329 const char* name()
const noexcept
override {
return "token_verification_error"; };
330 std::string message(
int ev)
const override {
336 return "claim type does not match expected type";
338 return "claim value does not match expected value";
341 return "token doesn't contain the required audience";
342 default:
return "unknown token verification error";
346 static token_verification_error_cat cat = {};
399 #ifdef JWT_OPENSSL_1_0_0
404 explicit evp_pkey_handle(EVP_PKEY* key) { m_key = std::shared_ptr<EVP_PKEY>(key, EVP_PKEY_free); }
406 EVP_PKEY*
get()
const noexcept {
return m_key.get(); }
407 bool operator!()
const noexcept {
return m_key ==
nullptr; }
408 explicit operator bool()
const noexcept {
return m_key !=
nullptr; }
411 std::shared_ptr<EVP_PKEY> m_key{
nullptr};
419 if (m_key !=
nullptr && EVP_PKEY_up_ref(m_key) != 1)
throw std::runtime_error(
"EVP_PKEY_up_ref failed");
422 #if __cplusplus >= 201402L
426 : m_key{other.m_key} {
427 other.m_key =
nullptr;
430 if (&other ==
this)
return *
this;
431 decrement_ref_count(m_key);
433 increment_ref_count(m_key);
437 if (&other ==
this)
return *
this;
438 decrement_ref_count(m_key);
440 other.m_key =
nullptr;
444 decrement_ref_count(m_key);
446 increment_ref_count(m_key);
451 EVP_PKEY*
get() const noexcept {
return m_key; }
452 bool operator!() const noexcept {
return m_key ==
nullptr; }
453 explicit operator bool() const noexcept {
return m_key !=
nullptr; }
456 EVP_PKEY* m_key{
nullptr};
458 static void increment_ref_count(EVP_PKEY* key) {
459 if (key !=
nullptr && EVP_PKEY_up_ref(key) != 1)
throw std::runtime_error(
"EVP_PKEY_up_ref failed");
461 static void decrement_ref_count(EVP_PKEY* key) noexcept {
462 if (key !=
nullptr) EVP_PKEY_free(key);
468 return std::unique_ptr<BIO, decltype(&BIO_free_all)>(BIO_new(BIO_s_mem()), BIO_free_all);
471 inline std::unique_ptr<BIO, decltype(&BIO_free_all)>
make_mem_buf_bio(
const std::string& data) {
472 return std::unique_ptr<BIO, decltype(&BIO_free_all)>(
473 #
if OPENSSL_VERSION_NUMBER <= 0x10100003L
474 BIO_new_mem_buf(
const_cast<char*
>(data.data()),
static_cast<int>(data.size())), BIO_free_all
476 BIO_new_mem_buf(data.data(),
static_cast<int>(data.size())), BIO_free_all
483 #ifdef JWT_OPENSSL_1_0_0
484 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
486 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
498 std::error_code& ec) {
502 if (!certbio || !keybio) {
507 std::unique_ptr<X509, decltype(&X509_free)> cert(
508 PEM_read_bio_X509(certbio.get(),
nullptr,
nullptr,
const_cast<char*
>(pw.c_str())), X509_free);
513 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free);
518 if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) {
523 auto len = BIO_get_mem_data(keybio.get(), &
ptr);
524 if (len <= 0 ||
ptr ==
nullptr) {
528 return {
ptr,
static_cast<size_t>(len)};
559 template<
typename Decode>
561 std::error_code& ec) {
563 const auto decodedStr =
decode(cert_base64_der_str);
564 auto c_str =
reinterpret_cast<const unsigned char*
>(decodedStr.c_str());
566 std::unique_ptr<X509, decltype(&X509_free)> cert(
567 d2i_X509(NULL, &c_str,
static_cast<int>(decodedStr.size())), X509_free);
569 if (!cert || !certbio) {
574 if (!PEM_write_bio_X509(certbio.get(), cert.get())) {
580 const auto len = BIO_get_mem_data(certbio.get(), &
ptr);
581 if (len <= 0 ||
ptr ==
nullptr) {
586 return {
ptr,
static_cast<size_t>(len)};
603 template<
typename Decode>
610 #ifndef JWT_DISABLE_BASE64
621 auto decode = [](
const std::string& token) {
622 return base::decode<alphabet::base64>(base::pad<alphabet::base64>(token));
653 std::error_code& ec) {
660 if (key.substr(0, 27) ==
"-----BEGIN CERTIFICATE-----") {
663 const int len =
static_cast<int>(epkey.size());
664 if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
669 const int len =
static_cast<int>(key.size());
670 if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
677 pubkey_bio.get(),
nullptr,
nullptr,
678 (
void*)password.data()));
707 std::error_code& ec) {
713 const int len =
static_cast<int>(key.size());
714 if (BIO_write(privkey_bio.get(), key.data(), len) != len) {
719 PEM_read_bio_PrivateKey(privkey_bio.get(),
nullptr,
nullptr,
const_cast<char*
>(password.c_str())));
748 std::error_code& ec) {
755 if (key.substr(0, 27) ==
"-----BEGIN CERTIFICATE-----") {
758 const int len =
static_cast<int>(epkey.size());
759 if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
764 const int len =
static_cast<int>(key.size());
765 if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
772 pubkey_bio.get(),
nullptr,
nullptr,
773 (
void*)password.data()));
788 const std::string& password =
"") {
803 std::error_code& ec) {
809 const int len =
static_cast<int>(key.size());
810 if (BIO_write(privkey_bio.get(), key.data(), len) != len) {
815 PEM_read_bio_PrivateKey(privkey_bio.get(),
nullptr,
nullptr,
const_cast<char*
>(password.c_str())));
828 const std::string& password =
"") {
841 #ifdef JWT_OPENSSL_1_0_0
849 std::string res(BN_num_bytes(bn),
'\0');
850 BN_bn2bin(bn, (
unsigned char*)res.data());
858 inline std::unique_ptr<BIGNUM, decltype(&BN_free)>
raw2bn(
const std::string& raw) {
859 return std::unique_ptr<BIGNUM, decltype(&BN_free)>(
860 BN_bin2bn(
reinterpret_cast<const unsigned char*
>(raw.data()),
static_cast<int>(raw.size()),
nullptr),
874 namespace algorithm {
884 std::string
sign(
const std::string& , std::error_code& ec)
const {
895 void verify(
const std::string& ,
const std::string& signature, std::error_code& ec)
const {
900 std::string
name()
const {
return "none"; }
913 : secret(
std::move(key)), md(md), alg_name(
std::move(
name)) {}
920 std::string
sign(
const std::string& data, std::error_code& ec)
const {
922 std::string res(
static_cast<size_t>(EVP_MAX_MD_SIZE),
'\0');
923 auto len =
static_cast<unsigned int>(res.size());
924 if (HMAC(md(), secret.data(),
static_cast<int>(secret.size()),
925 reinterpret_cast<const unsigned char*
>(data.data()),
static_cast<int>(data.size()),
926 (
unsigned char*)res.data(),
940 void verify(
const std::string& data,
const std::string& signature, std::error_code& ec)
const {
942 auto res =
sign(data, ec);
946 for (
size_t i = 0; i < std::min<size_t>(res.size(), signature.size());
i++)
947 if (res[
i] != signature[
i]) matched =
false;
948 if (res.size() != signature.size()) matched =
false;
958 std::string
name()
const {
return alg_name; }
962 const std::string secret;
964 const EVP_MD* (*md)();
966 const std::string alg_name;
981 rsa(
const std::string& public_key,
const std::string& private_key,
const std::string& public_key_password,
982 const std::string& private_key_password,
const EVP_MD* (*md)(), std::string
name)
983 : md(md), alg_name(
std::move(
name)) {
984 if (!private_key.empty()) {
986 }
else if (!public_key.empty()) {
997 std::string
sign(
const std::string& data, std::error_code& ec)
const {
1004 if (!EVP_SignInit(ctx.get(), md())) {
1009 std::string res(EVP_PKEY_size(pkey.
get()),
'\0');
1010 unsigned int len = 0;
1012 if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) {
1016 if (EVP_SignFinal(ctx.get(), (
unsigned char*)res.data(), &len, pkey.
get()) == 0) {
1030 void verify(
const std::string& data,
const std::string& signature, std::error_code& ec)
const {
1037 if (!EVP_VerifyInit(ctx.get(), md())) {
1041 if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) {
1045 auto res = EVP_VerifyFinal(ctx.get(),
reinterpret_cast<const unsigned char*
>(signature.data()),
1046 static_cast<unsigned int>(signature.size()), pkey.
get());
1056 std::string
name()
const {
return alg_name; }
1062 const EVP_MD* (*md)();
1064 const std::string alg_name;
1081 ecdsa(
const std::string& public_key,
const std::string& private_key,
const std::string& public_key_password,
1082 const std::string& private_key_password,
const EVP_MD* (*md)(), std::string
name,
size_t siglen)
1083 : md(md), alg_name(
std::move(
name)), signature_length(siglen) {
1084 if (!private_key.empty()) {
1086 check_private_key(pkey.
get());
1087 }
else if (!public_key.empty()) {
1089 check_public_key(pkey.
get());
1095 size_t keysize = EVP_PKEY_bits(pkey.
get());
1096 if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
1106 std::string
sign(
const std::string& data, std::error_code& ec)
const {
1113 if (!EVP_DigestSignInit(ctx.get(),
nullptr, md(),
nullptr, pkey.
get())) {
1117 if (!EVP_DigestUpdate(ctx.get(), data.data(), data.size())) {
1123 if (!EVP_DigestSignFinal(ctx.get(),
nullptr, &len)) {
1127 std::string res(len,
'\0');
1128 if (!EVP_DigestSignFinal(ctx.get(), (
unsigned char*)res.data(), &len)) {
1134 return der_to_p1363_signature(res, ec);
1143 void verify(
const std::string& data,
const std::string& signature, std::error_code& ec)
const {
1145 std::string der_signature = p1363_to_der_signature(signature, ec);
1153 if (!EVP_DigestVerifyInit(ctx.get(),
nullptr, md(),
nullptr, pkey.
get())) {
1157 if (!EVP_DigestUpdate(ctx.get(), data.data(), data.size())) {
1162 #if OPENSSL_VERSION_NUMBER < 0x10002000L
1163 unsigned char* der_sig_data =
reinterpret_cast<unsigned char*
>(
const_cast<char*
>(der_signature.data()));
1165 const unsigned char* der_sig_data =
reinterpret_cast<const unsigned char*
>(der_signature.data());
1168 EVP_DigestVerifyFinal(ctx.get(), der_sig_data,
static_cast<unsigned int>(der_signature.length()));
1182 std::string
name()
const {
return alg_name; }
1185 static void check_public_key(EVP_PKEY* pkey) {
1186 #ifdef JWT_OPENSSL_3_0
1187 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1188 EVP_PKEY_CTX_new_from_pkey(
nullptr, pkey,
nullptr), EVP_PKEY_CTX_free);
1190 if (EVP_PKEY_public_check(ctx.get()) != 1) {
1194 std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1200 static void check_private_key(EVP_PKEY* pkey) {
1201 #ifdef JWT_OPENSSL_3_0
1202 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1203 EVP_PKEY_CTX_new_from_pkey(
nullptr, pkey,
nullptr), EVP_PKEY_CTX_free);
1205 if (EVP_PKEY_private_check(ctx.get()) != 1) {
1209 std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1215 std::string der_to_p1363_signature(
const std::string& der_signature, std::error_code& ec)
const {
1216 const unsigned char* possl_signature =
reinterpret_cast<const unsigned char*
>(der_signature.data());
1217 std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(
1218 d2i_ECDSA_SIG(
nullptr, &possl_signature, der_signature.length()), ECDSA_SIG_free);
1224 #ifdef JWT_OPENSSL_1_0_0
1231 ECDSA_SIG_get0(sig.get(), &r, &
s);
1235 if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2)
1236 throw std::logic_error(
"bignum size exceeded expected length");
1237 rr.insert(0, signature_length / 2 - rr.size(),
'\0');
1238 rs.insert(0, signature_length / 2 - rs.size(),
'\0');
1242 std::string p1363_to_der_signature(
const std::string& signature, std::error_code& ec)
const {
1244 auto r =
helper::raw2bn(signature.substr(0, signature.size() / 2));
1248 #ifdef JWT_OPENSSL_1_0_0
1254 std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free);
1259 ECDSA_SIG_set0(sig.get(), r.release(),
s.release());
1263 int length = i2d_ECDSA_SIG(psig,
nullptr);
1268 std::string der_signature(length,
'\0');
1269 unsigned char* psbuffer = (
unsigned char*)der_signature.data();
1270 length = i2d_ECDSA_SIG(psig, &psbuffer);
1275 der_signature.resize(length);
1276 return der_signature;
1280 helper::evp_pkey_handle pkey;
1282 const EVP_MD* (*md)();
1284 const std::string alg_name;
1286 const size_t signature_length;
1289 #if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
1309 eddsa(
const std::string& public_key,
const std::string& private_key,
const std::string& public_key_password,
1310 const std::string& private_key_password, std::string
name)
1312 if (!private_key.empty()) {
1314 }
else if (!public_key.empty()) {
1325 std::string
sign(
const std::string& data, std::error_code& ec)
const {
1332 if (!EVP_DigestSignInit(ctx.get(),
nullptr,
nullptr,
nullptr, pkey.get())) {
1337 size_t len = EVP_PKEY_size(pkey.get());
1338 std::string res(len,
'\0');
1343 #if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1345 if (EVP_DigestSignUpdate(ctx.get(),
reinterpret_cast<const unsigned char*
>(data.data()), data.size()) !=
1347 std::cout << ERR_error_string(ERR_get_error(), NULL) << std::endl;
1351 if (EVP_DigestSignFinal(ctx.get(),
reinterpret_cast<unsigned char*
>(&res[0]), &len) != 1) {
1356 if (EVP_DigestSign(ctx.get(),
reinterpret_cast<unsigned char*
>(&res[0]), &len,
1357 reinterpret_cast<const unsigned char*
>(data.data()), data.size()) != 1) {
1373 void verify(
const std::string& data,
const std::string& signature, std::error_code& ec)
const {
1380 if (!EVP_DigestVerifyInit(ctx.get(),
nullptr,
nullptr,
nullptr, pkey.get())) {
1387 #if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1388 if (EVP_DigestVerifyUpdate(ctx.get(),
reinterpret_cast<const unsigned char*
>(data.data()),
1389 data.size()) != 1) {
1393 if (EVP_DigestVerifyFinal(ctx.get(),
reinterpret_cast<const unsigned char*
>(signature.data()),
1394 signature.size()) != 1) {
1399 auto res = EVP_DigestVerify(ctx.get(),
reinterpret_cast<const unsigned char*
>(signature.data()),
1400 signature.size(),
reinterpret_cast<const unsigned char*
>(data.data()),
1412 std::string
name()
const {
return alg_name; }
1418 const std::string alg_name;
1434 pss(
const std::string& public_key,
const std::string& private_key,
const std::string& public_key_password,
1435 const std::string& private_key_password,
const EVP_MD* (*md)(), std::string
name)
1436 : md(md), alg_name(
std::move(
name)) {
1437 if (!private_key.empty()) {
1439 }
else if (!public_key.empty()) {
1451 std::string
sign(
const std::string& data, std::error_code& ec)
const {
1458 EVP_PKEY_CTX* ctx =
nullptr;
1459 if (EVP_DigestSignInit(md_ctx.get(), &ctx, md(),
nullptr, pkey.get()) != 1) {
1463 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
1469 #ifndef LIBWOLFSSL_VERSION_HEX
1470 if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
1475 if (EVP_DigestUpdate(md_ctx.get(), data.data(), data.size()) != 1) {
1480 size_t size = EVP_PKEY_size(pkey.get());
1481 std::string res(size, 0x00);
1482 if (EVP_DigestSignFinal(
1484 (
unsigned char*)res.data(),
1499 void verify(
const std::string& data,
const std::string& signature, std::error_code& ec)
const {
1507 EVP_PKEY_CTX* ctx =
nullptr;
1508 if (EVP_DigestVerifyInit(md_ctx.get(), &ctx, md(),
nullptr, pkey.get()) != 1) {
1512 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
1518 #ifndef LIBWOLFSSL_VERSION_HEX
1519 if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
1524 if (EVP_DigestUpdate(md_ctx.get(), data.data(), data.size()) != 1) {
1529 if (EVP_DigestVerifyFinal(md_ctx.get(), (
unsigned char*)signature.data(), signature.size()) <= 0) {
1538 std::string
name()
const {
return alg_name; }
1544 const EVP_MD* (*md)();
1546 const std::string alg_name;
1590 explicit rs256(
const std::string& public_key,
const std::string& private_key =
"",
1591 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1592 :
rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256,
"RS256") {}
1605 explicit rs384(
const std::string& public_key,
const std::string& private_key =
"",
1606 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1607 :
rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384,
"RS384") {}
1620 explicit rs512(
const std::string& public_key,
const std::string& private_key =
"",
1621 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1622 :
rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512,
"RS512") {}
1637 explicit es256(
const std::string& public_key,
const std::string& private_key =
"",
1638 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1639 :
ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256,
"ES256", 64) {}
1654 explicit es384(
const std::string& public_key,
const std::string& private_key =
"",
1655 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1656 :
ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384,
"ES384", 96) {}
1671 explicit es512(
const std::string& public_key,
const std::string& private_key =
"",
1672 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1673 :
ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512,
"ES512", 132) {}
1687 explicit es256k(
const std::string& public_key,
const std::string& private_key =
"",
1688 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1689 :
ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256,
"ES256K", 64) {}
1692 #if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
1710 explicit ed25519(
const std::string& public_key,
const std::string& private_key =
"",
1711 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1712 :
eddsa(public_key, private_key, public_key_password, private_key_password,
"EdDSA") {}
1732 explicit ed448(
const std::string& public_key,
const std::string& private_key =
"",
1733 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1734 :
eddsa(public_key, private_key, public_key_password, private_key_password,
"EdDSA") {}
1749 explicit ps256(
const std::string& public_key,
const std::string& private_key =
"",
1750 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1751 :
pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256,
"PS256") {}
1764 explicit ps384(
const std::string& public_key,
const std::string& private_key =
"",
1765 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1766 :
pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384,
"PS384") {}
1779 explicit ps512(
const std::string& public_key,
const std::string& private_key =
"",
1780 const std::string& public_key_password =
"",
const std::string& private_key_password =
"")
1781 :
pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512,
"PS512") {}
1798 #ifdef __cpp_lib_void_t
1799 template<
typename... Ts>
1803 template<
typename... Ts>
1808 template<
typename... Ts>
1812 #ifdef __cpp_lib_experimental_detect
1813 template<
template<
typename...>
class _Op,
typename... _Args>
1816 template<
template<
typename...>
class _Op,
typename... _Args>
1829 template<
class Default,
class AlwaysVoid,
template<
class...>
class Op,
class... Args>
1835 template<
class Default,
template<
class...>
class Op,
class... Args>
1841 template<
template<
class...>
class Op,
class... Args>
1844 template<
template<
class...>
class Op,
class... Args>
1848 template<
typename traits_type>
1851 template<
typename traits_type,
typename value_type>
1853 typename std::is_same<get_type_function<traits_type>,
json::type(
const value_type&)>;
1855 template<
typename traits_type,
typename value_type>
1858 std::is_function<get_type_function<traits_type>>
::value &&
1862 template<
typename traits_type>
1865 template<
typename traits_type,
typename value_type,
typename object_type>
1867 typename std::is_same<as_object_function<traits_type>,
object_type(
const value_type&)>;
1869 template<
typename traits_type,
typename value_type,
typename object_type>
1871 static constexpr
auto value = std::is_constructible<value_type, object_type>::value &&
1873 std::is_function<as_object_function<traits_type>>
::value &&
1877 template<
typename traits_type>
1880 template<
typename traits_type,
typename value_type,
typename array_type>
1882 typename std::is_same<as_array_function<traits_type>,
array_type(
const value_type&)>;
1884 template<
typename traits_type,
typename value_type,
typename array_type>
1886 static constexpr
auto value = std::is_constructible<value_type, array_type>::value &&
1888 std::is_function<as_array_function<traits_type>>
::value &&
1892 template<
typename traits_type>
1895 template<
typename traits_type,
typename value_type,
typename string_type>
1897 typename std::is_same<as_string_function<traits_type>,
string_type(
const value_type&)>;
1899 template<
typename traits_type,
typename value_type,
typename string_type>
1901 static constexpr
auto value = std::is_constructible<value_type, string_type>::value &&
1903 std::is_function<as_string_function<traits_type>>
::value &&
1907 template<
typename traits_type>
1910 template<
typename traits_type,
typename value_type,
typename number_type>
1912 typename std::is_same<as_number_function<traits_type>,
number_type(
const value_type&)>;
1914 template<
typename traits_type,
typename value_type,
typename number_type>
1916 static constexpr
auto value = std::is_floating_point<number_type>::value &&
1917 std::is_constructible<value_type, number_type>::value &&
1919 std::is_function<as_number_function<traits_type>>
::value &&
1923 template<
typename traits_type>
1926 template<
typename traits_type,
typename value_type,
typename integer_type>
1928 typename std::is_same<as_integer_function<traits_type>, integer_type(
const value_type&)>;
1930 template<
typename traits_type,
typename value_type,
typename integer_type>
1932 static constexpr
auto value = std::is_signed<integer_type>::value &&
1933 !std::is_floating_point<integer_type>::value &&
1934 std::is_constructible<value_type, integer_type>::value &&
1936 std::is_function<as_integer_function<traits_type>>
::value &&
1940 template<
typename traits_type>
1943 template<
typename traits_type,
typename value_type,
typename boolean_type>
1945 typename std::is_same<as_boolean_function<traits_type>,
boolean_type(
const value_type&)>;
1947 template<
typename traits_type,
typename value_type,
typename boolean_type>
1949 static constexpr
auto value = std::is_convertible<boolean_type, bool>::value &&
1950 std::is_constructible<value_type, boolean_type>::value &&
1952 std::is_function<as_boolean_function<traits_type>>
::value &&
1956 template<
typename traits>
1960 "traits must provide `jwt::json::type get_type(const value_type&)`");
1962 "traits must provide `object_type as_object(const value_type&)`");
1964 "traits must provide `array_type as_array(const value_type&)`");
1966 "traits must provide `string_type as_string(const value_type&)`");
1968 "traits must provide `number_type as_number(const value_type&)`");
1971 "traits must provide `integer_type as_int(const value_type&)`");
1974 "traits must provide `boolean_type as_bool(const value_type&)`");
1986 template<
typename value_type>
1989 std::is_default_constructible<value_type>::value &&
1990 std::is_constructible<value_type, const value_type&>::value &&
1991 std::is_move_constructible<value_type>::value && std::is_assignable<value_type, value_type>::value &&
1992 std::is_copy_assignable<value_type>::value && std::is_move_assignable<value_type>::value;
1996 template<
typename traits_type>
1999 template<
typename traits_type>
2002 template<
typename traits_type>
2005 template<
typename object_type>
2008 template<
typename object_type>
2011 template<
typename object_type>
2015 template<
typename object_type>
2019 template<
typename object_type>
2026 template<
typename object_type>
2030 template<
typename object_type>
2034 template<
typename object_type>
2041 template<
typename object_type,
typename string_type>
2042 using is_count_signature =
typename std::is_integral<decltype(std::declval<const object_type>().count(
2043 std::declval<const string_type>()))>;
2045 template<
typename object_type,
typename string_type>
2050 template<
class T,
class A0>
2053 template<
class,
class A0>
2056 static constexpr
auto value = decltype(test_operator_plus<object_type, string_type>(0)){};
2059 template<
typename object_type,
typename value_type,
typename string_type>
2063 "object_type must implementate the subscription operator '[]' for this library");
2068 template<
typename object_type,
typename value_type,
typename string_type>
2070 typename std::is_same<decltype(std::declval<const object_type>().at(std::declval<const string_type>())),
2073 template<
typename value_type,
typename string_type,
typename object_type>
2077 std::is_same<typename object_type::mapped_type, value_type>::value &&
2079 (std::is_same<typename object_type::key_type, string_type>::value ||
2080 std::is_constructible<typename object_type::key_type, string_type>::value) &&
2087 template<
typename value_type,
typename array_type>
2089 static constexpr
auto value = std::is_same<typename array_type::value_type, value_type>::value;
2092 template<
typename string_type,
typename integer_type>
2094 typename std::is_same<decltype(std::declval<string_type>().substr(std::declval<integer_type>(),
2095 std::declval<integer_type>())),
2098 template<
typename string_type,
typename integer_type>
2100 typename std::is_same<decltype(std::declval<string_type>().substr(std::declval<integer_type>())),
2103 template<
typename string_type>
2108 template<
class T,
class A0>
2111 template<
class,
class A0>
2114 static constexpr
auto value = decltype(test_operator_plus<string_type, string_type>(0)){};
2117 template<
typename string_type>
2119 typename std::is_same<decltype(std::operator+(std::declval<string_type>(), std::declval<string_type>())),
2122 template<
typename string_type,
typename integer_type>
2126 static_assert(
substr,
"string_type must have a substr method taking only a start index and an overload "
2127 "taking a start and end index, both must return a string_type");
2132 "string_type must have a '+' operator implemented which returns the concatenated string");
2142 "value_type must meet basic requirements, default constructor, copyable, moveable");
2144 "object_type must be a string_type to value_type container");
2146 "array_type must be a container of value_type");
2162 template<
typename json_traits>
2170 static_assert(std::is_same<typename json_traits::string_type, std::string>::value ||
2171 std::is_convertible<typename json_traits::string_type, std::string>::value ||
2172 std::is_constructible<typename json_traits::string_type, std::string>::value,
2173 "string_type must be a std::string, convertible to a std::string, or construct a std::string.");
2179 "must staisfy json container requirements");
2182 typename json_traits::value_type val;
2185 using set_t = std::set<typename json_traits::string_type>;
2196 : val(typename json_traits::integer_type(
std::chrono::system_clock::to_time_t(d))) {}
2200 template<
typename Iterator>
2207 typename json_traits::value_type
to_json()
const {
return val; }
2244 using std::chrono::system_clock;
2246 return system_clock::from_time_t(
as_int());
2263 for (
const auto& e : json_traits::as_array(val)) {
2264 res.insert(json_traits::as_string(e));
2274 typename json_traits::integer_type
as_int()
const {
return json_traits::as_int(val); }
2307 template<
typename json_traits>
2311 using iterator =
typename json_traits::object_type::iterator;
2338 typename json_traits::value_type val;
2341 return json_traits::as_object(val);
2349 return claims.count(name) != 0;
2370 template<
typename json_traits>
2437 return aud.as_set();
2488 template<
typename json_traits>
2563 template<
typename json_traits>
2583 #ifndef JWT_DISABLE_BASE64
2595 return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(str));
2609 template<
typename Decode>
2611 auto hdr_end =
token.find(
'.');
2612 if (hdr_end == json_traits::string_type::npos)
throw std::invalid_argument(
"invalid token supplied");
2613 auto payload_end =
token.find(
'.', hdr_end + 1);
2614 if (payload_end == json_traits::string_type::npos)
throw std::invalid_argument(
"invalid token supplied");
2698 template<
typename json_traits>
2712 header_claims[id] = std::move(
c);
2723 header_claims[id] =
c.to_json();
2733 payload_claims[id] = std::move(
c);
2743 payload_claims[id] =
c.to_json();
2851 template<
typename Algo,
typename Encode>
2858 #ifndef JWT_DISABLE_BASE64
2867 template<
typename Algo>
2870 auto res =
sign(algo, ec);
2888 template<
typename Algo,
typename Encode>
2892 if (header_claims.count(
"alg") == 0) obj_header[
"alg"] =
typename json_traits::value_type(algo.name());
2894 const auto header =
encode(json_traits::serialize(
typename json_traits::value_type(obj_header)));
2895 const auto payload =
encode(json_traits::serialize(
typename json_traits::value_type(payload_claims)));
2898 auto signature = algo.sign(token, ec);
2901 return token +
"." +
encode(signature);
2903 #ifndef JWT_DISABLE_BASE64
2913 template<
typename Algo>
2918 return base::trim<alphabet::base64url>(base::encode<alphabet::base64url>(data));
2925 namespace verify_ops {
2929 template<
typename json_traits>
2962 if (
c.get_type() != t) {
2977 template<
typename json_traits,
bool in_header = false>
2983 const bool matches = [&]() {
2991 return json_traits::serialize(
expected.to_json()) == json_traits::serialize(jc.to_json());
2992 default:
throw std::logic_error(
"internal error, should be unreachable");
3006 template<
typename json_traits,
bool in_header = false>
3012 auto c = jc.as_date();
3023 template<
typename json_traits,
bool in_header = false>
3029 auto c = jc.as_date();
3041 template<
typename json_traits,
bool in_header = false>
3053 auto jc =
c.as_set();
3055 if (jc.find(e) == jc.end()) {
3070 template<
typename json_traits,
bool in_header = false>
3086 #if __cplusplus > 201103L
3087 std::wstring_convert<std::codecvt_utf8<wchar_t>,
wchar_t> conv;
3088 auto wide = conv.from_bytes(str);
3089 auto&
f = std::use_facet<std::ctype<wchar_t>>(loc);
3090 f.tolower(&wide[0], &wide[0] + wide.size());
3091 return conv.to_bytes(wide);
3094 std::transform(str.begin(), str.end(), std::back_inserter(result),
3095 [&loc](
unsigned char c) { return std::tolower(c, loc); });
3106 template<
typename Clock,
typename json_traits>
3124 virtual ~algo_base() =
default;
3125 virtual void verify(
const std::string& data,
const std::string& sig, std::error_code& ec) = 0;
3127 template<
typename T>
3128 struct algo :
public algo_base {
3130 explicit algo(T a) : alg(a) {}
3131 void verify(
const std::string& data,
const std::string& sig, std::error_code& ec)
override {
3132 alg.verify(data, sig, ec);
3136 std::unordered_map<typename json_traits::string_type, verify_check_fn_t> claims;
3138 size_t default_leeway = 0;
3142 std::unordered_map<std::string, std::shared_ptr<algo_base>> algs;
3151 if (!ctx.
jwt.has_expires_at())
return;
3152 auto exp = ctx.
jwt.get_expires_at();
3158 if (!ctx.
jwt.has_issued_at())
return;
3159 auto iat = ctx.
jwt.get_issued_at();
3165 if (!ctx.
jwt.has_not_before())
return;
3166 auto nbf = ctx.
jwt.get_not_before();
3302 template<
typename Algorithm>
3304 algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg);
3327 const std::string algo =
jwt.get_algorithm();
3328 if (algs.count(algo) == 0) {
3332 algs.at(algo)->verify(data, sig, ec);
3336 for (
auto&
c : claims) {
3337 ctx.claim_key =
c.first;
3352 template<
typename json_traits>
3359 : jwk_claims(details::map_of_claims<json_traits>::parse_claims(str)) {}
3362 : jwk_claims(json_traits::as_object(json)) {}
3460 return json_traits::as_string(x5c_array.front());
3540 bool empty() const noexcept {
return jwk_claims.empty(); }
3559 template<
typename json_traits>
3568 typename json_traits::value_type parsed_val;
3574 auto jwk_list = jwks_json.
get_claim(
"keys").as_array();
3575 std::transform(jwk_list.begin(), jwk_list.end(), std::back_inserter(jwk_claims),
3576 [](
const typename json_traits::value_type& val) { return jwk_t{val}; });
3591 return find_by_kid(key_id) != end();
3600 const auto maybe = find_by_kid(key_id);
3606 jwt_vector_t jwk_claims;
3609 return std::find_if(cbegin(), cend(), [key_id](
const jwk_t&
jwk) {
3621 template<
typename Clock,
typename json_traits>
3638 template<
typename json_traits>
3640 return verifier<default_clock, json_traits>(
c);
3646 template<
typename json_traits>
3659 template<
typename json_traits,
typename Decode>
3671 template<
typename json_traits>
3676 template<
typename json_traits>
3681 template<
typename json_traits>
3687 template<
typename json_traits>
3689 return c.operator>>(is);
3692 template<
typename json_traits>
3694 return os <<
c.to_json();
3697 #ifndef JWT_DISABLE_PICOJSON