JWT-CPP v0.7.0
A header only library for creating and validating JSON Web Tokens (JWT) in C++
Loading...
Searching...
No Matches
jwt.h
1#ifndef JWT_CPP_JWT_H
2#define JWT_CPP_JWT_H
3
4#ifndef JWT_DISABLE_PICOJSON
5#ifndef PICOJSON_USE_INT64
6#define PICOJSON_USE_INT64
7#endif
8#include "picojson/picojson.h"
9#endif
10
11#ifndef JWT_DISABLE_BASE64
12#include "base.h"
13#endif
14
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>
23
24#include <algorithm>
25#include <chrono>
26#include <climits>
27#include <cmath>
28#include <cstring>
29#include <functional>
30#include <iterator>
31#include <locale>
32#include <memory>
33#include <set>
34#include <system_error>
35#include <type_traits>
36#include <unordered_map>
37#include <utility>
38#include <vector>
39
40#if __cplusplus >= 201402L
41#ifdef __has_include
42#if __has_include(<experimental/type_traits>)
43#include <experimental/type_traits>
44#endif
45#endif
46#endif
47
48#if OPENSSL_VERSION_NUMBER >= 0x30000000L // 3.0.0
49#define JWT_OPENSSL_3_0
50#include <openssl/param_build.h>
51#elif OPENSSL_VERSION_NUMBER >= 0x10101000L // 1.1.1
52#define JWT_OPENSSL_1_1_1
53#elif OPENSSL_VERSION_NUMBER >= 0x10100000L // 1.1.0
54#define JWT_OPENSSL_1_1_0
55#elif OPENSSL_VERSION_NUMBER >= 0x10000000L // 1.0.0
56#define JWT_OPENSSL_1_0_0
57#endif
58
59#if defined(LIBRESSL_VERSION_NUMBER)
60#if LIBRESSL_VERSION_NUMBER >= 0x3050300fL
61#define JWT_OPENSSL_1_1_0
62#else
63#define JWT_OPENSSL_1_0_0
64#endif
65#endif
66
67#if defined(LIBWOLFSSL_VERSION_HEX)
68#define JWT_OPENSSL_1_1_1
69#endif
70
71#ifndef JWT_CLAIM_EXPLICIT
72#define JWT_CLAIM_EXPLICIT explicit
73#endif
74
82namespace jwt {
86 using date = std::chrono::system_clock::time_point;
87
91 namespace error {
92 struct signature_verification_exception : public std::system_error {
93 using system_error::system_error;
94 };
95 struct signature_generation_exception : public std::system_error {
96 using system_error::system_error;
97 };
98 struct rsa_exception : public std::system_error {
99 using system_error::system_error;
100 };
101 struct ecdsa_exception : public std::system_error {
102 using system_error::system_error;
103 };
104 struct token_verification_exception : public std::system_error {
105 using system_error::system_error;
106 };
110 enum class rsa_error {
111 ok = 0,
112 cert_load_failed = 10,
113 get_key_failed,
114 write_key_failed,
115 write_cert_failed,
116 convert_to_pem_failed,
117 load_key_bio_write,
118 load_key_bio_read,
119 create_mem_bio_failed,
120 no_key_provided,
121 set_rsa_failed,
122 create_context_failed
123 };
127 inline std::error_category& rsa_error_category() {
128 class rsa_error_cat : public std::error_category {
129 public:
130 const char* name() const noexcept override { return "rsa_error"; };
131 std::string message(int ev) const override {
132 switch (static_cast<rsa_error>(ev)) {
133 case rsa_error::ok: return "no error";
134 case rsa_error::cert_load_failed: return "error loading cert into memory";
135 case rsa_error::get_key_failed: return "error getting key from certificate";
136 case rsa_error::write_key_failed: return "error writing key data in PEM format";
137 case rsa_error::write_cert_failed: return "error writing cert data in PEM format";
138 case rsa_error::convert_to_pem_failed: return "failed to convert key to pem";
139 case rsa_error::load_key_bio_write: return "failed to load key: bio write failed";
140 case rsa_error::load_key_bio_read: return "failed to load key: bio read failed";
141 case rsa_error::create_mem_bio_failed: return "failed to create memory bio";
142 case rsa_error::no_key_provided: return "at least one of public or private key need to be present";
143 case rsa_error::set_rsa_failed: return "set modulus and exponent to RSA failed";
144 case rsa_error::create_context_failed: return "failed to create context";
145 default: return "unknown RSA error";
146 }
147 }
148 };
149 static rsa_error_cat cat;
150 return cat;
151 }
155 inline std::error_code make_error_code(rsa_error e) { return {static_cast<int>(e), rsa_error_category()}; }
159 enum class ecdsa_error {
160 ok = 0,
161 load_key_bio_write = 10,
162 load_key_bio_read,
163 create_mem_bio_failed,
164 no_key_provided,
165 invalid_key_size,
166 invalid_key,
167 create_context_failed,
168 cert_load_failed,
169 get_key_failed,
170 write_key_failed,
171 write_cert_failed,
172 convert_to_pem_failed,
173 unknown_curve,
174 set_ecdsa_failed
175 };
179 inline std::error_category& ecdsa_error_category() {
180 class ecdsa_error_cat : public std::error_category {
181 public:
182 const char* name() const noexcept override { return "ecdsa_error"; };
183 std::string message(int ev) const override {
184 switch (static_cast<ecdsa_error>(ev)) {
185 case ecdsa_error::ok: return "no error";
186 case ecdsa_error::load_key_bio_write: return "failed to load key: bio write failed";
187 case ecdsa_error::load_key_bio_read: return "failed to load key: bio read failed";
188 case ecdsa_error::create_mem_bio_failed: return "failed to create memory bio";
189 case ecdsa_error::no_key_provided:
190 return "at least one of public or private key need to be present";
191 case ecdsa_error::invalid_key_size: return "invalid key size";
192 case ecdsa_error::invalid_key: return "invalid key";
193 case ecdsa_error::create_context_failed: return "failed to create context";
194 case ecdsa_error::cert_load_failed: return "error loading cert into memory";
195 case ecdsa_error::get_key_failed: return "error getting key from certificate";
196 case ecdsa_error::write_key_failed: return "error writing key data in PEM format";
197 case ecdsa_error::write_cert_failed: return "error writing cert data in PEM format";
198 case ecdsa_error::convert_to_pem_failed: return "failed to convert key to pem";
199 case ecdsa_error::unknown_curve: return "unknown curve";
200 case ecdsa_error::set_ecdsa_failed: return "set parameters to ECDSA failed";
201 default: return "unknown ECDSA error";
202 }
203 }
204 };
205 static ecdsa_error_cat cat;
206 return cat;
207 }
211 inline std::error_code make_error_code(ecdsa_error e) { return {static_cast<int>(e), ecdsa_error_category()}; }
212
217 ok = 0,
218 invalid_signature = 10,
219 create_context_failed,
220 verifyinit_failed,
221 verifyupdate_failed,
222 verifyfinal_failed,
223 get_key_failed,
224 set_rsa_pss_saltlen_failed,
225 signature_encoding_failed
226 };
230 inline std::error_category& signature_verification_error_category() {
231 class verification_error_cat : public std::error_category {
232 public:
233 const char* name() const noexcept override { return "signature_verification_error"; };
234 std::string message(int ev) const override {
235 switch (static_cast<signature_verification_error>(ev)) {
236 case signature_verification_error::ok: return "no error";
237 case signature_verification_error::invalid_signature: return "invalid signature";
238 case signature_verification_error::create_context_failed:
239 return "failed to verify signature: could not create context";
240 case signature_verification_error::verifyinit_failed:
241 return "failed to verify signature: VerifyInit failed";
242 case signature_verification_error::verifyupdate_failed:
243 return "failed to verify signature: VerifyUpdate failed";
244 case signature_verification_error::verifyfinal_failed:
245 return "failed to verify signature: VerifyFinal failed";
246 case signature_verification_error::get_key_failed:
247 return "failed to verify signature: Could not get key";
248 case signature_verification_error::set_rsa_pss_saltlen_failed:
249 return "failed to verify signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
250 case signature_verification_error::signature_encoding_failed:
251 return "failed to verify signature: i2d_ECDSA_SIG failed";
252 default: return "unknown signature verification error";
253 }
254 }
255 };
256 static verification_error_cat cat;
257 return cat;
258 }
263 return {static_cast<int>(e), signature_verification_error_category()};
264 }
265
270 ok = 0,
271 hmac_failed = 10,
272 create_context_failed,
273 signinit_failed,
274 signupdate_failed,
275 signfinal_failed,
276 ecdsa_do_sign_failed,
277 digestinit_failed,
278 digestupdate_failed,
279 digestfinal_failed,
280 rsa_padding_failed,
281 rsa_private_encrypt_failed,
282 get_key_failed,
283 set_rsa_pss_saltlen_failed,
284 signature_decoding_failed
285 };
289 inline std::error_category& signature_generation_error_category() {
290 class signature_generation_error_cat : public std::error_category {
291 public:
292 const char* name() const noexcept override { return "signature_generation_error"; };
293 std::string message(int ev) const override {
294 switch (static_cast<signature_generation_error>(ev)) {
295 case signature_generation_error::ok: return "no error";
296 case signature_generation_error::hmac_failed: return "hmac failed";
297 case signature_generation_error::create_context_failed:
298 return "failed to create signature: could not create context";
299 case signature_generation_error::signinit_failed:
300 return "failed to create signature: SignInit failed";
301 case signature_generation_error::signupdate_failed:
302 return "failed to create signature: SignUpdate failed";
303 case signature_generation_error::signfinal_failed:
304 return "failed to create signature: SignFinal failed";
305 case signature_generation_error::ecdsa_do_sign_failed: return "failed to generate ecdsa signature";
306 case signature_generation_error::digestinit_failed:
307 return "failed to create signature: DigestInit failed";
308 case signature_generation_error::digestupdate_failed:
309 return "failed to create signature: DigestUpdate failed";
310 case signature_generation_error::digestfinal_failed:
311 return "failed to create signature: DigestFinal failed";
312 case signature_generation_error::rsa_padding_failed:
313 return "failed to create signature: EVP_PKEY_CTX_set_rsa_padding failed";
314 case signature_generation_error::rsa_private_encrypt_failed:
315 return "failed to create signature: RSA_private_encrypt failed";
316 case signature_generation_error::get_key_failed:
317 return "failed to generate signature: Could not get key";
318 case signature_generation_error::set_rsa_pss_saltlen_failed:
319 return "failed to create signature: EVP_PKEY_CTX_set_rsa_pss_saltlen failed";
320 case signature_generation_error::signature_decoding_failed:
321 return "failed to create signature: d2i_ECDSA_SIG failed";
322 default: return "unknown signature generation error";
323 }
324 }
325 };
326 static signature_generation_error_cat cat = {};
327 return cat;
328 }
332 inline std::error_code make_error_code(signature_generation_error e) {
333 return {static_cast<int>(e), signature_generation_error_category()};
334 }
335
340 ok = 0,
341 wrong_algorithm = 10,
342 missing_claim,
343 claim_type_missmatch,
344 claim_value_missmatch,
345 token_expired,
346 audience_missmatch
347 };
351 inline std::error_category& token_verification_error_category() {
352 class token_verification_error_cat : public std::error_category {
353 public:
354 const char* name() const noexcept override { return "token_verification_error"; };
355 std::string message(int ev) const override {
356 switch (static_cast<token_verification_error>(ev)) {
357 case token_verification_error::ok: return "no error";
358 case token_verification_error::wrong_algorithm: return "wrong algorithm";
359 case token_verification_error::missing_claim: return "decoded JWT is missing required claim(s)";
360 case token_verification_error::claim_type_missmatch:
361 return "claim type does not match expected type";
362 case token_verification_error::claim_value_missmatch:
363 return "claim value does not match expected value";
364 case token_verification_error::token_expired: return "token expired";
365 case token_verification_error::audience_missmatch:
366 return "token doesn't contain the required audience";
367 default: return "unknown token verification error";
368 }
369 }
370 };
371 static token_verification_error_cat cat = {};
372 return cat;
373 }
377 inline std::error_code make_error_code(token_verification_error e) {
378 return {static_cast<int>(e), token_verification_error_category()};
379 }
383 inline void throw_if_error(std::error_code ec) {
384 if (ec) {
385 if (ec.category() == rsa_error_category()) throw rsa_exception(ec);
386 if (ec.category() == ecdsa_error_category()) throw ecdsa_exception(ec);
387 if (ec.category() == signature_verification_error_category())
390 if (ec.category() == token_verification_error_category()) throw token_verification_exception(ec);
391 }
392 }
393 } // namespace error
394} // namespace jwt
395
396namespace std {
397 template<>
398 struct is_error_code_enum<jwt::error::rsa_error> : true_type {};
399 template<>
400 struct is_error_code_enum<jwt::error::ecdsa_error> : true_type {};
401 template<>
402 struct is_error_code_enum<jwt::error::signature_verification_error> : true_type {};
403 template<>
404 struct is_error_code_enum<jwt::error::signature_generation_error> : true_type {};
405 template<>
406 struct is_error_code_enum<jwt::error::token_verification_error> : true_type {};
407} // namespace std
408
409namespace jwt {
417 namespace helper {
426 public:
430 constexpr evp_pkey_handle() noexcept = default;
431#ifdef JWT_OPENSSL_1_0_0
436 explicit evp_pkey_handle(EVP_PKEY* key) { m_key = std::shared_ptr<EVP_PKEY>(key, EVP_PKEY_free); }
437
438 EVP_PKEY* get() const noexcept { return m_key.get(); }
439 bool operator!() const noexcept { return m_key == nullptr; }
440 explicit operator bool() const noexcept { return m_key != nullptr; }
441
442 private:
443 std::shared_ptr<EVP_PKEY> m_key{nullptr};
444#else
449 explicit constexpr evp_pkey_handle(EVP_PKEY* key) noexcept : m_key{key} {}
450 evp_pkey_handle(const evp_pkey_handle& other) : m_key{other.m_key} {
451 if (m_key != nullptr && EVP_PKEY_up_ref(m_key) != 1) throw std::runtime_error("EVP_PKEY_up_ref failed");
452 }
453// C++11 requires the body of a constexpr constructor to be empty
454#if __cplusplus >= 201402L
455 constexpr
456#endif
457 evp_pkey_handle(evp_pkey_handle&& other) noexcept
458 : m_key{other.m_key} {
459 other.m_key = nullptr;
460 }
461 evp_pkey_handle& operator=(const evp_pkey_handle& other) {
462 if (&other == this) return *this;
463 decrement_ref_count(m_key);
464 m_key = other.m_key;
465 increment_ref_count(m_key);
466 return *this;
467 }
468 evp_pkey_handle& operator=(evp_pkey_handle&& other) noexcept {
469 if (&other == this) return *this;
470 decrement_ref_count(m_key);
471 m_key = other.m_key;
472 other.m_key = nullptr;
473 return *this;
474 }
475 evp_pkey_handle& operator=(EVP_PKEY* key) {
476 decrement_ref_count(m_key);
477 m_key = key;
478 increment_ref_count(m_key);
479 return *this;
480 }
481 ~evp_pkey_handle() noexcept { decrement_ref_count(m_key); }
482
483 EVP_PKEY* get() const noexcept { return m_key; }
484 bool operator!() const noexcept { return m_key == nullptr; }
485 explicit operator bool() const noexcept { return m_key != nullptr; }
486
487 private:
488 EVP_PKEY* m_key{nullptr};
489
490 static void increment_ref_count(EVP_PKEY* key) {
491 if (key != nullptr && EVP_PKEY_up_ref(key) != 1) throw std::runtime_error("EVP_PKEY_up_ref failed");
492 }
493 static void decrement_ref_count(EVP_PKEY* key) noexcept {
494 if (key != nullptr) EVP_PKEY_free(key);
495 }
496#endif
497 };
498
499 inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio() {
500 return std::unique_ptr<BIO, decltype(&BIO_free_all)>(BIO_new(BIO_s_mem()), BIO_free_all);
501 }
502
503 inline std::unique_ptr<BIO, decltype(&BIO_free_all)> make_mem_buf_bio(const std::string& data) {
504 return std::unique_ptr<BIO, decltype(&BIO_free_all)>(
505#if OPENSSL_VERSION_NUMBER <= 0x10100003L
506 BIO_new_mem_buf(const_cast<char*>(data.data()), static_cast<int>(data.size())), BIO_free_all
507#else
508 BIO_new_mem_buf(data.data(), static_cast<int>(data.size())), BIO_free_all
509#endif
510 );
511 }
512
513 template<typename error_category = error::rsa_error>
514 std::string write_bio_to_string(std::unique_ptr<BIO, decltype(&BIO_free_all)>& bio_out, std::error_code& ec) {
515 char* ptr = nullptr;
516 auto len = BIO_get_mem_data(bio_out.get(), &ptr);
517 if (len <= 0 || ptr == nullptr) {
518 ec = error_category::convert_to_pem_failed;
519 return {};
520 }
521 return {ptr, static_cast<size_t>(len)};
522 }
523
524 inline std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX*)> make_evp_md_ctx() {
525 return
526#ifdef JWT_OPENSSL_1_0_0
527 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
528#else
529 std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
530#endif
531 }
532
541 template<typename error_category = error::rsa_error>
542 std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw, std::error_code& ec) {
543 ec.clear();
544 auto certbio = make_mem_buf_bio(certstr);
545 auto keybio = make_mem_buf_bio();
546 if (!certbio || !keybio) {
547 ec = error_category::create_mem_bio_failed;
548 return {};
549 }
550
551 std::unique_ptr<X509, decltype(&X509_free)> cert(
552 PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast<char*>(pw.c_str())), X509_free);
553 if (!cert) {
554 ec = error_category::cert_load_failed;
555 return {};
556 }
557 std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)> key(X509_get_pubkey(cert.get()), EVP_PKEY_free);
558 if (!key) {
559 ec = error_category::get_key_failed;
560 return {};
561 }
562 if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) {
563 ec = error_category::write_key_failed;
564 return {};
565 }
566
567 return write_bio_to_string<error_category>(keybio, ec);
568 }
569
578 template<typename error_category = error::rsa_error>
579 std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") {
580 std::error_code ec;
581 auto res = extract_pubkey_from_cert<error_category>(certstr, pw, ec);
583 return res;
584 }
585
592 inline std::string convert_der_to_pem(const std::string& cert_der_str, std::error_code& ec) {
593 ec.clear();
594
595 auto c_str = reinterpret_cast<const unsigned char*>(cert_der_str.c_str());
596
597 std::unique_ptr<X509, decltype(&X509_free)> cert(
598 d2i_X509(NULL, &c_str, static_cast<int>(cert_der_str.size())), X509_free);
599 auto certbio = make_mem_buf_bio();
600 if (!cert || !certbio) {
601 ec = error::rsa_error::create_mem_bio_failed;
602 return {};
603 }
604
605 if (!PEM_write_bio_X509(certbio.get(), cert.get())) {
606 ec = error::rsa_error::write_cert_failed;
607 return {};
608 }
609
610 return write_bio_to_string(certbio, ec);
611 }
612
627 template<typename Decode>
628 std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode,
629 std::error_code& ec) {
630 ec.clear();
631 const auto decoded_str = decode(cert_base64_der_str);
632 return convert_der_to_pem(decoded_str, ec);
633 }
634
649 template<typename Decode>
650 std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode) {
651 std::error_code ec;
652 auto res = convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
654 return res;
655 }
656
663 inline std::string convert_der_to_pem(const std::string& cert_der_str) {
664 std::error_code ec;
665 auto res = convert_der_to_pem(cert_der_str, ec);
667 return res;
668 }
669
670#ifndef JWT_DISABLE_BASE64
680 inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) {
681 auto decode = [](const std::string& token) {
682 return base::decode<alphabet::base64>(base::pad<alphabet::base64>(token));
683 };
684 return convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec);
685 }
686
696 inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) {
697 std::error_code ec;
698 auto res = convert_base64_der_to_pem(cert_base64_der_str, ec);
700 return res;
701 }
702#endif
713 template<typename error_category = error::rsa_error>
714 evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password,
715 std::error_code& ec) {
716 ec.clear();
717 auto pubkey_bio = make_mem_buf_bio();
718 if (!pubkey_bio) {
719 ec = error_category::create_mem_bio_failed;
720 return {};
721 }
722 if (key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") {
723 auto epkey = helper::extract_pubkey_from_cert<error_category>(key, password, ec);
724 if (ec) return {};
725 const int len = static_cast<int>(epkey.size());
726 if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) {
727 ec = error_category::load_key_bio_write;
728 return {};
729 }
730 } else {
731 const int len = static_cast<int>(key.size());
732 if (BIO_write(pubkey_bio.get(), key.data(), len) != len) {
733 ec = error_category::load_key_bio_write;
734 return {};
735 }
736 }
737
738 evp_pkey_handle pkey(PEM_read_bio_PUBKEY(
739 pubkey_bio.get(), nullptr, nullptr,
740 (void*)password.data())); // NOLINT(google-readability-casting) requires `const_cast`
741 if (!pkey) ec = error_category::load_key_bio_read;
742 return pkey;
743 }
744
755 template<typename error_category = error::rsa_error>
756 inline evp_pkey_handle load_public_key_from_string(const std::string& key, const std::string& password = "") {
757 std::error_code ec;
758 auto res = load_public_key_from_string<error_category>(key, password, ec);
760 return res;
761 }
762
771 template<typename error_category = error::rsa_error>
772 inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password,
773 std::error_code& ec) {
774 ec.clear();
775 auto private_key_bio = make_mem_buf_bio();
776 if (!private_key_bio) {
777 ec = error_category::create_mem_bio_failed;
778 return {};
779 }
780 const int len = static_cast<int>(key.size());
781 if (BIO_write(private_key_bio.get(), key.data(), len) != len) {
782 ec = error_category::load_key_bio_write;
783 return {};
784 }
785 evp_pkey_handle pkey(
786 PEM_read_bio_PrivateKey(private_key_bio.get(), nullptr, nullptr, const_cast<char*>(password.c_str())));
787 if (!pkey) ec = error_category::load_key_bio_read;
788 return pkey;
789 }
790
799 template<typename error_category = error::rsa_error>
800 inline evp_pkey_handle load_private_key_from_string(const std::string& key, const std::string& password = "") {
801 std::error_code ec;
802 auto res = load_private_key_from_string<error_category>(key, password, ec);
804 return res;
805 }
806
818 inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key, const std::string& password,
819 std::error_code& ec) {
820 return load_public_key_from_string<error::ecdsa_error>(key, password, ec);
821 }
822
828 inline
829#ifdef JWT_OPENSSL_1_0_0
830 std::string
831 bn2raw(BIGNUM* bn)
832#else
833 std::string
834 bn2raw(const BIGNUM* bn)
835#endif
836 {
837 std::string res(BN_num_bytes(bn), '\0');
838 BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast`
839 return res;
840 }
847 inline std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw, std::error_code& ec) {
848 auto bn =
849 BN_bin2bn(reinterpret_cast<const unsigned char*>(raw.data()), static_cast<int>(raw.size()), nullptr);
850 // https://www.openssl.org/docs/man1.1.1/man3/BN_bin2bn.html#RETURN-VALUES
851 if (!bn) {
852 ec = error::rsa_error::set_rsa_failed;
853 return {nullptr, BN_free};
854 }
855 return {bn, BN_free};
856 }
862 inline std::unique_ptr<BIGNUM, decltype(&BN_free)> raw2bn(const std::string& raw) {
863 std::error_code ec;
864 auto res = raw2bn(raw, ec);
866 return res;
867 }
868
880 inline evp_pkey_handle load_public_ec_key_from_string(const std::string& key,
881 const std::string& password = "") {
882 std::error_code ec;
883 auto res = load_public_key_from_string<error::ecdsa_error>(key, password, ec);
885 return res;
886 }
887
897 inline evp_pkey_handle load_private_ec_key_from_string(const std::string& key, const std::string& password,
898 std::error_code& ec) {
899 return load_private_key_from_string<error::ecdsa_error>(key, password, ec);
900 }
901
916 template<typename Decode>
917 std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
918 Decode decode, std::error_code& ec) {
919 ec.clear();
920 auto decoded_modulus = decode(modulus);
921 auto decoded_exponent = decode(exponent);
922
923 auto n = helper::raw2bn(decoded_modulus, ec);
924 if (ec) return {};
925 auto e = helper::raw2bn(decoded_exponent, ec);
926 if (ec) return {};
927
928#if defined(JWT_OPENSSL_3_0)
929 // OpenSSL deprecated mutable keys and there is a new way for making them
930 // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
931 // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
932 std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
933 OSSL_PARAM_BLD_free);
934 if (!param_bld) {
935 ec = error::rsa_error::create_context_failed;
936 return {};
937 }
938
939 if (OSSL_PARAM_BLD_push_BN(param_bld.get(), "n", n.get()) != 1 ||
940 OSSL_PARAM_BLD_push_BN(param_bld.get(), "e", e.get()) != 1) {
941 ec = error::rsa_error::set_rsa_failed;
942 return {};
943 }
944
945 std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
946 OSSL_PARAM_free);
947 if (!params) {
948 ec = error::rsa_error::set_rsa_failed;
949 return {};
950 }
951
952 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
953 EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free);
954 if (!ctx) {
955 ec = error::rsa_error::create_context_failed;
956 return {};
957 }
958
959 // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
960 // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
961 EVP_PKEY* pkey = NULL;
962 if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
963 EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
964 // It's unclear if this can fail after allocating but free it anyways
965 // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
966 EVP_PKEY_free(pkey);
967
968 ec = error::rsa_error::cert_load_failed;
969 return {};
970 }
971
972 // Transfer ownership so we get ref counter and cleanup
973 evp_pkey_handle rsa(pkey);
974
975#else
976 std::unique_ptr<RSA, decltype(&RSA_free)> rsa(RSA_new(), RSA_free);
977
978#if defined(JWT_OPENSSL_1_1_1) || defined(JWT_OPENSSL_1_1_0)
979 // After this RSA_free will also free the n and e big numbers
980 // See https://github.com/Thalhammer/jwt-cpp/pull/298#discussion_r1282619186
981 if (RSA_set0_key(rsa.get(), n.get(), e.get(), nullptr) == 1) {
982 // This can only fail we passed in NULL for `n` or `e`
983 // https://github.com/openssl/openssl/blob/d6e4056805f54bb1a0ef41fa3a6a35b70c94edba/crypto/rsa/rsa_lib.c#L396
984 // So to make sure there is no memory leak, we hold the references
985 n.release();
986 e.release();
987 } else {
988 ec = error::rsa_error::set_rsa_failed;
989 return {};
990 }
991#elif defined(JWT_OPENSSL_1_0_0)
992 rsa->e = e.release();
993 rsa->n = n.release();
994 rsa->d = nullptr;
995#endif
996#endif
997
998 auto pub_key_bio = make_mem_buf_bio();
999 if (!pub_key_bio) {
1000 ec = error::rsa_error::create_mem_bio_failed;
1001 return {};
1002 }
1003
1004 auto write_pem_to_bio =
1005#if defined(JWT_OPENSSL_3_0)
1006 // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_RSA_PUBKEY.html
1007 &PEM_write_bio_PUBKEY;
1008#else
1009 &PEM_write_bio_RSA_PUBKEY;
1010#endif
1011 if (write_pem_to_bio(pub_key_bio.get(), rsa.get()) != 1) {
1012 ec = error::rsa_error::load_key_bio_write;
1013 return {};
1014 }
1015
1016 return write_bio_to_string<error::rsa_error>(pub_key_bio, ec);
1017 }
1018
1032 template<typename Decode>
1033 std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent,
1034 Decode decode) {
1035 std::error_code ec;
1036 auto res = create_public_key_from_rsa_components(modulus, exponent, decode, ec);
1038 return res;
1039 }
1040
1041#ifndef JWT_DISABLE_BASE64
1052 inline std::string create_public_key_from_rsa_components(const std::string& modulus,
1053 const std::string& exponent, std::error_code& ec) {
1054 auto decode = [](const std::string& token) {
1055 return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
1056 };
1057 return create_public_key_from_rsa_components(modulus, exponent, std::move(decode), ec);
1058 }
1068 inline std::string create_public_key_from_rsa_components(const std::string& modulus,
1069 const std::string& exponent) {
1070 std::error_code ec;
1071 auto res = create_public_key_from_rsa_components(modulus, exponent, ec);
1073 return res;
1074 }
1075#endif
1086 const std::string& password = "") {
1087 std::error_code ec;
1088 auto res = load_private_key_from_string<error::ecdsa_error>(key, password, ec);
1090 return res;
1091 }
1092
1093#if defined(JWT_OPENSSL_3_0)
1094
1102 inline std::string curve2group(const std::string curve, std::error_code& ec) {
1103 if (curve == "P-256") {
1104 return "prime256v1";
1105 } else if (curve == "P-384") {
1106 return "secp384r1";
1107 } else if (curve == "P-521") {
1108 return "secp521r1";
1109 } else {
1110 ec = jwt::error::ecdsa_error::unknown_curve;
1111 return {};
1112 }
1113 }
1114
1115#else
1116
1124 inline int curve2nid(const std::string curve, std::error_code& ec) {
1125 if (curve == "P-256") {
1126 return NID_X9_62_prime256v1;
1127 } else if (curve == "P-384") {
1128 return NID_secp384r1;
1129 } else if (curve == "P-521") {
1130 return NID_secp521r1;
1131 } else {
1132 ec = jwt::error::ecdsa_error::unknown_curve;
1133 return {};
1134 }
1135 }
1136
1137#endif
1138
1154 template<typename Decode>
1155 std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1156 const std::string& y, Decode decode, std::error_code& ec) {
1157 ec.clear();
1158 auto decoded_x = decode(x);
1159 auto decoded_y = decode(y);
1160
1161#if defined(JWT_OPENSSL_3_0)
1162 // OpenSSL deprecated mutable keys and there is a new way for making them
1163 // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html
1164 // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2
1165 std::unique_ptr<OSSL_PARAM_BLD, decltype(&OSSL_PARAM_BLD_free)> param_bld(OSSL_PARAM_BLD_new(),
1166 OSSL_PARAM_BLD_free);
1167 if (!param_bld) {
1168 ec = error::ecdsa_error::create_context_failed;
1169 return {};
1170 }
1171
1172 std::string group = helper::curve2group(curve, ec);
1173 if (ec) return {};
1174
1175 // https://github.com/openssl/openssl/issues/16270#issuecomment-895734092
1176 std::string pub = std::string("\x04").append(decoded_x).append(decoded_y);
1177
1178 if (OSSL_PARAM_BLD_push_utf8_string(param_bld.get(), "group", group.data(), group.size()) != 1 ||
1179 OSSL_PARAM_BLD_push_octet_string(param_bld.get(), "pub", pub.data(), pub.size()) != 1) {
1180 ec = error::ecdsa_error::set_ecdsa_failed;
1181 return {};
1182 }
1183
1184 std::unique_ptr<OSSL_PARAM, decltype(&OSSL_PARAM_free)> params(OSSL_PARAM_BLD_to_param(param_bld.get()),
1185 OSSL_PARAM_free);
1186 if (!params) {
1187 ec = error::ecdsa_error::set_ecdsa_failed;
1188 return {};
1189 }
1190
1191 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1192 EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr), EVP_PKEY_CTX_free);
1193 if (!ctx) {
1194 ec = error::ecdsa_error::create_context_failed;
1195 return {};
1196 }
1197
1198 // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES
1199 // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES
1200 EVP_PKEY* pkey = NULL;
1201 if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 ||
1202 EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) {
1203 // It's unclear if this can fail after allocating but free it anyways
1204 // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html
1205 EVP_PKEY_free(pkey);
1206
1207 ec = error::ecdsa_error::cert_load_failed;
1208 return {};
1209 }
1210
1211 // Transfer ownership so we get ref counter and cleanup
1212 evp_pkey_handle ecdsa(pkey);
1213
1214#else
1215 int nid = helper::curve2nid(curve, ec);
1216 if (ec) return {};
1217
1218 auto qx = helper::raw2bn(decoded_x, ec);
1219 if (ec) return {};
1220 auto qy = helper::raw2bn(decoded_y, ec);
1221 if (ec) return {};
1222
1223 std::unique_ptr<EC_GROUP, decltype(&EC_GROUP_free)> ecgroup(EC_GROUP_new_by_curve_name(nid), EC_GROUP_free);
1224 if (!ecgroup) {
1225 ec = error::ecdsa_error::set_ecdsa_failed;
1226 return {};
1227 }
1228
1229 EC_GROUP_set_asn1_flag(ecgroup.get(), OPENSSL_EC_NAMED_CURVE);
1230
1231 std::unique_ptr<EC_POINT, decltype(&EC_POINT_free)> ecpoint(EC_POINT_new(ecgroup.get()), EC_POINT_free);
1232 if (!ecpoint ||
1233 EC_POINT_set_affine_coordinates_GFp(ecgroup.get(), ecpoint.get(), qx.get(), qy.get(), nullptr) != 1) {
1234 ec = error::ecdsa_error::set_ecdsa_failed;
1235 return {};
1236 }
1237
1238 std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> ecdsa(EC_KEY_new(), EC_KEY_free);
1239 if (!ecdsa || EC_KEY_set_group(ecdsa.get(), ecgroup.get()) != 1 ||
1240 EC_KEY_set_public_key(ecdsa.get(), ecpoint.get()) != 1) {
1241 ec = error::ecdsa_error::set_ecdsa_failed;
1242 return {};
1243 }
1244
1245#endif
1246
1247 auto pub_key_bio = make_mem_buf_bio();
1248 if (!pub_key_bio) {
1249 ec = error::ecdsa_error::create_mem_bio_failed;
1250 return {};
1251 }
1252
1253 auto write_pem_to_bio =
1254#if defined(JWT_OPENSSL_3_0)
1255 // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_EC_PUBKEY.html
1256 &PEM_write_bio_PUBKEY;
1257#else
1258 &PEM_write_bio_EC_PUBKEY;
1259#endif
1260 if (write_pem_to_bio(pub_key_bio.get(), ecdsa.get()) != 1) {
1261 ec = error::ecdsa_error::load_key_bio_write;
1262 return {};
1263 }
1264
1265 return write_bio_to_string<error::ecdsa_error>(pub_key_bio, ec);
1266 }
1267
1282 template<typename Decode>
1283 std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1284 const std::string& y, Decode decode) {
1285 std::error_code ec;
1286 auto res = create_public_key_from_ec_components(curve, x, y, decode, ec);
1288 return res;
1289 }
1290
1291#ifndef JWT_DISABLE_BASE64
1303 inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1304 const std::string& y, std::error_code& ec) {
1305 auto decode = [](const std::string& token) {
1306 return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(token));
1307 };
1308 return create_public_key_from_ec_components(curve, x, y, std::move(decode), ec);
1309 }
1320 inline std::string create_public_key_from_ec_components(const std::string& curve, const std::string& x,
1321 const std::string& y) {
1322 std::error_code ec;
1323 auto res = create_public_key_from_ec_components(curve, x, y, ec);
1325 return res;
1326 }
1327#endif
1328 } // namespace helper
1329
1339 namespace algorithm {
1347 struct none {
1351 std::string sign(const std::string& /*unused*/, std::error_code& ec) const {
1352 ec.clear();
1353 return {};
1354 }
1362 void verify(const std::string& /*unused*/, const std::string& signature, std::error_code& ec) const {
1363 ec.clear();
1364 if (!signature.empty()) { ec = error::signature_verification_error::invalid_signature; }
1365 }
1367 std::string name() const { return "none"; }
1368 };
1372 struct hmacsha {
1380 hmacsha(std::string key, const EVP_MD* (*md)(), std::string name)
1381 : secret(std::move(key)), md(md), alg_name(std::move(name)) {}
1389 std::string sign(const std::string& data, std::error_code& ec) const {
1390 ec.clear();
1391 std::string res(static_cast<size_t>(EVP_MAX_MD_SIZE), '\0');
1392 auto len = static_cast<unsigned int>(res.size());
1393 if (HMAC(md(), secret.data(), static_cast<int>(secret.size()),
1394 reinterpret_cast<const unsigned char*>(data.data()), static_cast<int>(data.size()),
1395 (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
1396 &len) == nullptr) {
1397 ec = error::signature_generation_error::hmac_failed;
1398 return {};
1399 }
1400 res.resize(len);
1401 return res;
1402 }
1410 void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
1411 ec.clear();
1412 auto res = sign(data, ec);
1413 if (ec) return;
1414
1415 bool matched = true;
1416 for (size_t i = 0; i < std::min<size_t>(res.size(), signature.size()); i++)
1417 if (res[i] != signature[i]) matched = false;
1418 if (res.size() != signature.size()) matched = false;
1419 if (!matched) {
1420 ec = error::signature_verification_error::invalid_signature;
1421 return;
1422 }
1423 }
1429 std::string name() const { return alg_name; }
1430
1431 private:
1433 const std::string secret;
1435 const EVP_MD* (*md)();
1437 const std::string alg_name;
1438 };
1442 struct rsa {
1453 rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
1454 const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
1455 : md(md), alg_name(std::move(name)) {
1456 if (!private_key.empty()) {
1457 pkey = helper::load_private_key_from_string(private_key, private_key_password);
1458 } else if (!public_key.empty()) {
1459 pkey = helper::load_public_key_from_string(public_key, public_key_password);
1460 } else
1461 throw error::rsa_exception(error::rsa_error::no_key_provided);
1462 }
1469 std::string sign(const std::string& data, std::error_code& ec) const {
1470 ec.clear();
1471 auto ctx = helper::make_evp_md_ctx();
1472 if (!ctx) {
1473 ec = error::signature_generation_error::create_context_failed;
1474 return {};
1475 }
1476 if (!EVP_SignInit(ctx.get(), md())) {
1477 ec = error::signature_generation_error::signinit_failed;
1478 return {};
1479 }
1480
1481 std::string res(EVP_PKEY_size(pkey.get()), '\0');
1482 unsigned int len = 0;
1483
1484 if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) {
1485 ec = error::signature_generation_error::signupdate_failed;
1486 return {};
1487 }
1488 if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) {
1489 ec = error::signature_generation_error::signfinal_failed;
1490 return {};
1491 }
1492
1493 res.resize(len);
1494 return res;
1495 }
1503 void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
1504 ec.clear();
1505 auto ctx = helper::make_evp_md_ctx();
1506 if (!ctx) {
1507 ec = error::signature_verification_error::create_context_failed;
1508 return;
1509 }
1510 if (!EVP_VerifyInit(ctx.get(), md())) {
1511 ec = error::signature_verification_error::verifyinit_failed;
1512 return;
1513 }
1514 if (!EVP_VerifyUpdate(ctx.get(), data.data(), data.size())) {
1515 ec = error::signature_verification_error::verifyupdate_failed;
1516 return;
1517 }
1518 auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
1519 static_cast<unsigned int>(signature.size()), pkey.get());
1520 if (res != 1) {
1521 ec = error::signature_verification_error::verifyfinal_failed;
1522 return;
1523 }
1524 }
1529 std::string name() const { return alg_name; }
1530
1531 private:
1535 const EVP_MD* (*md)();
1537 const std::string alg_name;
1538 };
1542 struct ecdsa {
1554 ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
1555 const std::string& private_key_password, const EVP_MD* (*md)(), std::string name, size_t siglen)
1556 : md(md), alg_name(std::move(name)), signature_length(siglen) {
1557 if (!private_key.empty()) {
1558 pkey = helper::load_private_ec_key_from_string(private_key, private_key_password);
1559 check_private_key(pkey.get());
1560 } else if (!public_key.empty()) {
1561 pkey = helper::load_public_ec_key_from_string(public_key, public_key_password);
1562 check_public_key(pkey.get());
1563 } else {
1564 throw error::ecdsa_exception(error::ecdsa_error::no_key_provided);
1565 }
1566 if (!pkey) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1567
1568 size_t keysize = EVP_PKEY_bits(pkey.get());
1569 if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521))
1570 throw error::ecdsa_exception(error::ecdsa_error::invalid_key_size);
1571 }
1572
1579 std::string sign(const std::string& data, std::error_code& ec) const {
1580 ec.clear();
1581 auto ctx = helper::make_evp_md_ctx();
1582 if (!ctx) {
1583 ec = error::signature_generation_error::create_context_failed;
1584 return {};
1585 }
1586 if (!EVP_DigestSignInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
1587 ec = error::signature_generation_error::signinit_failed;
1588 return {};
1589 }
1590 if (!EVP_DigestUpdate(ctx.get(), data.data(), data.size())) {
1591 ec = error::signature_generation_error::digestupdate_failed;
1592 return {};
1593 }
1594
1595 size_t len = 0;
1596 if (!EVP_DigestSignFinal(ctx.get(), nullptr, &len)) {
1597 ec = error::signature_generation_error::signfinal_failed;
1598 return {};
1599 }
1600 std::string res(len, '\0');
1601 if (!EVP_DigestSignFinal(ctx.get(), (unsigned char*)res.data(), &len)) {
1602 ec = error::signature_generation_error::signfinal_failed;
1603 return {};
1604 }
1605
1606 res.resize(len);
1607 return der_to_p1363_signature(res, ec);
1608 }
1609
1616 void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
1617 ec.clear();
1618 std::string der_signature = p1363_to_der_signature(signature, ec);
1619 if (ec) { return; }
1620
1621 auto ctx = helper::make_evp_md_ctx();
1622 if (!ctx) {
1623 ec = error::signature_verification_error::create_context_failed;
1624 return;
1625 }
1626 if (!EVP_DigestVerifyInit(ctx.get(), nullptr, md(), nullptr, pkey.get())) {
1627 ec = error::signature_verification_error::verifyinit_failed;
1628 return;
1629 }
1630 if (!EVP_DigestUpdate(ctx.get(), data.data(), data.size())) {
1631 ec = error::signature_verification_error::verifyupdate_failed;
1632 return;
1633 }
1634
1635#if OPENSSL_VERSION_NUMBER < 0x10002000L
1636 unsigned char* der_sig_data = reinterpret_cast<unsigned char*>(const_cast<char*>(der_signature.data()));
1637#else
1638 const unsigned char* der_sig_data = reinterpret_cast<const unsigned char*>(der_signature.data());
1639#endif
1640 auto res =
1641 EVP_DigestVerifyFinal(ctx.get(), der_sig_data, static_cast<unsigned int>(der_signature.length()));
1642 if (res == 0) {
1643 ec = error::signature_verification_error::invalid_signature;
1644 return;
1645 }
1646 if (res == -1) {
1647 ec = error::signature_verification_error::verifyfinal_failed;
1648 return;
1649 }
1650 }
1655 std::string name() const { return alg_name; }
1656
1657 private:
1658 static void check_public_key(EVP_PKEY* pkey) {
1659#ifdef JWT_OPENSSL_3_0
1660 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1661 EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
1662 if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
1663 if (EVP_PKEY_public_check(ctx.get()) != 1) {
1664 throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1665 }
1666#else
1667 std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1668 if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1669 if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1670#endif
1671 }
1672
1673 static void check_private_key(EVP_PKEY* pkey) {
1674#ifdef JWT_OPENSSL_3_0
1675 std::unique_ptr<EVP_PKEY_CTX, decltype(&EVP_PKEY_CTX_free)> ctx(
1676 EVP_PKEY_CTX_new_from_pkey(nullptr, pkey, nullptr), EVP_PKEY_CTX_free);
1677 if (!ctx) { throw error::ecdsa_exception(error::ecdsa_error::create_context_failed); }
1678 if (EVP_PKEY_private_check(ctx.get()) != 1) {
1679 throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1680 }
1681#else
1682 std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> eckey(EVP_PKEY_get1_EC_KEY(pkey), EC_KEY_free);
1683 if (!eckey) { throw error::ecdsa_exception(error::ecdsa_error::invalid_key); }
1684 if (EC_KEY_check_key(eckey.get()) == 0) throw error::ecdsa_exception(error::ecdsa_error::invalid_key);
1685#endif
1686 }
1687
1688 std::string der_to_p1363_signature(const std::string& der_signature, std::error_code& ec) const {
1689 const unsigned char* possl_signature = reinterpret_cast<const unsigned char*>(der_signature.data());
1690 std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(
1691 d2i_ECDSA_SIG(nullptr, &possl_signature, static_cast<long>(der_signature.length())),
1692 ECDSA_SIG_free);
1693 if (!sig) {
1694 ec = error::signature_generation_error::signature_decoding_failed;
1695 return {};
1696 }
1697
1698#ifdef JWT_OPENSSL_1_0_0
1699 auto rr = helper::bn2raw(sig->r);
1700 auto rs = helper::bn2raw(sig->s);
1701#else
1702 const BIGNUM* r;
1703 const BIGNUM* s;
1704 ECDSA_SIG_get0(sig.get(), &r, &s);
1705 auto rr = helper::bn2raw(r);
1706 auto rs = helper::bn2raw(s);
1707#endif
1708 if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2)
1709 throw std::logic_error("bignum size exceeded expected length");
1710 rr.insert(0, signature_length / 2 - rr.size(), '\0');
1711 rs.insert(0, signature_length / 2 - rs.size(), '\0');
1712 return rr + rs;
1713 }
1714
1715 std::string p1363_to_der_signature(const std::string& signature, std::error_code& ec) const {
1716 ec.clear();
1717 auto r = helper::raw2bn(signature.substr(0, signature.size() / 2), ec);
1718 if (ec) return {};
1719 auto s = helper::raw2bn(signature.substr(signature.size() / 2), ec);
1720 if (ec) return {};
1721
1722 ECDSA_SIG* psig;
1723#ifdef JWT_OPENSSL_1_0_0
1724 ECDSA_SIG sig;
1725 sig.r = r.get();
1726 sig.s = s.get();
1727 psig = &sig;
1728#else
1729 std::unique_ptr<ECDSA_SIG, decltype(&ECDSA_SIG_free)> sig(ECDSA_SIG_new(), ECDSA_SIG_free);
1730 if (!sig) {
1731 ec = error::signature_verification_error::create_context_failed;
1732 return {};
1733 }
1734 ECDSA_SIG_set0(sig.get(), r.release(), s.release());
1735 psig = sig.get();
1736#endif
1737
1738 int length = i2d_ECDSA_SIG(psig, nullptr);
1739 if (length < 0) {
1740 ec = error::signature_verification_error::signature_encoding_failed;
1741 return {};
1742 }
1743 std::string der_signature(length, '\0');
1744 unsigned char* psbuffer = (unsigned char*)der_signature.data();
1745 length = i2d_ECDSA_SIG(psig, &psbuffer);
1746 if (length < 0) {
1747 ec = error::signature_verification_error::signature_encoding_failed;
1748 return {};
1749 }
1750 der_signature.resize(length);
1751 return der_signature;
1752 }
1753
1755 helper::evp_pkey_handle pkey;
1757 const EVP_MD* (*md)();
1759 const std::string alg_name;
1761 const size_t signature_length;
1762 };
1763
1764#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
1773 struct eddsa {
1784 eddsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
1785 const std::string& private_key_password, std::string name)
1786 : alg_name(std::move(name)) {
1787 if (!private_key.empty()) {
1788 pkey = helper::load_private_key_from_string(private_key, private_key_password);
1789 } else if (!public_key.empty()) {
1790 pkey = helper::load_public_key_from_string(public_key, public_key_password);
1791 } else
1792 throw error::ecdsa_exception(error::ecdsa_error::load_key_bio_read);
1793 }
1800 std::string sign(const std::string& data, std::error_code& ec) const {
1801 ec.clear();
1802 auto ctx = helper::make_evp_md_ctx();
1803 if (!ctx) {
1804 ec = error::signature_generation_error::create_context_failed;
1805 return {};
1806 }
1807 if (!EVP_DigestSignInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
1808 ec = error::signature_generation_error::signinit_failed;
1809 return {};
1810 }
1811
1812 size_t len = EVP_PKEY_size(pkey.get());
1813 std::string res(len, '\0');
1814
1815// LibreSSL is the special kid in the block, as it does not support EVP_DigestSign.
1816// OpenSSL on the otherhand does not support using EVP_DigestSignUpdate for eddsa, which is why we end up with this
1817// mess.
1818#if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1819 ERR_clear_error();
1820 if (EVP_DigestSignUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()), data.size()) !=
1821 1) {
1822 std::cout << ERR_error_string(ERR_get_error(), NULL) << std::endl;
1823 ec = error::signature_generation_error::signupdate_failed;
1824 return {};
1825 }
1826 if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len) != 1) {
1827 ec = error::signature_generation_error::signfinal_failed;
1828 return {};
1829 }
1830#else
1831 if (EVP_DigestSign(ctx.get(), reinterpret_cast<unsigned char*>(&res[0]), &len,
1832 reinterpret_cast<const unsigned char*>(data.data()), data.size()) != 1) {
1833 ec = error::signature_generation_error::signfinal_failed;
1834 return {};
1835 }
1836#endif
1837
1838 res.resize(len);
1839 return res;
1840 }
1841
1848 void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
1849 ec.clear();
1850 auto ctx = helper::make_evp_md_ctx();
1851 if (!ctx) {
1852 ec = error::signature_verification_error::create_context_failed;
1853 return;
1854 }
1855 if (!EVP_DigestVerifyInit(ctx.get(), nullptr, nullptr, nullptr, pkey.get())) {
1856 ec = error::signature_verification_error::verifyinit_failed;
1857 return;
1858 }
1859// LibreSSL is the special kid in the block, as it does not support EVP_DigestVerify.
1860// OpenSSL on the otherhand does not support using EVP_DigestVerifyUpdate for eddsa, which is why we end up with this
1861// mess.
1862#if defined(LIBRESSL_VERSION_NUMBER) || defined(LIBWOLFSSL_VERSION_HEX)
1863 if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast<const unsigned char*>(data.data()),
1864 data.size()) != 1) {
1865 ec = error::signature_verification_error::verifyupdate_failed;
1866 return;
1867 }
1868 if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
1869 signature.size()) != 1) {
1870 ec = error::signature_verification_error::verifyfinal_failed;
1871 return;
1872 }
1873#else
1874 auto res = EVP_DigestVerify(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()),
1875 signature.size(), reinterpret_cast<const unsigned char*>(data.data()),
1876 data.size());
1877 if (res != 1) {
1878 ec = error::signature_verification_error::verifyfinal_failed;
1879 return;
1880 }
1881#endif
1882 }
1887 std::string name() const { return alg_name; }
1888
1889 private:
1893 const std::string alg_name;
1894 };
1895#endif
1899 struct pss {
1909 pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password,
1910 const std::string& private_key_password, const EVP_MD* (*md)(), std::string name)
1911 : md(md), alg_name(std::move(name)) {
1912 if (!private_key.empty()) {
1913 pkey = helper::load_private_key_from_string(private_key, private_key_password);
1914 } else if (!public_key.empty()) {
1915 pkey = helper::load_public_key_from_string(public_key, public_key_password);
1916 } else
1917 throw error::rsa_exception(error::rsa_error::no_key_provided);
1918 }
1919
1926 std::string sign(const std::string& data, std::error_code& ec) const {
1927 ec.clear();
1928 auto md_ctx = helper::make_evp_md_ctx();
1929 if (!md_ctx) {
1930 ec = error::signature_generation_error::create_context_failed;
1931 return {};
1932 }
1933 EVP_PKEY_CTX* ctx = nullptr;
1934 if (EVP_DigestSignInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
1935 ec = error::signature_generation_error::signinit_failed;
1936 return {};
1937 }
1938 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
1939 ec = error::signature_generation_error::rsa_padding_failed;
1940 return {};
1941 }
1942// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
1943// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
1944#ifndef LIBWOLFSSL_VERSION_HEX
1945 if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
1946 ec = error::signature_generation_error::set_rsa_pss_saltlen_failed;
1947 return {};
1948 }
1949#endif
1950 if (EVP_DigestUpdate(md_ctx.get(), data.data(), data.size()) != 1) {
1951 ec = error::signature_generation_error::digestupdate_failed;
1952 return {};
1953 }
1954
1955 size_t size = EVP_PKEY_size(pkey.get());
1956 std::string res(size, 0x00);
1957 if (EVP_DigestSignFinal(
1958 md_ctx.get(),
1959 (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast`
1960 &size) <= 0) {
1961 ec = error::signature_generation_error::signfinal_failed;
1962 return {};
1963 }
1964
1965 return res;
1966 }
1967
1974 void verify(const std::string& data, const std::string& signature, std::error_code& ec) const {
1975 ec.clear();
1976
1977 auto md_ctx = helper::make_evp_md_ctx();
1978 if (!md_ctx) {
1979 ec = error::signature_verification_error::create_context_failed;
1980 return;
1981 }
1982 EVP_PKEY_CTX* ctx = nullptr;
1983 if (EVP_DigestVerifyInit(md_ctx.get(), &ctx, md(), nullptr, pkey.get()) != 1) {
1984 ec = error::signature_verification_error::verifyinit_failed;
1985 return;
1986 }
1987 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
1988 ec = error::signature_generation_error::rsa_padding_failed;
1989 return;
1990 }
1991// wolfSSL does not require EVP_PKEY_CTX_set_rsa_pss_saltlen. The default behavior
1992// sets the salt length to the hash length. Unlike OpenSSL which exposes this functionality.
1993#ifndef LIBWOLFSSL_VERSION_HEX
1994 if (EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx, -1) <= 0) {
1995 ec = error::signature_verification_error::set_rsa_pss_saltlen_failed;
1996 return;
1997 }
1998#endif
1999 if (EVP_DigestUpdate(md_ctx.get(), data.data(), data.size()) != 1) {
2000 ec = error::signature_verification_error::verifyupdate_failed;
2001 return;
2002 }
2003
2004 if (EVP_DigestVerifyFinal(md_ctx.get(), (unsigned char*)signature.data(), signature.size()) <= 0) {
2005 ec = error::signature_verification_error::verifyfinal_failed;
2006 return;
2007 }
2008 }
2013 std::string name() const { return alg_name; }
2014
2015 private:
2019 const EVP_MD* (*md)();
2021 const std::string alg_name;
2022 };
2023
2027 struct hs256 : public hmacsha {
2032 explicit hs256(std::string key) : hmacsha(std::move(key), EVP_sha256, "HS256") {}
2033 };
2037 struct hs384 : public hmacsha {
2042 explicit hs384(std::string key) : hmacsha(std::move(key), EVP_sha384, "HS384") {}
2043 };
2047 struct hs512 : public hmacsha {
2052 explicit hs512(std::string key) : hmacsha(std::move(key), EVP_sha512, "HS512") {}
2053 };
2059 struct rs256 : public rsa {
2068 explicit rs256(const std::string& public_key, const std::string& private_key = "",
2069 const std::string& public_key_password = "", const std::string& private_key_password = "")
2070 : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") {}
2071 };
2075 struct rs384 : public rsa {
2083 explicit rs384(const std::string& public_key, const std::string& private_key = "",
2084 const std::string& public_key_password = "", const std::string& private_key_password = "")
2085 : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") {}
2086 };
2090 struct rs512 : public rsa {
2098 explicit rs512(const std::string& public_key, const std::string& private_key = "",
2099 const std::string& public_key_password = "", const std::string& private_key_password = "")
2100 : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") {}
2101 };
2105 struct es256 : public ecdsa {
2115 explicit es256(const std::string& public_key, const std::string& private_key = "",
2116 const std::string& public_key_password = "", const std::string& private_key_password = "")
2117 : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) {}
2118 };
2122 struct es384 : public ecdsa {
2132 explicit es384(const std::string& public_key, const std::string& private_key = "",
2133 const std::string& public_key_password = "", const std::string& private_key_password = "")
2134 : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) {}
2135 };
2139 struct es512 : public ecdsa {
2149 explicit es512(const std::string& public_key, const std::string& private_key = "",
2150 const std::string& public_key_password = "", const std::string& private_key_password = "")
2151 : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) {}
2152 };
2156 struct es256k : public ecdsa {
2165 explicit es256k(const std::string& public_key, const std::string& private_key = "",
2166 const std::string& public_key_password = "", const std::string& private_key_password = "")
2167 : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256K", 64) {}
2168 };
2169
2170#if !defined(JWT_OPENSSL_1_0_0) && !defined(JWT_OPENSSL_1_1_0)
2178 struct ed25519 : public eddsa {
2188 explicit ed25519(const std::string& public_key, const std::string& private_key = "",
2189 const std::string& public_key_password = "", const std::string& private_key_password = "")
2190 : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
2191 };
2192
2200 struct ed448 : public eddsa {
2210 explicit ed448(const std::string& public_key, const std::string& private_key = "",
2211 const std::string& public_key_password = "", const std::string& private_key_password = "")
2212 : eddsa(public_key, private_key, public_key_password, private_key_password, "EdDSA") {}
2213 };
2214#endif
2215
2219 struct ps256 : public pss {
2227 explicit ps256(const std::string& public_key, const std::string& private_key = "",
2228 const std::string& public_key_password = "", const std::string& private_key_password = "")
2229 : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") {}
2230 };
2234 struct ps384 : public pss {
2242 explicit ps384(const std::string& public_key, const std::string& private_key = "",
2243 const std::string& public_key_password = "", const std::string& private_key_password = "")
2244 : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") {}
2245 };
2249 struct ps512 : public pss {
2257 explicit ps512(const std::string& public_key, const std::string& private_key = "",
2258 const std::string& public_key_password = "", const std::string& private_key_password = "")
2259 : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") {}
2260 };
2261 } // namespace algorithm
2262
2266 namespace json {
2274 enum class type { boolean, integer, number, string, array, object };
2275 } // namespace json
2276
2277 namespace details {
2278#ifdef __cpp_lib_void_t
2279 template<typename... Ts>
2280 using void_t = std::void_t<Ts...>;
2281#else
2282 // https://en.cppreference.com/w/cpp/types/void_t
2283 template<typename... Ts>
2284 struct make_void {
2285 using type = void;
2286 };
2287
2288 template<typename... Ts>
2289 using void_t = typename make_void<Ts...>::type;
2290#endif
2291
2292#ifdef __cpp_lib_experimental_detect
2293 template<template<typename...> class _Op, typename... _Args>
2294 using is_detected = std::experimental::is_detected<_Op, _Args...>;
2295#else
2296 struct nonesuch {
2297 nonesuch() = delete;
2298 ~nonesuch() = delete;
2299 nonesuch(nonesuch const&) = delete;
2300 nonesuch(nonesuch const&&) = delete;
2301 void operator=(nonesuch const&) = delete;
2302 void operator=(nonesuch&&) = delete;
2303 };
2304
2305 // https://en.cppreference.com/w/cpp/experimental/is_detected
2306 template<class Default, class AlwaysVoid, template<class...> class Op, class... Args>
2307 struct detector {
2308 using value = std::false_type;
2309 using type = Default;
2310 };
2311
2312 template<class Default, template<class...> class Op, class... Args>
2313 struct detector<Default, void_t<Op<Args...>>, Op, Args...> {
2314 using value = std::true_type;
2315 using type = Op<Args...>;
2316 };
2317
2318 template<template<class...> class Op, class... Args>
2319 using is_detected = typename detector<nonesuch, void, Op, Args...>::value;
2320#endif
2321
2322 template<typename T, typename Signature>
2323 using is_signature = typename std::is_same<T, Signature>;
2324
2325 template<typename traits_type, template<typename...> class Op, typename Signature>
2326 struct is_function_signature_detected {
2327 using type = Op<traits_type>;
2328 static constexpr auto value = is_detected<Op, traits_type>::value && std::is_function<type>::value &&
2329 is_signature<type, Signature>::value;
2330 };
2331
2332 template<typename traits_type, typename value_type>
2333 struct supports_get_type {
2334 template<typename T>
2335 using get_type_t = decltype(T::get_type);
2336
2337 static constexpr auto value =
2338 is_function_signature_detected<traits_type, get_type_t, json::type(const value_type&)>::value;
2339
2340 // Internal assertions for better feedback
2341 static_assert(value, "traits implementation must provide `jwt::json::type get_type(const value_type&)`");
2342 };
2343
2344#define JWT_CPP_JSON_TYPE_TYPE(TYPE) json_##TYPE_type
2345#define JWT_CPP_AS_TYPE_T(TYPE) as_##TYPE_t
2346#define JWT_CPP_SUPPORTS_AS(TYPE) \
2347 template<typename traits_type, typename value_type, typename JWT_CPP_JSON_TYPE_TYPE(TYPE)> \
2348 struct supports_as_##TYPE { \
2349 template<typename T> \
2350 using JWT_CPP_AS_TYPE_T(TYPE) = decltype(T::as_##TYPE); \
2351 \
2352 static constexpr auto value = \
2353 is_function_signature_detected<traits_type, JWT_CPP_AS_TYPE_T(TYPE), \
2354 JWT_CPP_JSON_TYPE_TYPE(TYPE)(const value_type&)>::value; \
2355 \
2356 static_assert(value, "traits implementation must provide `" #TYPE "_type as_" #TYPE "(const value_type&)`"); \
2357 }
2358
2359 JWT_CPP_SUPPORTS_AS(object);
2360 JWT_CPP_SUPPORTS_AS(array);
2361 JWT_CPP_SUPPORTS_AS(string);
2362 JWT_CPP_SUPPORTS_AS(number);
2363 JWT_CPP_SUPPORTS_AS(integer);
2364 JWT_CPP_SUPPORTS_AS(boolean);
2365
2366#undef JWT_CPP_JSON_TYPE_TYPE
2367#undef JWT_CPP_AS_TYPE_T
2368#undef JWT_CPP_SUPPORTS_AS
2369
2370 template<typename traits>
2371 struct is_valid_traits {
2372 static constexpr auto value =
2373 supports_get_type<traits, typename traits::value_type>::value &&
2374 supports_as_object<traits, typename traits::value_type, typename traits::object_type>::value &&
2375 supports_as_array<traits, typename traits::value_type, typename traits::array_type>::value &&
2376 supports_as_string<traits, typename traits::value_type, typename traits::string_type>::value &&
2377 supports_as_number<traits, typename traits::value_type, typename traits::number_type>::value &&
2378 supports_as_integer<traits, typename traits::value_type, typename traits::integer_type>::value &&
2379 supports_as_boolean<traits, typename traits::value_type, typename traits::boolean_type>::value;
2380 };
2381
2382 template<typename value_type>
2383 struct is_valid_json_value {
2384 static constexpr auto value =
2385 std::is_default_constructible<value_type>::value &&
2386 std::is_constructible<value_type, const value_type&>::value && // a more generic is_copy_constructible
2387 std::is_move_constructible<value_type>::value && std::is_assignable<value_type, value_type>::value &&
2388 std::is_copy_assignable<value_type>::value && std::is_move_assignable<value_type>::value;
2389 // TODO(prince-chrismc): Stream operators
2390 };
2391
2392 // https://stackoverflow.com/a/53967057/8480874
2393 template<typename T, typename = void>
2394 struct is_iterable : std::false_type {};
2395
2396 template<typename T>
2397 struct is_iterable<T, void_t<decltype(std::begin(std::declval<T>())), decltype(std::end(std::declval<T>())),
2398#if __cplusplus > 201402L
2399 decltype(std::cbegin(std::declval<T>())), decltype(std::cend(std::declval<T>()))
2400#else
2401 decltype(std::begin(std::declval<const T>())),
2402 decltype(std::end(std::declval<const T>()))
2403#endif
2404 >> : std::true_type {
2405 };
2406
2407#if __cplusplus > 201703L
2408 template<typename T>
2409 inline constexpr bool is_iterable_v = is_iterable<T>::value;
2410#endif
2411
2412 template<typename object_type, typename string_type>
2413 using is_count_signature = typename std::is_integral<decltype(std::declval<const object_type>().count(
2414 std::declval<const string_type>()))>;
2415
2416 template<typename object_type, typename string_type, typename = void>
2417 struct is_subcription_operator_signature : std::false_type {};
2418
2419 template<typename object_type, typename string_type>
2420 struct is_subcription_operator_signature<
2421 object_type, string_type,
2422 void_t<decltype(std::declval<object_type>().operator[](std::declval<string_type>()))>> : std::true_type {
2423 // TODO(prince-chrismc): I am not convienced this is meaningful anymore
2424 static_assert(
2425 value,
2426 "object_type must implementate the subscription operator '[]' taking string_type as an argument");
2427 };
2428
2429 template<typename object_type, typename value_type, typename string_type>
2430 using is_at_const_signature =
2431 typename std::is_same<decltype(std::declval<const object_type>().at(std::declval<const string_type>())),
2432 const value_type&>;
2433
2434 template<typename value_type, typename string_type, typename object_type>
2435 struct is_valid_json_object {
2436 template<typename T>
2437 using mapped_type_t = typename T::mapped_type;
2438 template<typename T>
2439 using key_type_t = typename T::key_type;
2440 template<typename T>
2441 using iterator_t = typename T::iterator;
2442 template<typename T>
2443 using const_iterator_t = typename T::const_iterator;
2444
2445 static constexpr auto value =
2446 std::is_constructible<value_type, object_type>::value &&
2447 is_detected<mapped_type_t, object_type>::value &&
2448 std::is_same<typename object_type::mapped_type, value_type>::value &&
2449 is_detected<key_type_t, object_type>::value &&
2450 (std::is_same<typename object_type::key_type, string_type>::value ||
2451 std::is_constructible<typename object_type::key_type, string_type>::value) &&
2452 is_detected<iterator_t, object_type>::value && is_detected<const_iterator_t, object_type>::value &&
2453 is_iterable<object_type>::value && is_count_signature<object_type, string_type>::value &&
2454 is_subcription_operator_signature<object_type, string_type>::value &&
2455 is_at_const_signature<object_type, value_type, string_type>::value;
2456 };
2457
2458 template<typename value_type, typename array_type>
2459 struct is_valid_json_array {
2460 template<typename T>
2461 using value_type_t = typename T::value_type;
2462
2463 static constexpr auto value = std::is_constructible<value_type, array_type>::value &&
2464 is_iterable<array_type>::value &&
2465 is_detected<value_type_t, array_type>::value &&
2466 std::is_same<typename array_type::value_type, value_type>::value;
2467 };
2468
2469 template<typename string_type, typename integer_type>
2470 using is_substr_start_end_index_signature =
2471 typename std::is_same<decltype(std::declval<string_type>().substr(std::declval<integer_type>(),
2472 std::declval<integer_type>())),
2473 string_type>;
2474
2475 template<typename string_type, typename integer_type>
2476 using is_substr_start_index_signature =
2477 typename std::is_same<decltype(std::declval<string_type>().substr(std::declval<integer_type>())),
2478 string_type>;
2479
2480 template<typename string_type>
2481 using is_std_operate_plus_signature =
2482 typename std::is_same<decltype(std::operator+(std::declval<string_type>(), std::declval<string_type>())),
2483 string_type>;
2484
2485 template<typename value_type, typename string_type, typename integer_type>
2486 struct is_valid_json_string {
2487 static constexpr auto substr = is_substr_start_end_index_signature<string_type, integer_type>::value &&
2488 is_substr_start_index_signature<string_type, integer_type>::value;
2489 static_assert(substr, "string_type must have a substr method taking only a start index and an overload "
2490 "taking a start and end index, both must return a string_type");
2491
2492 static constexpr auto operator_plus = is_std_operate_plus_signature<string_type>::value;
2493 static_assert(operator_plus,
2494 "string_type must have a '+' operator implemented which returns the concatenated string");
2495
2496 static constexpr auto value =
2497 std::is_constructible<value_type, string_type>::value && substr && operator_plus;
2498 };
2499
2500 template<typename value_type, typename number_type>
2501 struct is_valid_json_number {
2502 static constexpr auto value =
2503 std::is_floating_point<number_type>::value && std::is_constructible<value_type, number_type>::value;
2504 };
2505
2506 template<typename value_type, typename integer_type>
2507 struct is_valid_json_integer {
2508 static constexpr auto value = std::is_signed<integer_type>::value &&
2509 !std::is_floating_point<integer_type>::value &&
2510 std::is_constructible<value_type, integer_type>::value;
2511 };
2512 template<typename value_type, typename boolean_type>
2513 struct is_valid_json_boolean {
2514 static constexpr auto value = std::is_convertible<boolean_type, bool>::value &&
2515 std::is_constructible<value_type, boolean_type>::value;
2516 };
2517
2518 template<typename value_type, typename object_type, typename array_type, typename string_type,
2519 typename number_type, typename integer_type, typename boolean_type>
2520 struct is_valid_json_types {
2521 // Internal assertions for better feedback
2522 static_assert(is_valid_json_value<value_type>::value,
2523 "value_type must meet basic requirements, default constructor, copyable, moveable");
2524 static_assert(is_valid_json_object<value_type, string_type, object_type>::value,
2525 "object_type must be a string_type to value_type container");
2526 static_assert(is_valid_json_array<value_type, array_type>::value,
2527 "array_type must be a container of value_type");
2528
2529 static constexpr auto value = is_valid_json_value<value_type>::value &&
2530 is_valid_json_object<value_type, string_type, object_type>::value &&
2531 is_valid_json_array<value_type, array_type>::value &&
2532 is_valid_json_string<value_type, string_type, integer_type>::value &&
2533 is_valid_json_number<value_type, number_type>::value &&
2534 is_valid_json_integer<value_type, integer_type>::value &&
2535 is_valid_json_boolean<value_type, boolean_type>::value;
2536 };
2537 } // namespace details
2538
2546 template<typename json_traits>
2554 static_assert(std::is_same<typename json_traits::string_type, std::string>::value ||
2555 std::is_convertible<typename json_traits::string_type, std::string>::value ||
2556 std::is_constructible<typename json_traits::string_type, std::string>::value,
2557 "string_type must be a std::string, convertible to a std::string, or construct a std::string.");
2558
2559 static_assert(
2560 details::is_valid_json_types<typename json_traits::value_type, typename json_traits::object_type,
2561 typename json_traits::array_type, typename json_traits::string_type,
2562 typename json_traits::number_type, typename json_traits::integer_type,
2563 typename json_traits::boolean_type>::value,
2564 "must satisfy json container requirements");
2565 static_assert(details::is_valid_traits<json_traits>::value, "traits must satisfy requirements");
2566
2567 typename json_traits::value_type val;
2568
2569 public:
2573 using set_t = std::set<typename json_traits::string_type>;
2574
2575 basic_claim() = default;
2576 basic_claim(const basic_claim&) = default;
2577 basic_claim(basic_claim&&) = default;
2578 basic_claim& operator=(const basic_claim&) = default;
2579 basic_claim& operator=(basic_claim&&) = default;
2580 ~basic_claim() = default;
2581
2582 JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::string_type s) : val(std::move(s)) {}
2583 JWT_CLAIM_EXPLICIT basic_claim(const date& d)
2584 : val(typename json_traits::integer_type(std::chrono::system_clock::to_time_t(d))) {}
2585 JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::array_type a) : val(std::move(a)) {}
2586 JWT_CLAIM_EXPLICIT basic_claim(typename json_traits::value_type v) : val(std::move(v)) {}
2587 JWT_CLAIM_EXPLICIT basic_claim(const set_t& s) : val(typename json_traits::array_type(s.begin(), s.end())) {}
2588 template<typename Iterator>
2589 basic_claim(Iterator begin, Iterator end) : val(typename json_traits::array_type(begin, end)) {}
2590
2595 typename json_traits::value_type to_json() const { return val; }
2596
2601 std::istream& operator>>(std::istream& is) { return is >> val; }
2602
2607 std::ostream& operator<<(std::ostream& os) { return os << val; }
2608
2614 json::type get_type() const { return json_traits::get_type(val); }
2615
2621 typename json_traits::string_type as_string() const { return json_traits::as_string(val); }
2622
2631 date as_date() const {
2632 using std::chrono::system_clock;
2633 if (get_type() == json::type::number) return system_clock::from_time_t(std::round(as_number()));
2634 return system_clock::from_time_t(as_integer());
2635 }
2636
2642 typename json_traits::array_type as_array() const { return json_traits::as_array(val); }
2643
2649 set_t as_set() const {
2650 set_t res;
2651 for (const auto& e : json_traits::as_array(val)) {
2652 res.insert(json_traits::as_string(e));
2653 }
2654 return res;
2655 }
2656
2662 typename json_traits::integer_type as_integer() const { return json_traits::as_integer(val); }
2663
2669 typename json_traits::boolean_type as_boolean() const { return json_traits::as_boolean(val); }
2670
2676 typename json_traits::number_type as_number() const { return json_traits::as_number(val); }
2677 };
2678
2679 namespace error {
2683 struct invalid_json_exception : public std::runtime_error {
2684 invalid_json_exception() : runtime_error("invalid json") {}
2685 };
2689 struct claim_not_present_exception : public std::out_of_range {
2690 claim_not_present_exception() : out_of_range("claim not found") {}
2691 };
2692 } // namespace error
2693
2694 namespace details {
2695 template<typename json_traits>
2696 struct map_of_claims {
2697 typename json_traits::object_type claims;
2698 using basic_claim_t = basic_claim<json_traits>;
2699 using iterator = typename json_traits::object_type::iterator;
2700 using const_iterator = typename json_traits::object_type::const_iterator;
2701
2702 map_of_claims() = default;
2703 map_of_claims(const map_of_claims&) = default;
2704 map_of_claims(map_of_claims&&) = default;
2705 map_of_claims& operator=(const map_of_claims&) = default;
2706 map_of_claims& operator=(map_of_claims&&) = default;
2707
2708 map_of_claims(typename json_traits::object_type json) : claims(std::move(json)) {}
2709
2710 iterator begin() { return claims.begin(); }
2711 iterator end() { return claims.end(); }
2712 const_iterator cbegin() const { return claims.begin(); }
2713 const_iterator cend() const { return claims.end(); }
2714 const_iterator begin() const { return claims.begin(); }
2715 const_iterator end() const { return claims.end(); }
2716
2725 static typename json_traits::object_type parse_claims(const typename json_traits::string_type& str) {
2726 typename json_traits::value_type val;
2727 if (!json_traits::parse(val, str)) throw error::invalid_json_exception();
2728
2729 return json_traits::as_object(val);
2730 };
2731
2736 bool has_claim(const typename json_traits::string_type& name) const noexcept {
2737 return claims.count(name) != 0;
2738 }
2739
2747 basic_claim_t get_claim(const typename json_traits::string_type& name) const {
2748 if (!has_claim(name)) throw error::claim_not_present_exception();
2749 return basic_claim_t{claims.at(name)};
2750 }
2751 };
2752 } // namespace details
2753
2758 template<typename json_traits>
2759 class payload {
2760 protected:
2761 details::map_of_claims<json_traits> payload_claims;
2762
2763 public:
2765
2770 bool has_issuer() const noexcept { return has_payload_claim("iss"); }
2775 bool has_subject() const noexcept { return has_payload_claim("sub"); }
2780 bool has_audience() const noexcept { return has_payload_claim("aud"); }
2785 bool has_expires_at() const noexcept { return has_payload_claim("exp"); }
2790 bool has_not_before() const noexcept { return has_payload_claim("nbf"); }
2795 bool has_issued_at() const noexcept { return has_payload_claim("iat"); }
2800 bool has_id() const noexcept { return has_payload_claim("jti"); }
2807 typename json_traits::string_type get_issuer() const { return get_payload_claim("iss").as_string(); }
2814 typename json_traits::string_type get_subject() const { return get_payload_claim("sub").as_string(); }
2822 auto aud = get_payload_claim("aud");
2823 if (aud.get_type() == json::type::string) return {aud.as_string()};
2824
2825 return aud.as_set();
2826 }
2833 date get_expires_at() const { return get_payload_claim("exp").as_date(); }
2840 date get_not_before() const { return get_payload_claim("nbf").as_date(); }
2847 date get_issued_at() const { return get_payload_claim("iat").as_date(); }
2854 typename json_traits::string_type get_id() const { return get_payload_claim("jti").as_string(); }
2859 bool has_payload_claim(const typename json_traits::string_type& name) const noexcept {
2860 return payload_claims.has_claim(name);
2861 }
2867 basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
2868 return payload_claims.get_claim(name);
2869 }
2870 };
2871
2876 template<typename json_traits>
2877 class header {
2878 protected:
2879 details::map_of_claims<json_traits> header_claims;
2880
2881 public:
2887 bool has_algorithm() const noexcept { return has_header_claim("alg"); }
2892 bool has_type() const noexcept { return has_header_claim("typ"); }
2897 bool has_content_type() const noexcept { return has_header_claim("cty"); }
2902 bool has_key_id() const noexcept { return has_header_claim("kid"); }
2909 typename json_traits::string_type get_algorithm() const { return get_header_claim("alg").as_string(); }
2916 typename json_traits::string_type get_type() const { return get_header_claim("typ").as_string(); }
2923 typename json_traits::string_type get_content_type() const { return get_header_claim("cty").as_string(); }
2930 typename json_traits::string_type get_key_id() const { return get_header_claim("kid").as_string(); }
2935 bool has_header_claim(const typename json_traits::string_type& name) const noexcept {
2936 return header_claims.has_claim(name);
2937 }
2943 basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
2944 return header_claims.get_claim(name);
2945 }
2946 };
2947
2951 template<typename json_traits>
2952 class decoded_jwt : public header<json_traits>, public payload<json_traits> {
2953 protected:
2955 typename json_traits::string_type token;
2957 typename json_traits::string_type header;
2959 typename json_traits::string_type header_base64;
2961 typename json_traits::string_type payload;
2963 typename json_traits::string_type payload_base64;
2965 typename json_traits::string_type signature;
2967 typename json_traits::string_type signature_base64;
2968
2969 public:
2971#ifndef JWT_DISABLE_BASE64
2981 JWT_CLAIM_EXPLICIT decoded_jwt(const typename json_traits::string_type& token)
2982 : decoded_jwt(token, [](const typename json_traits::string_type& str) {
2983 return base::decode<alphabet::base64url>(base::pad<alphabet::base64url>(str));
2984 }) {}
2985#endif
2997 template<typename Decode>
2998 decoded_jwt(const typename json_traits::string_type& token, Decode decode) : token(token) {
2999 auto hdr_end = token.find('.');
3000 if (hdr_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
3001 auto payload_end = token.find('.', hdr_end + 1);
3002 if (payload_end == json_traits::string_type::npos) throw std::invalid_argument("invalid token supplied");
3003 header_base64 = token.substr(0, hdr_end);
3004 payload_base64 = token.substr(hdr_end + 1, payload_end - hdr_end - 1);
3005 signature_base64 = token.substr(payload_end + 1);
3006
3010
3011 this->header_claims = details::map_of_claims<json_traits>::parse_claims(header);
3012 this->payload_claims = details::map_of_claims<json_traits>::parse_claims(payload);
3013 }
3014
3019 const typename json_traits::string_type& get_token() const noexcept { return token; }
3024 const typename json_traits::string_type& get_header() const noexcept { return header; }
3029 const typename json_traits::string_type& get_payload() const noexcept { return payload; }
3034 const typename json_traits::string_type& get_signature() const noexcept { return signature; }
3039 const typename json_traits::string_type& get_header_base64() const noexcept { return header_base64; }
3044 const typename json_traits::string_type& get_payload_base64() const noexcept { return payload_base64; }
3049 const typename json_traits::string_type& get_signature_base64() const noexcept { return signature_base64; }
3054 typename json_traits::object_type get_payload_json() const { return this->payload_claims.claims; }
3059 typename json_traits::object_type get_header_json() const { return this->header_claims.claims; }
3067 basic_claim_t get_payload_claim(const typename json_traits::string_type& name) const {
3068 return this->payload_claims.get_claim(name);
3069 }
3077 basic_claim_t get_header_claim(const typename json_traits::string_type& name) const {
3078 return this->header_claims.get_claim(name);
3079 }
3080 };
3081
3086 template<typename Clock, typename json_traits>
3087 class builder {
3088 typename json_traits::object_type header_claims;
3089 typename json_traits::object_type payload_claims;
3090
3092 Clock clock;
3093
3094 public:
3099 JWT_CLAIM_EXPLICIT builder(Clock c) : clock(c) {}
3106 builder& set_header_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
3107 header_claims[id] = std::move(c);
3108 return *this;
3109 }
3110
3117 builder& set_header_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
3118 header_claims[id] = c.to_json();
3119 return *this;
3120 }
3127 builder& set_payload_claim(const typename json_traits::string_type& id, typename json_traits::value_type c) {
3128 payload_claims[id] = std::move(c);
3129 return *this;
3130 }
3137 builder& set_payload_claim(const typename json_traits::string_type& id, basic_claim<json_traits> c) {
3138 payload_claims[id] = c.to_json();
3139 return *this;
3140 }
3148 builder& set_algorithm(typename json_traits::string_type str) {
3149 return set_header_claim("alg", typename json_traits::value_type(str));
3150 }
3156 builder& set_type(typename json_traits::string_type str) {
3157 return set_header_claim("typ", typename json_traits::value_type(str));
3158 }
3164 builder& set_content_type(typename json_traits::string_type str) {
3165 return set_header_claim("cty", typename json_traits::value_type(str));
3166 }
3173 builder& set_key_id(typename json_traits::string_type str) {
3174 return set_header_claim("kid", typename json_traits::value_type(str));
3175 }
3181 builder& set_issuer(typename json_traits::string_type str) {
3182 return set_payload_claim("iss", typename json_traits::value_type(str));
3183 }
3189 builder& set_subject(typename json_traits::string_type str) {
3190 return set_payload_claim("sub", typename json_traits::value_type(str));
3191 }
3197 builder& set_audience(typename json_traits::array_type a) {
3198 return set_payload_claim("aud", typename json_traits::value_type(a));
3199 }
3205 builder& set_audience(typename json_traits::string_type aud) {
3206 return set_payload_claim("aud", typename json_traits::value_type(aud));
3207 }
3219 template<class Rep>
3220 builder& set_expires_in(const std::chrono::duration<Rep>& d) {
3221 return set_payload_claim("exp", basic_claim<json_traits>(clock.now() + d));
3222 }
3239 builder& set_issued_now() { return set_issued_at(clock.now()); }
3245 builder& set_id(const typename json_traits::string_type& str) {
3246 return set_payload_claim("jti", typename json_traits::value_type(str));
3247 }
3248
3260 template<typename Algo, typename Encode>
3261 typename json_traits::string_type sign(const Algo& algo, Encode encode) const {
3262 std::error_code ec;
3263 auto res = sign(algo, encode, ec);
3265 return res;
3266 }
3267#ifndef JWT_DISABLE_BASE64
3276 template<typename Algo>
3277 typename json_traits::string_type sign(const Algo& algo) const {
3278 std::error_code ec;
3279 auto res = sign(algo, ec);
3281 return res;
3282 }
3283#endif
3284
3297 template<typename Algo, typename Encode>
3298 typename json_traits::string_type sign(const Algo& algo, Encode encode, std::error_code& ec) const {
3299 // make a copy such that a builder can be re-used
3300 typename json_traits::object_type obj_header = header_claims;
3301 if (header_claims.count("alg") == 0) obj_header["alg"] = typename json_traits::value_type(algo.name());
3302
3303 const auto header = encode(json_traits::serialize(typename json_traits::value_type(obj_header)));
3304 const auto payload = encode(json_traits::serialize(typename json_traits::value_type(payload_claims)));
3305 const auto token = header + "." + payload;
3306
3307 auto signature = algo.sign(token, ec);
3308 if (ec) return {};
3309
3310 return token + "." + encode(signature);
3311 }
3312#ifndef JWT_DISABLE_BASE64
3322 template<typename Algo>
3323 typename json_traits::string_type sign(const Algo& algo, std::error_code& ec) const {
3324 return sign(
3325 algo,
3326 [](const typename json_traits::string_type& data) {
3327 return base::trim<alphabet::base64url>(base::encode<alphabet::base64url>(data));
3328 },
3329 ec);
3330 }
3331#endif
3332 };
3333
3334 namespace verify_ops {
3338 template<typename json_traits>
3340 verify_context(date ctime, const decoded_jwt<json_traits>& j, size_t l)
3341 : current_time(ctime), jwt(j), default_leeway(l) {}
3348
3350 typename json_traits::string_type claim_key{};
3351
3358 basic_claim<json_traits> get_claim(bool in_header, std::error_code& ec) const {
3359 if (in_header) {
3360 if (!jwt.has_header_claim(claim_key)) {
3361 ec = error::token_verification_error::missing_claim;
3362 return {};
3363 }
3364 return jwt.get_header_claim(claim_key);
3365 } else {
3366 if (!jwt.has_payload_claim(claim_key)) {
3367 ec = error::token_verification_error::missing_claim;
3368 return {};
3369 }
3370 return jwt.get_payload_claim(claim_key);
3371 }
3372 }
3380 basic_claim<json_traits> get_claim(bool in_header, json::type t, std::error_code& ec) const {
3381 auto c = get_claim(in_header, ec);
3382 if (ec) return {};
3383 if (c.get_type() != t) {
3384 ec = error::token_verification_error::claim_type_missmatch;
3385 return {};
3386 }
3387 return c;
3388 }
3394 basic_claim<json_traits> get_claim(std::error_code& ec) const { return get_claim(false, ec); }
3401 basic_claim<json_traits> get_claim(json::type t, std::error_code& ec) const {
3402 return get_claim(false, t, ec);
3403 }
3404 };
3405
3409 template<typename json_traits, bool in_header = false>
3411 const basic_claim<json_traits> expected;
3412 void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3413 auto jc = ctx.get_claim(in_header, expected.get_type(), ec);
3414 if (ec) return;
3415 const bool matches = [&]() {
3416 switch (expected.get_type()) {
3417 case json::type::boolean: return expected.as_boolean() == jc.as_boolean();
3418 case json::type::integer: return expected.as_integer() == jc.as_integer();
3419 case json::type::number: return expected.as_number() == jc.as_number();
3420 case json::type::string: return expected.as_string() == jc.as_string();
3421 case json::type::array:
3422 case json::type::object:
3423 return json_traits::serialize(expected.to_json()) == json_traits::serialize(jc.to_json());
3424 default: throw std::logic_error("internal error, should be unreachable");
3425 }
3426 }();
3427 if (!matches) {
3428 ec = error::token_verification_error::claim_value_missmatch;
3429 return;
3430 }
3431 }
3432 };
3433
3438 template<typename json_traits, bool in_header = false>
3440 const size_t leeway;
3441 void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3442 auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3443 if (ec) return;
3444 auto c = jc.as_date();
3445 if (ctx.current_time > c + std::chrono::seconds(leeway)) {
3446 ec = error::token_verification_error::token_expired;
3447 }
3448 }
3449 };
3450
3455 template<typename json_traits, bool in_header = false>
3457 const size_t leeway;
3458 void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3459 auto jc = ctx.get_claim(in_header, json::type::integer, ec);
3460 if (ec) return;
3461 auto c = jc.as_date();
3462 if (ctx.current_time < c - std::chrono::seconds(leeway)) {
3463 ec = error::token_verification_error::token_expired;
3464 }
3465 }
3466 };
3467
3473 template<typename json_traits, bool in_header = false>
3475 const typename basic_claim<json_traits>::set_t expected;
3476 void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3477 auto c = ctx.get_claim(in_header, ec);
3478 if (ec) return;
3479 if (c.get_type() == json::type::string) {
3480 if (expected.size() != 1 || *expected.begin() != c.as_string()) {
3481 ec = error::token_verification_error::audience_missmatch;
3482 return;
3483 }
3484 } else if (c.get_type() == json::type::array) {
3485 auto jc = c.as_set();
3486 for (auto& e : expected) {
3487 if (jc.find(e) == jc.end()) {
3488 ec = error::token_verification_error::audience_missmatch;
3489 return;
3490 }
3491 }
3492 } else {
3493 ec = error::token_verification_error::claim_type_missmatch;
3494 return;
3495 }
3496 }
3497 };
3498
3502 template<typename json_traits, bool in_header = false>
3504 const typename json_traits::string_type expected;
3505 std::locale locale;
3506 insensitive_string_claim(const typename json_traits::string_type& e, std::locale loc)
3507 : expected(to_lower_unicode(e, loc)), locale(loc) {}
3508
3509 void operator()(const verify_context<json_traits>& ctx, std::error_code& ec) const {
3510 const auto c = ctx.get_claim(in_header, json::type::string, ec);
3511 if (ec) return;
3512 if (to_lower_unicode(c.as_string(), locale) != expected) {
3513 ec = error::token_verification_error::claim_value_missmatch;
3514 }
3515 }
3516
3517 static std::string to_lower_unicode(const std::string& str, const std::locale& loc) {
3518 std::mbstate_t state = std::mbstate_t();
3519 const char* in_next = str.data();
3520 const char* in_end = str.data() + str.size();
3521 std::wstring wide;
3522 wide.reserve(str.size());
3523
3524 while (in_next != in_end) {
3525 wchar_t wc;
3526 std::size_t result = std::mbrtowc(&wc, in_next, in_end - in_next, &state);
3527 if (result == static_cast<std::size_t>(-1)) {
3528 throw std::runtime_error("encoding error: " + std::string(std::strerror(errno)));
3529 } else if (result == static_cast<std::size_t>(-2)) {
3530 throw std::runtime_error("conversion error: next bytes constitute an incomplete, but so far "
3531 "valid, multibyte character.");
3532 }
3533 in_next += result;
3534 wide.push_back(wc);
3535 }
3536
3537 auto& f = std::use_facet<std::ctype<wchar_t>>(loc);
3538 f.tolower(&wide[0], &wide[0] + wide.size());
3539
3540 std::string out;
3541 out.reserve(wide.size());
3542 for (wchar_t wc : wide) {
3543 char mb[MB_LEN_MAX];
3544 std::size_t n = std::wcrtomb(mb, wc, &state);
3545 if (n != static_cast<std::size_t>(-1)) out.append(mb, n);
3546 }
3547
3548 return out;
3549 }
3550 };
3551 } // namespace verify_ops
3552
3557 template<typename Clock, typename json_traits>
3558 class verifier {
3559 public:
3571 std::function<void(const verify_ops::verify_context<json_traits>&, std::error_code& ec)>;
3572
3573 private:
3574 struct algo_base {
3575 virtual ~algo_base() = default;
3576 virtual void verify(const std::string& data, const std::string& sig, std::error_code& ec) = 0;
3577 };
3578 template<typename T>
3579 struct algo : public algo_base {
3580 T alg;
3581 explicit algo(T a) : alg(a) {}
3582 void verify(const std::string& data, const std::string& sig, std::error_code& ec) override {
3583 alg.verify(data, sig, ec);
3584 }
3585 };
3587 std::unordered_map<typename json_traits::string_type, verify_check_fn_t> claims;
3589 size_t default_leeway = 0;
3591 Clock clock;
3593 std::unordered_map<std::string, std::shared_ptr<algo_base>> algs;
3594
3595 public:
3600 explicit verifier(Clock c) : clock(c) {
3601 claims["exp"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
3602 if (!ctx.jwt.has_expires_at()) return;
3603 auto exp = ctx.jwt.get_expires_at();
3604 if (ctx.current_time > exp + std::chrono::seconds(ctx.default_leeway)) {
3605 ec = error::token_verification_error::token_expired;
3606 }
3607 };
3608 claims["iat"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
3609 if (!ctx.jwt.has_issued_at()) return;
3610 auto iat = ctx.jwt.get_issued_at();
3611 if (ctx.current_time < iat - std::chrono::seconds(ctx.default_leeway)) {
3612 ec = error::token_verification_error::token_expired;
3613 }
3614 };
3615 claims["nbf"] = [](const verify_ops::verify_context<json_traits>& ctx, std::error_code& ec) {
3616 if (!ctx.jwt.has_not_before()) return;
3617 auto nbf = ctx.jwt.get_not_before();
3618 if (ctx.current_time < nbf - std::chrono::seconds(ctx.default_leeway)) {
3619 ec = error::token_verification_error::token_expired;
3620 }
3621 };
3622 }
3623
3630 default_leeway = leeway;
3631 return *this;
3632 }
3641 return *this;
3642 }
3651 return *this;
3652 }
3661 return *this;
3662 }
3663
3675 verifier& with_type(const typename json_traits::string_type& type, std::locale locale = std::locale{}) {
3676 return with_claim("typ", verify_ops::insensitive_string_claim<json_traits, true>{type, std::move(locale)});
3677 }
3678
3685 verifier& with_issuer(const typename json_traits::string_type& iss) {
3686 return with_claim("iss", basic_claim_t(iss));
3687 }
3688
3695 verifier& with_subject(const typename json_traits::string_type& sub) {
3696 return with_claim("sub", basic_claim_t(sub));
3697 }
3705 claims["aud"] = verify_ops::is_subset_claim<json_traits>{aud};
3706 return *this;
3707 }
3714 verifier& with_audience(const typename json_traits::string_type& aud) {
3715 typename basic_claim_t::set_t s;
3716 s.insert(aud);
3717 return with_audience(s);
3718 }
3725 verifier& with_id(const typename json_traits::string_type& id) { return with_claim("jti", basic_claim_t(id)); }
3726
3738 verifier& with_claim(const typename json_traits::string_type& name, verify_check_fn_t fn) {
3739 claims[name] = fn;
3740 return *this;
3741 }
3742
3753 verifier& with_claim(const typename json_traits::string_type& name, basic_claim_t c) {
3755 }
3756
3770 template<typename Algorithm>
3771 verifier& allow_algorithm(Algorithm alg) {
3772 algs[alg.name()] = std::make_shared<algo<Algorithm>>(alg);
3773 return *this;
3774 }
3775
3782 std::error_code ec;
3783 verify(jwt, ec);
3785 }
3791 void verify(const decoded_jwt<json_traits>& jwt, std::error_code& ec) const {
3792 ec.clear();
3793 const typename json_traits::string_type data = jwt.get_header_base64() + "." + jwt.get_payload_base64();
3794 const typename json_traits::string_type sig = jwt.get_signature();
3795 const std::string algo = jwt.get_algorithm();
3796 if (algs.count(algo) == 0) {
3797 ec = error::token_verification_error::wrong_algorithm;
3798 return;
3799 }
3800 algs.at(algo)->verify(data, sig, ec);
3801 if (ec) return;
3802
3803 verify_ops::verify_context<json_traits> ctx{clock.now(), jwt, default_leeway};
3804 for (auto& c : claims) {
3805 ctx.claim_key = c.first;
3806 c.second(ctx, ec);
3807 if (ec) return;
3808 }
3809 }
3810 };
3811
3820 template<typename json_traits>
3821 class jwk {
3823 const details::map_of_claims<json_traits> jwk_claims;
3824
3825 public:
3826 JWT_CLAIM_EXPLICIT jwk(const typename json_traits::string_type& str)
3827 : jwk_claims(details::map_of_claims<json_traits>::parse_claims(str)) {}
3828
3829 JWT_CLAIM_EXPLICIT jwk(const typename json_traits::value_type& json)
3830 : jwk_claims(json_traits::as_object(json)) {}
3831
3840 typename json_traits::string_type get_key_type() const { return get_jwk_claim("kty").as_string(); }
3841
3848 typename json_traits::string_type get_use() const { return get_jwk_claim("use").as_string(); }
3849
3856 typename basic_claim_t::set_t get_key_operations() const { return get_jwk_claim("key_ops").as_set(); }
3857
3864 typename json_traits::string_type get_algorithm() const { return get_jwk_claim("alg").as_string(); }
3865
3872 typename json_traits::string_type get_key_id() const { return get_jwk_claim("kid").as_string(); }
3873
3884 typename json_traits::string_type get_curve() const { return get_jwk_claim("crv").as_string(); }
3885
3892 typename json_traits::array_type get_x5c() const { return get_jwk_claim("x5c").as_array(); };
3893
3900 typename json_traits::string_type get_x5u() const { return get_jwk_claim("x5u").as_string(); };
3901
3908 typename json_traits::string_type get_x5t() const { return get_jwk_claim("x5t").as_string(); };
3909
3916 typename json_traits::string_type get_x5t_sha256() const { return get_jwk_claim("x5t#S256").as_string(); };
3917
3924 typename json_traits::string_type get_x5c_key_value() const {
3925 auto x5c_array = get_jwk_claim("x5c").as_array();
3926 if (x5c_array.size() == 0) throw error::claim_not_present_exception();
3927
3928 return json_traits::as_string(x5c_array.front());
3929 };
3930
3935 bool has_key_type() const noexcept { return has_jwk_claim("kty"); }
3936
3941 bool has_use() const noexcept { return has_jwk_claim("use"); }
3942
3947 bool has_key_operations() const noexcept { return has_jwk_claim("key_ops"); }
3948
3953 bool has_algorithm() const noexcept { return has_jwk_claim("alg"); }
3954
3959 bool has_curve() const noexcept { return has_jwk_claim("crv"); }
3960
3965 bool has_key_id() const noexcept { return has_jwk_claim("kid"); }
3966
3971 bool has_x5u() const noexcept { return has_jwk_claim("x5u"); }
3972
3977 bool has_x5c() const noexcept { return has_jwk_claim("x5c"); }
3978
3983 bool has_x5t() const noexcept { return has_jwk_claim("x5t"); }
3984
3989 bool has_x5t_sha256() const noexcept { return has_jwk_claim("x5t#S256"); }
3990
3995 bool has_jwk_claim(const typename json_traits::string_type& name) const noexcept {
3996 return jwk_claims.has_claim(name);
3997 }
3998
4004 basic_claim_t get_jwk_claim(const typename json_traits::string_type& name) const {
4005 return jwk_claims.get_claim(name);
4006 }
4007
4012 bool empty() const noexcept { return jwk_claims.empty(); }
4013
4018 typename json_traits::object_type get_claims() const { return this->jwk_claims.claims; }
4019 };
4020
4031 template<typename json_traits>
4032 class jwks {
4033 public:
4037 using jwks_vector_t = std::vector<jwks_t>;
4038 using iterator = typename jwks_vector_t::iterator;
4039 using const_iterator = typename jwks_vector_t::const_iterator;
4040
4044 jwks() = default;
4045
4052 JWT_CLAIM_EXPLICIT jwks(const typename json_traits::string_type& str) {
4053 typename json_traits::value_type parsed_val;
4054 if (!json_traits::parse(parsed_val, str)) throw error::invalid_json_exception();
4055
4056 const details::map_of_claims<json_traits> jwks_json = json_traits::as_object(parsed_val);
4057 if (!jwks_json.has_claim("keys")) throw error::invalid_json_exception();
4058
4059 auto jwk_list = jwks_json.get_claim("keys").as_array();
4060 std::transform(jwk_list.begin(), jwk_list.end(), std::back_inserter(jwk_claims),
4061 [](const typename json_traits::value_type& val) { return jwks_t{val}; });
4062 }
4063
4064 iterator begin() { return jwk_claims.begin(); }
4065 iterator end() { return jwk_claims.end(); }
4066 const_iterator cbegin() const { return jwk_claims.begin(); }
4067 const_iterator cend() const { return jwk_claims.end(); }
4068 const_iterator begin() const { return jwk_claims.begin(); }
4069 const_iterator end() const { return jwk_claims.end(); }
4070
4075 bool has_jwk(const typename json_traits::string_type& key_id) const noexcept {
4076 return find_by_kid(key_id) != end();
4077 }
4078
4084 jwks_t get_jwk(const typename json_traits::string_type& key_id) const {
4085 const auto maybe = find_by_kid(key_id);
4086 if (maybe == end()) throw error::claim_not_present_exception();
4087 return *maybe;
4088 }
4089
4090 private:
4091 jwks_vector_t jwk_claims;
4092
4093 const_iterator find_by_kid(const typename json_traits::string_type& key_id) const noexcept {
4094 return std::find_if(cbegin(), cend(), [key_id](const jwks_t& jwk) {
4095 if (!jwk.has_key_id()) { return false; }
4096 return jwk.get_key_id() == key_id;
4097 });
4098 }
4099 };
4100
4106 template<typename Clock, typename json_traits>
4110
4116 template<typename Clock, typename json_traits>
4120
4129 date now() const { return date::clock::now(); }
4130 };
4131
4140 template<typename json_traits>
4142 return verifier<default_clock, json_traits>(c);
4143 }
4144
4148 template<typename json_traits>
4150 return builder<default_clock, json_traits>(c);
4151 }
4152
4167 template<typename json_traits, typename Decode>
4168 decoded_jwt<json_traits> decode(const typename json_traits::string_type& token, Decode decode) {
4169 return decoded_jwt<json_traits>(token, decode);
4170 }
4171
4182 template<typename json_traits>
4183 decoded_jwt<json_traits> decode(const typename json_traits::string_type& token) {
4184 return decoded_jwt<json_traits>(token);
4185 }
4192 template<typename json_traits>
4193 jwk<json_traits> parse_jwk(const typename json_traits::string_type& jwk_) {
4194 return jwk<json_traits>(jwk_);
4195 }
4206 template<typename json_traits>
4207 jwks<json_traits> parse_jwks(const typename json_traits::string_type& jwks_) {
4208 return jwks<json_traits>(jwks_);
4209 }
4210} // namespace jwt
4211
4212template<typename json_traits>
4213std::istream& operator>>(std::istream& is, jwt::basic_claim<json_traits>& c) {
4214 return c.operator>>(is);
4215}
4216
4217template<typename json_traits>
4218std::ostream& operator<<(std::ostream& os, const jwt::basic_claim<json_traits>& c) {
4219 return os << c.to_json();
4220}
4221
4222#ifndef JWT_DISABLE_PICOJSON
4223#include "traits/kazuho-picojson/defaults.h"
4224#endif
4225
4226#endif
a class to store a generic JSON value as claim
Definition jwt.h:2547
json_traits::number_type as_number() const
Definition jwt.h:2676
set_t as_set() const
Definition jwt.h:2649
json::type get_type() const
Definition jwt.h:2614
std::set< typename json_traits::string_type > set_t
Definition jwt.h:2573
std::istream & operator>>(std::istream &is)
Definition jwt.h:2601
json_traits::boolean_type as_boolean() const
Definition jwt.h:2669
date as_date() const
Get the contained JSON value as a date.
Definition jwt.h:2631
std::ostream & operator<<(std::ostream &os)
Definition jwt.h:2607
json_traits::integer_type as_integer() const
Definition jwt.h:2662
json_traits::value_type to_json() const
Definition jwt.h:2595
json_traits::array_type as_array() const
Definition jwt.h:2642
json_traits::string_type as_string() const
Definition jwt.h:2621
Definition jwt.h:3087
builder & set_audience(typename json_traits::string_type aud)
Definition jwt.h:3205
builder & set_payload_claim(const typename json_traits::string_type &id, basic_claim< json_traits > c)
Definition jwt.h:3137
builder & set_expires_in(const std::chrono::duration< Rep > &d)
Definition jwt.h:3220
builder & set_algorithm(typename json_traits::string_type str)
Set algorithm claim You normally don't need to do this, as the algorithm is automatically set if you ...
Definition jwt.h:3148
builder & set_expires_at(const date &d)
Definition jwt.h:3213
builder & set_type(typename json_traits::string_type str)
Definition jwt.h:3156
JWT_CLAIM_EXPLICIT builder(Clock c)
Definition jwt.h:3099
json_traits::string_type sign(const Algo &algo, std::error_code &ec) const
Definition jwt.h:3323
builder & set_issued_at(const date &d)
Definition jwt.h:3234
json_traits::string_type sign(const Algo &algo) const
Definition jwt.h:3277
builder & set_payload_claim(const typename json_traits::string_type &id, typename json_traits::value_type c)
Definition jwt.h:3127
builder & set_id(const typename json_traits::string_type &str)
Definition jwt.h:3245
builder & set_header_claim(const typename json_traits::string_type &id, typename json_traits::value_type c)
Definition jwt.h:3106
builder & set_header_claim(const typename json_traits::string_type &id, basic_claim< json_traits > c)
Definition jwt.h:3117
json_traits::string_type sign(const Algo &algo, Encode encode) const
Definition jwt.h:3261
builder & set_audience(typename json_traits::array_type a)
Definition jwt.h:3197
json_traits::string_type sign(const Algo &algo, Encode encode, std::error_code &ec) const
Definition jwt.h:3298
builder & set_content_type(typename json_traits::string_type str)
Definition jwt.h:3164
builder & set_not_before(const date &d)
Definition jwt.h:3228
builder & set_subject(typename json_traits::string_type str)
Definition jwt.h:3189
builder & set_issued_now()
Definition jwt.h:3239
builder & set_key_id(typename json_traits::string_type str)
Set key id claim.
Definition jwt.h:3173
builder & set_issuer(typename json_traits::string_type str)
Definition jwt.h:3181
Definition jwt.h:2952
const json_traits::string_type & get_header() const noexcept
Definition jwt.h:3024
const json_traits::string_type & get_signature_base64() const noexcept
Definition jwt.h:3049
json_traits::string_type signature
Signature part decoded from base64.
Definition jwt.h:2965
json_traits::string_type header
Header part decoded from base64.
Definition jwt.h:2957
json_traits::string_type header_base64
Unmodified header part in base64.
Definition jwt.h:2959
json_traits::string_type token
Unmodified token, as passed to constructor.
Definition jwt.h:2955
basic_claim_t get_payload_claim(const typename json_traits::string_type &name) const
Definition jwt.h:3067
const json_traits::string_type & get_signature() const noexcept
Definition jwt.h:3034
JWT_CLAIM_EXPLICIT decoded_jwt(const typename json_traits::string_type &token)
Parses a given token.
Definition jwt.h:2981
basic_claim_t get_header_claim(const typename json_traits::string_type &name) const
Definition jwt.h:3077
decoded_jwt(const typename json_traits::string_type &token, Decode decode)
Parses a given token.
Definition jwt.h:2998
json_traits::object_type get_payload_json() const
Definition jwt.h:3054
json_traits::string_type signature_base64
Unmodified signature part in base64.
Definition jwt.h:2967
const json_traits::string_type & get_payload_base64() const noexcept
Definition jwt.h:3044
const json_traits::string_type & get_token() const noexcept
Definition jwt.h:3019
json_traits::object_type get_header_json() const
Definition jwt.h:3059
const json_traits::string_type & get_payload() const noexcept
Definition jwt.h:3029
const json_traits::string_type & get_header_base64() const noexcept
Definition jwt.h:3039
json_traits::string_type payload_base64
Unmodified payload part in base64.
Definition jwt.h:2963
json_traits::string_type payload
Payload part decoded from base64.
Definition jwt.h:2961
Definition jwt.h:2877
json_traits::string_type get_type() const
Definition jwt.h:2916
bool has_header_claim(const typename json_traits::string_type &name) const noexcept
Definition jwt.h:2935
bool has_algorithm() const noexcept
Definition jwt.h:2887
bool has_type() const noexcept
Definition jwt.h:2892
json_traits::string_type get_algorithm() const
Definition jwt.h:2909
bool has_content_type() const noexcept
Definition jwt.h:2897
basic_claim_t get_header_claim(const typename json_traits::string_type &name) const
Definition jwt.h:2943
json_traits::string_type get_key_id() const
Definition jwt.h:2930
json_traits::string_type get_content_type() const
Definition jwt.h:2923
bool has_key_id() const noexcept
Definition jwt.h:2902
Handle class for EVP_PKEY structures.
Definition jwt.h:425
constexpr evp_pkey_handle() noexcept=default
Creates a null key pointer.
constexpr evp_pkey_handle(EVP_PKEY *key) noexcept
Construct a new handle. The handle takes ownership of the key.
Definition jwt.h:449
JSON Web Key.
Definition jwt.h:3821
bool has_x5c() const noexcept
Definition jwt.h:3977
json_traits::string_type get_curve() const
Get curve claim.
Definition jwt.h:3884
bool has_x5t_sha256() const noexcept
Definition jwt.h:3989
json_traits::string_type get_algorithm() const
Definition jwt.h:3864
json_traits::array_type get_x5c() const
Definition jwt.h:3892
json_traits::object_type get_claims() const
Definition jwt.h:4018
json_traits::string_type get_x5t() const
Definition jwt.h:3908
json_traits::string_type get_x5c_key_value() const
Definition jwt.h:3924
json_traits::string_type get_x5t_sha256() const
Definition jwt.h:3916
json_traits::string_type get_key_id() const
Definition jwt.h:3872
bool has_algorithm() const noexcept
Definition jwt.h:3953
json_traits::string_type get_use() const
Definition jwt.h:3848
bool has_key_id() const noexcept
Definition jwt.h:3965
bool has_x5u() const noexcept
Definition jwt.h:3971
bool has_key_operations() const noexcept
Definition jwt.h:3947
bool empty() const noexcept
Definition jwt.h:4012
bool has_use() const noexcept
Definition jwt.h:3941
bool has_x5t() const noexcept
Definition jwt.h:3983
bool has_jwk_claim(const typename json_traits::string_type &name) const noexcept
Definition jwt.h:3995
basic_claim_t::set_t get_key_operations() const
Definition jwt.h:3856
bool has_curve() const noexcept
Definition jwt.h:3959
bool has_key_type() const noexcept
Definition jwt.h:3935
basic_claim_t get_jwk_claim(const typename json_traits::string_type &name) const
Definition jwt.h:4004
json_traits::string_type get_x5u() const
Definition jwt.h:3900
json_traits::string_type get_key_type() const
Definition jwt.h:3840
JWK Set.
Definition jwt.h:4032
jwks_t get_jwk(const typename json_traits::string_type &key_id) const
Definition jwt.h:4084
jwks()=default
std::vector< jwks_t > jwks_vector_t
Type specialization for the vector of JWK.
Definition jwt.h:4037
JWT_CLAIM_EXPLICIT jwks(const typename json_traits::string_type &str)
Definition jwt.h:4052
bool has_jwk(const typename json_traits::string_type &key_id) const noexcept
Definition jwt.h:4075
Definition jwt.h:2759
basic_claim_t::set_t get_audience() const
Definition jwt.h:2821
json_traits::string_type get_id() const
Definition jwt.h:2854
bool has_issued_at() const noexcept
Definition jwt.h:2795
bool has_not_before() const noexcept
Definition jwt.h:2790
bool has_payload_claim(const typename json_traits::string_type &name) const noexcept
Definition jwt.h:2859
bool has_subject() const noexcept
Definition jwt.h:2775
date get_not_before() const
Definition jwt.h:2840
bool has_issuer() const noexcept
Definition jwt.h:2770
bool has_id() const noexcept
Definition jwt.h:2800
bool has_expires_at() const noexcept
Definition jwt.h:2785
date get_issued_at() const
Definition jwt.h:2847
basic_claim_t get_payload_claim(const typename json_traits::string_type &name) const
Definition jwt.h:2867
bool has_audience() const noexcept
Definition jwt.h:2780
date get_expires_at() const
Definition jwt.h:2833
json_traits::string_type get_subject() const
Definition jwt.h:2814
json_traits::string_type get_issuer() const
Definition jwt.h:2807
Definition jwt.h:3558
verifier & expires_at_leeway(size_t leeway)
Definition jwt.h:3639
verifier & with_claim(const typename json_traits::string_type &name, verify_check_fn_t fn)
Definition jwt.h:3738
void verify(const decoded_jwt< json_traits > &jwt, std::error_code &ec) const
Definition jwt.h:3791
std::function< void(const verify_ops::verify_context< json_traits > &, std::error_code &ec)> verify_check_fn_t
Verification function data structure.
Definition jwt.h:3570
verifier & not_before_leeway(size_t leeway)
Definition jwt.h:3649
verifier & issued_at_leeway(size_t leeway)
Definition jwt.h:3659
verifier & with_subject(const typename json_traits::string_type &sub)
Definition jwt.h:3695
verifier & with_audience(const typename basic_claim_t::set_t &aud)
Definition jwt.h:3704
verifier & with_claim(const typename json_traits::string_type &name, basic_claim_t c)
Definition jwt.h:3753
verifier & with_audience(const typename json_traits::string_type &aud)
Definition jwt.h:3714
void verify(const decoded_jwt< json_traits > &jwt) const
Definition jwt.h:3781
verifier(Clock c)
Definition jwt.h:3600
verifier & leeway(size_t leeway)
Definition jwt.h:3629
verifier & with_issuer(const typename json_traits::string_type &iss)
Definition jwt.h:3685
verifier & allow_algorithm(Algorithm alg)
Add an algorithm available for checking.
Definition jwt.h:3771
verifier & with_type(const typename json_traits::string_type &type, std::locale locale=std::locale{})
Definition jwt.h:3675
verifier & with_id(const typename json_traits::string_type &id)
Definition jwt.h:3725
signature_verification_error
Errors related to verification of signatures.
Definition jwt.h:216
std::error_category & token_verification_error_category()
Error category for token verification errors.
Definition jwt.h:351
void throw_if_error(std::error_code ec)
Raises an exception if any JWT-CPP error codes are active.
Definition jwt.h:383
std::error_category & ecdsa_error_category()
Error category for ECDSA errors.
Definition jwt.h:179
std::error_category & signature_verification_error_category()
Error category for verification errors.
Definition jwt.h:230
std::error_category & rsa_error_category()
Error category for RSA errors.
Definition jwt.h:127
std::error_category & signature_generation_error_category()
Error category for signature generation errors.
Definition jwt.h:289
ecdsa_error
Errors related to processing of RSA signatures.
Definition jwt.h:159
rsa_error
Errors related to processing of RSA signatures.
Definition jwt.h:110
signature_generation_error
Errors related to signature generation errors.
Definition jwt.h:269
token_verification_error
Errors related to token verification errors.
Definition jwt.h:339
std::error_code make_error_code(rsa_error e)
Converts JWT-CPP errors into generic STL error_codes.
Definition jwt.h:155
std::string extract_pubkey_from_cert(const std::string &certstr, const std::string &pw, std::error_code &ec)
Extract the public key of a pem certificate.
Definition jwt.h:542
evp_pkey_handle load_public_ec_key_from_string(const std::string &key, const std::string &password, std::error_code &ec)
Load a public key from a string.
Definition jwt.h:818
evp_pkey_handle load_public_key_from_string(const std::string &key, const std::string &password, std::error_code &ec)
Load a public key from a string.
Definition jwt.h:714
std::string create_public_key_from_rsa_components(const std::string &modulus, const std::string &exponent, Decode decode, std::error_code &ec)
create public key from modulus and exponent. This is defined in RFC 7518 Section 6....
Definition jwt.h:917
std::unique_ptr< BIGNUM, decltype(&BN_free)> raw2bn(const std::string &raw, std::error_code &ec)
Definition jwt.h:847
evp_pkey_handle load_private_ec_key_from_string(const std::string &key, const std::string &password, std::error_code &ec)
Load a private key from a string.
Definition jwt.h:897
int curve2nid(const std::string curve, std::error_code &ec)
Convert a curve name to an ID.
Definition jwt.h:1124
std::string convert_base64_der_to_pem(const std::string &cert_base64_der_str, Decode decode, std::error_code &ec)
Convert the certificate provided as base64 DER to PEM.
Definition jwt.h:628
std::string bn2raw(const BIGNUM *bn)
Definition jwt.h:834
std::string create_public_key_from_ec_components(const std::string &curve, const std::string &x, const std::string &y, Decode decode, std::error_code &ec)
Definition jwt.h:1155
evp_pkey_handle load_private_key_from_string(const std::string &key, const std::string &password, std::error_code &ec)
Load a private key from a string.
Definition jwt.h:772
std::string convert_der_to_pem(const std::string &cert_der_str, std::error_code &ec)
Convert the certificate provided as DER to PEM.
Definition jwt.h:592
type
Categories for the various JSON types used in JWTs.
Definition jwt.h:2274
JSON Web Token.
Definition base.h:21
verifier< Clock, json_traits > verify(Clock c)
Definition jwt.h:4107
std::chrono::system_clock::time_point date
Definition jwt.h:86
builder< Clock, json_traits > create(Clock c)
Definition jwt.h:4117
verifier< default_clock, traits::boost_json > verify()
Definition defaults.h:23
jwk< json_traits > parse_jwk(const typename json_traits::string_type &jwk_)
Definition jwt.h:4193
jwks< json_traits > parse_jwks(const typename json_traits::string_type &jwks_)
Definition jwt.h:4207
decoded_jwt< json_traits > decode(const typename json_traits::string_type &token, Decode decode)
Decode a token. This can be used to to help access important feild like 'x5c' for verifying tokens....
Definition jwt.h:4168
verify_ops::verify_context< traits::boost_json > verify_context
Definition defaults.h:88
Base class for ECDSA family of algorithms.
Definition jwt.h:1542
void verify(const std::string &data, const std::string &signature, std::error_code &ec) const
Definition jwt.h:1616
std::string sign(const std::string &data, std::error_code &ec) const
Definition jwt.h:1579
ecdsa(const std::string &public_key, const std::string &private_key, const std::string &public_key_password, const std::string &private_key_password, const EVP_MD *(*md)(), std::string name, size_t siglen)
Definition jwt.h:1554
std::string name() const
Definition jwt.h:1655
Definition jwt.h:2178
ed25519(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2188
Definition jwt.h:2200
ed448(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2210
Base class for EdDSA family of algorithms.
Definition jwt.h:1773
std::string name() const
Definition jwt.h:1887
eddsa(const std::string &public_key, const std::string &private_key, const std::string &public_key_password, const std::string &private_key_password, std::string name)
Definition jwt.h:1784
std::string sign(const std::string &data, std::error_code &ec) const
Definition jwt.h:1800
void verify(const std::string &data, const std::string &signature, std::error_code &ec) const
Definition jwt.h:1848
Definition jwt.h:2105
es256(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2115
Definition jwt.h:2156
es256k(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2165
Definition jwt.h:2122
es384(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2132
Definition jwt.h:2139
es512(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2149
Base class for HMAC family of algorithms.
Definition jwt.h:1372
std::string sign(const std::string &data, std::error_code &ec) const
Definition jwt.h:1389
std::string name() const
Definition jwt.h:1429
void verify(const std::string &data, const std::string &signature, std::error_code &ec) const
Definition jwt.h:1410
hmacsha(std::string key, const EVP_MD *(*md)(), std::string name)
Definition jwt.h:1380
Definition jwt.h:2027
hs256(std::string key)
Definition jwt.h:2032
Definition jwt.h:2037
hs384(std::string key)
Definition jwt.h:2042
Definition jwt.h:2047
hs512(std::string key)
Definition jwt.h:2052
"none" algorithm.
Definition jwt.h:1347
void verify(const std::string &, const std::string &signature, std::error_code &ec) const
Check if the given signature is empty.
Definition jwt.h:1362
std::string name() const
Get algorithm name.
Definition jwt.h:1367
std::string sign(const std::string &, std::error_code &ec) const
Return an empty string.
Definition jwt.h:1351
Definition jwt.h:2219
ps256(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2227
Definition jwt.h:2234
ps384(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2242
Definition jwt.h:2249
ps512(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2257
Base class for PSS-RSA family of algorithms.
Definition jwt.h:1899
std::string name() const
Definition jwt.h:2013
pss(const std::string &public_key, const std::string &private_key, const std::string &public_key_password, const std::string &private_key_password, const EVP_MD *(*md)(), std::string name)
Definition jwt.h:1909
void verify(const std::string &data, const std::string &signature, std::error_code &ec) const
Definition jwt.h:1974
std::string sign(const std::string &data, std::error_code &ec) const
Definition jwt.h:1926
Definition jwt.h:2059
rs256(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Construct new instance of algorithm.
Definition jwt.h:2068
Definition jwt.h:2075
rs384(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2083
Definition jwt.h:2090
rs512(const std::string &public_key, const std::string &private_key="", const std::string &public_key_password="", const std::string &private_key_password="")
Definition jwt.h:2098
Base class for RSA family of algorithms.
Definition jwt.h:1442
void verify(const std::string &data, const std::string &signature, std::error_code &ec) const
Definition jwt.h:1503
std::string sign(const std::string &data, std::error_code &ec) const
Definition jwt.h:1469
rsa(const std::string &public_key, const std::string &private_key, const std::string &public_key_password, const std::string &private_key_password, const EVP_MD *(*md)(), std::string name)
Definition jwt.h:1453
std::string name() const
Definition jwt.h:1529
Definition jwt.h:4124
date now() const
Definition jwt.h:4129
Definition jwt.h:101
Definition jwt.h:98
Definition jwt.h:3410
Definition jwt.h:3339
date current_time
Current time, retrieved from the verifiers clock and cached for performance and consistency.
Definition jwt.h:3343
basic_claim< json_traits > get_claim(bool in_header, json::type t, std::error_code &ec) const
Definition jwt.h:3380
size_t default_leeway
The configured default leeway for this verification.
Definition jwt.h:3347
basic_claim< json_traits > get_claim(bool in_header, std::error_code &ec) const
Helper method to get a claim from the jwt in this context.
Definition jwt.h:3358
basic_claim< json_traits > get_claim(json::type t, std::error_code &ec) const
Helper method to get a payload claim of a specific type from the jwt.
Definition jwt.h:3401
basic_claim< json_traits > get_claim(std::error_code &ec) const
Helper method to get a payload claim from the jwt.
Definition jwt.h:3394
json_traits::string_type claim_key
The claim key to apply this comparison on.
Definition jwt.h:3350
const decoded_jwt< json_traits > & jwt
The jwt passed to the verifier.
Definition jwt.h:3345