Debian Codegraph @

include/jwt/jwt.hpp

raw
1 /*
2 Copyright (c) 2017 Arun Muralidharan
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #ifndef JWT_HPP
24 #define JWT_HPP
25
26 #include <set>
27 #include <array>
28 #include <string>
29 #include <chrono>
30 #include <ostream>
31 #include <cassert>
32 #include <cstring>
33
34 #include "jwt/assertions.hpp"
35 #include "jwt/base64.hpp"
36 #include "jwt/config.hpp"
37 #include "jwt/algorithm.hpp"
38 #include "jwt/string_view.hpp"
39 #include "jwt/parameters.hpp"
40 #include "jwt/exceptions.hpp"
41 #if defined(CPP_JWT_USE_VENDORED_NLOHMANN_JSON)
42 #include "jwt/json/json.hpp"
43 #else
44 #include "nlohmann/json.hpp"
45 #endif
46 // For convenience
47 using json_t = nlohmann::json;
48 using system_time_t = std::chrono::time_point<std::chrono::system_clock>;
49 namespace json_ns = nlohmann;
50
51 namespace jwt {
52
53 /**
54 * The type of header.
55 * NOTE: Only JWT is supported currently.
56 */
57 enum class type
58 {
59 NONE = 0,
60 JWT = 1,
61 };
62
63 /**
64 * Converts a string representing a value of type
65 * `enum class type` into its actual type.
66 */
67 inline enum type str_to_type(const jwt::string_view typ) noexcept
68 {
69 assert (typ.length() && "Empty type string");
70
71 if (!strcasecmp(typ.data(), "jwt")) return type::JWT;
72 else if(!strcasecmp(typ.data(), "none")) return type::NONE;
73
74 JWT_NOT_REACHED("Code not reached");
75 }
76
77
78 /**
79 * Converts an instance of type `enum class type`
80 * to its string equivalent.
81 */
82 inline jwt::string_view type_to_str(SCOPED_ENUM type typ)
83 {
84 switch (typ) {
85 case type::JWT: return "JWT";
86 default: assert (0 && "Unknown type");
87 };
88
89 JWT_NOT_REACHED("Code not reached");
90 }
91
92
93 /**
94 * Registered claim names.
95 */
96 enum class registered_claims
97 {
98 // Expiration Time claim
99 expiration = 0,
100 // Not Before Time claim
101 not_before,
102 // Issuer name claim
103 issuer,
104 // Audience claim
105 audience,
106 // Issued At Time claim
107 issued_at,
108 // Subject claim
109 subject,
110 // JWT ID claim
111 jti,
112 };
113
114
115 /**
116 * Converts an instance of type `enum class registered_claims`
117 * to its string equivalent representation.
118 */
119 inline jwt::string_view reg_claims_to_str(SCOPED_ENUM registered_claims claim) noexcept
120 {
121 switch (claim) {
122 case registered_claims::expiration: return "exp";
123 case registered_claims::not_before: return "nbf";
124 case registered_claims::issuer: return "iss";
125 case registered_claims::audience: return "aud";
126 case registered_claims::issued_at: return "iat";
127 case registered_claims::subject: return "sub";
128 case registered_claims::jti: return "jti";
129 default: assert (0 && "Not a registered claim");
130 };
131 JWT_NOT_REACHED("Code not reached");
132 }
133
134 /**
135 * A helper class that enables reuse of the
136 * std::set container with custom comparator.
137 */
138 struct jwt_set
139 {
140 /**
141 * Transparent comparator.
142 * @note: C++14 only.
143 */
144 struct case_compare
145 {
146 using is_transparent = std::true_type;
147
148 bool operator()(const jwt::string_view lhs, const jwt::string_view rhs) const noexcept
149 {
150 int ret = lhs.compare(rhs);
151 return (ret < 0);
152 }
153 };
154
155 using header_claim_set_t = std::set<std::string, case_compare>;
156 };
157
158 // Fwd declaration for friend functions to specify the
159 // default arguments
160 // See: https://stackoverflow.com/a/23336823/434233
161 template <typename T, typename = typename std::enable_if<
162 detail::meta::has_create_json_obj_member<T>{}>::type>
163 std::string to_json_str(const T& obj, bool pretty=false);
164
165 template <typename T>
166 std::ostream& write(std::ostream& os, const T& obj, bool pretty=false);
167
168 template <typename T,
169 typename = typename std::enable_if<
170 detail::meta::has_create_json_obj_member<T>{}>::type
171 >
172 std::ostream& operator<< (std::ostream& os, const T& obj);
173
174
175 /**
176 * A helper class providing the necessary functionalities
177 * for:
178 * a) converting an object into JSON string.
179 * b) writing to a standard output stream in JSON format.
180 * c) writing to standard console in JSON format using
181 * overloaded '<<' operator.
182 *
183 * @note: The JWT component classes inherits from this
184 * class to get the above functionalities.
185 */
186 struct write_interface
187 {
188 /**
189 * Converts an object of type `T` to its JSON
190 * string format.
191 * @note: Type `T` must have a member function named
192 * `create_json_obj`.
193 * The check is made at compile time. Check
194 * `meta::has_create_json_obj_member` for more details.
195 * This check is done in `Cond` template parameter.
196 *
197 * For pretty print, pass second parameter as `true`.
198 */
199 template <typename T, typename Cond>
200 friend std::string to_json_str(const T& obj, bool pretty);
201
202 /**
203 * Writes the object of instance `T` in JSON format
204 * to standard output stream.
205 * The requirements on type `T` is same as that for
206 * `to_json_str` API.
207 */
208 template <typename T>
209 friend std::ostream& write(
210 std::ostream& os, const T& obj, bool pretty);
211
212 /**
213 * An overloaded operator for writing to standard
214 * ostream in JSON format.
215 * The requirements on type `T` is same as that for
216 * `to_json_str` API.
217 *
218 * This API is same in functionality as that of
219 * `write` API. Only difference is that, there is no
220 * option to write the JSON representation in pretty
221 * format.
222 */
223 template <typename T, typename Cond>
224 friend std::ostream& operator<< (std::ostream& os, const T& obj);
225 };
226
227 /**
228 * Provides the functionality for doing
229 * base64 encoding and decoding from the
230 * json string.
231 *
232 * @note: The JWT component classes inherits from this
233 * class to get the base64 related encoding and decoding
234 * functionalities.
235 */
236 template <typename Derived>
237 struct base64_enc_dec
238 {
239 /**
240 * Does URL safe base64 encoding
241 */
242 std::string base64_encode(bool with_pretty = false) const
243 {
244 std::string jstr = to_json_str(*static_cast<const Derived*>(this), with_pretty);
245 std::string b64_str = jwt::base64_encode(jstr.c_str(), jstr.length());
246 // Do the URI safe encoding
247 auto new_len = jwt::base64_uri_encode(&b64_str[0], b64_str.length());
248 b64_str.resize(new_len);
249
250 return b64_str;
251 }
252
253 /**
254 * Does URL safe base64 decoding.
255 */
256 std::string base64_decode(const jwt::string_view encoded_str)
257 {
258 return jwt::base64_uri_decode(encoded_str.data(), encoded_str.length());
259 }
260
261 };
262
263
264 /**
265 * Component class representing JWT Header.
266 */
267 struct jwt_header: write_interface
268 , base64_enc_dec<jwt_header>
269 {
270 public: // 'tors
271 /*
272 * Default constructor.
273 */
274 jwt_header()
275 {
276 payload_["alg"] = "none";
277 payload_["typ"] = "JWT";
278 }
279
280 /**
281 * Constructor taking specified algorithm type
282 * and JWT type.
283 */
284 jwt_header(SCOPED_ENUM algorithm alg, SCOPED_ENUM type typ = type::JWT)
285 : alg_(alg)
286 , typ_(typ)
287 {
288 payload_["typ"] = std::string(type_to_str(typ_));
289 payload_["alg"] = std::string(alg_to_str(alg_));
290 }
291
292 /**
293 * Construct the header from an encoded string.
294 */
295 jwt_header(const jwt::string_view enc_str)
296 {
297 this->decode(enc_str);
298 }
299
300 /// Default Copy and assignment
301 jwt_header(const jwt_header&) = default;
302 jwt_header& operator=(const jwt_header&) = default;
303
304 ~jwt_header() = default;
305
306 public: // Exposed APIs
307 /**
308 * NOTE: Any previously saved json dump or the encoding of the
309 * header would not be valid after modifying the algorithm.
310 */
311 /**
312 * Set the algorithm.
313 */
314 void algo(SCOPED_ENUM algorithm alg)
315 {
316 alg_ = alg;
317 payload_["alg"] = std::string(alg_to_str(alg_));
318 }
319
320 /**
321 * Set the algorithm. String overload.
322 */
323 void algo(const jwt::string_view sv)
324 {
325 alg_ = str_to_alg(sv.data());
326 payload_["alg"] = std::string(alg_to_str(alg_));
327 }
328
329 /**
330 * Get the algorithm.
331 */
332 SCOPED_ENUM algorithm algo() const noexcept
333 {
334 return alg_;
335 }
336
337 /**
338 * NOTE: Any previously saved json dump or the encoding of the
339 * header would not be valid after modifying the type.
340 */
341 /**
342 * Set the JWT type.
343 */
344 void typ(SCOPED_ENUM type typ) noexcept
345 {
346 typ_ = typ;
347 payload_["typ"] = std::string(type_to_str(typ_));
348 }
349
350 /**
351 * Set the JWT type header. String overload.
352 */
353 void typ(const jwt::string_view sv)
354 {
355 typ_ = str_to_type(sv.data());
356 payload_["typ"] = std::string(type_to_str(typ_));
357 }
358
359 /**
360 * Get the JWT type.
361 */
362 SCOPED_ENUM type typ() const noexcept
363 {
364 return typ_;
365 }
366
367 /**
368 * Add a header to the JWT header.
369 */
370 template <typename T,
371 typename=std::enable_if_t<
372 !std::is_same<jwt::string_view, std::decay_t<T>>::value
373 >
374 >
375 bool add_header(const jwt::string_view hname, T&& hvalue, bool overwrite=false)
376 {
377 auto itr = headers_.find(hname);
378 if (itr != std::end(headers_) && !overwrite) {
379 return false;
380 }
381
382 headers_.emplace(hname.data(), hname.length());
383 payload_[hname.data()] = std::forward<T>(hvalue);
384
385 return true;
386 }
387
388 /**
389 * Add a header to the JWT header.
390 * Overload which takes the header value as `jwt::string_view`
391 */
392 bool add_header(const jwt::string_view cname, const jwt::string_view cvalue, bool overwrite=false)
393 {
394 return add_header(cname,
395 std::string{cvalue.data(), cvalue.length()},
396 overwrite);
397 }
398
399 /**
400 * Remove the header from JWT.
401 * NOTE: Special handling for removing type field
402 * from header. The typ_ is set to NONE when removed.
403 */
404 bool remove_header(const jwt::string_view hname)
405 {
406 if (!strcasecmp(hname.data(), "typ")) {
407 typ_ = type::NONE;
408 payload_.erase(hname.data());
409 return true;
410 }
411
412 auto itr = headers_.find(hname);
413 if (itr == std::end(headers_)) {
414 return false;
415 }
416 payload_.erase(hname.data());
417 headers_.erase(hname.data());
418
419 return true;
420 }
421
422 /**
423 * Checks if header with the given name
424 * is present or not.
425 */
426 bool has_header(const jwt::string_view hname)
427 {
428 if (!strcasecmp(hname.data(), "typ")) return typ_ != type::NONE;
429 return headers_.find(hname) != std::end(headers_);
430 }
431
432
433 /**
434 * Get the URL safe base64 encoded string
435 * of the header.
436 */
437 //TODO: error code ?
438 std::string encode(bool pprint = false)
439 {
440 return base64_encode(pprint);
441 }
442
443 /**
444 * Decodes the base64 encoded string to JWT header.
445 * @note: Overwrites the data member of this instance
446 * with the decoded values.
447 *
448 * This API takes an error_code to set the error instead
449 * of throwing an exception.
450 *
451 * @note: Exceptions related to memory allocation failures
452 * are not translated to an error_code. The API would
453 * still throw an exception in those cases.
454 */
455 void decode(const jwt::string_view enc_str, std::error_code& ec);
456
457 /**
458 * Exception throwing API version of decode.
459 * Throws `DecodeError` exception.
460 * Could also throw memory allocation failure
461 * exceptions.
462 */
463 void decode(const jwt::string_view enc_str);
464
465 /**
466 * Creates a `json_t` object this class instance.
467 * @note: Presence of this member function is a requirement
468 * for some interfaces (Eg: `write_interface`).
469 */
470 const json_t& create_json_obj() const
471 {
472 return payload_;
473 }
474
475 private: // Data members
476 /// The Algorithm to use for signature creation
477 SCOPED_ENUM algorithm alg_ = algorithm::NONE;
478
479 /// The type of header
480 SCOPED_ENUM type typ_ = type::JWT;
481
482 // The JSON payload object
483 json_t payload_;
484
485 //Extra headers for JWS
486 jwt_set::header_claim_set_t headers_;
487 };
488
489
490 /**
491 * Component class representing JWT Payload.
492 * The payload is nothing but a set of claims
493 * which are directly written into a JSON object.
494 */
495 struct jwt_payload: write_interface
496 , base64_enc_dec<jwt_payload>
497 {
498 public: // 'tors
499 /**
500 * Default constructor.
501 */
502 jwt_payload() = default;
503
504 /**
505 * Construct the payload from an encoded string.
506 * TODO: Throw an exception in case of error.
507 */
508 jwt_payload(const jwt::string_view enc_str)
509 {
510 this->decode(enc_str);
511 }
512
513 /// Default copy and assignment operations
514 jwt_payload(const jwt_payload&) = default;
515 jwt_payload& operator=(const jwt_payload&) = default;
516
517 ~jwt_payload() = default;
518
519 public: // Exposed APIs
520 /**
521 * Add a claim to the set.
522 * Parameters:
523 * cname - The name of the claim.
524 * cvalue - Value of the claim.
525 * overwrite - Over write the value if already present.
526 *
527 * @note: This overload works for all value types which
528 * are:
529 * a) _not_ an instance of type system_time_t.
530 * b) _not_ an instance of type jwt::string_view.
531 * c) can be written to `json_t` object.
532 */
533 template <typename T,
534 typename=typename std::enable_if_t<
535 !std::is_same<system_time_t, std::decay_t<T>>::value ||
536 !std::is_same<jwt::string_view, std::decay_t<T>>::value
537 >
538 >
539 bool add_claim(const jwt::string_view cname, T&& cvalue, bool overwrite=false)
540 {
541 // Duplicate claim names not allowed
542 // if overwrite flag is set to true.
543 auto itr = claim_names_.find(cname);
544 if (itr != claim_names_.end() && !overwrite) {
545 return false;
546 }
547
548 // Add it to the known set of claims
549 claim_names_.emplace(cname.data(), cname.length());
550
551 //Add it to the json payload
552 payload_[cname.data()] = std::forward<T>(cvalue);
553
554 return true;
555 }
556
557 /**
558 * Adds a claim.
559 * This overload takes string claim value.
560 */
561 bool add_claim(const jwt::string_view cname, const jwt::string_view cvalue, bool overwrite=false)
562 {
563 return add_claim(cname, std::string{cvalue.data(), cvalue.length()}, overwrite);
564 }
565
566 /**
567 * Adds a claim.
568 * This overload takes system_time_t claim value.
569 * @note: Useful for providing timestamp as the claim value.
570 */
571 bool add_claim(const jwt::string_view cname, system_time_t tp, bool overwrite=false)
572 {
573 return add_claim(
574 cname,
575 std::chrono::duration_cast<
576 std::chrono::seconds>(tp.time_since_epoch()).count(),
577 overwrite
578 );
579 }
580
581 /**
582 * Adds a claim.
583 * This overload takes `registered_claims` as the claim name.
584 */
585 template <typename T,
586 typename=std::enable_if_t<
587 !std::is_same<std::decay_t<T>, system_time_t>::value ||
588 !std::is_same<std::decay_t<T>, jwt::string_view>::value
589 >>
590 bool add_claim(SCOPED_ENUM registered_claims cname, T&& cvalue, bool overwrite=false)
591 {
592 return add_claim(
593 reg_claims_to_str(cname),
594 std::forward<T>(cvalue),
595 overwrite
596 );
597 }
598
599 /**
600 * Adds a claim.
601 * This overload takes `registered_claims` as the claim name and
602 * `system_time_t` as the claim value type.
603 */
604 bool add_claim(SCOPED_ENUM registered_claims cname, system_time_t tp, bool overwrite=false)
605 {
606 return add_claim(
607 reg_claims_to_str(cname),
608 std::chrono::duration_cast<
609 std::chrono::seconds>(tp.time_since_epoch()).count(),
610 overwrite
611 );
612 }
613
614 /**
615 * Adds a claim.
616 * This overload takes `registered_claims` as the claim name and
617 * `jwt::string_view` as the claim value type.
618 */
619 bool add_claim(SCOPED_ENUM registered_claims cname, jwt::string_view cvalue, bool overwrite=false)
620 {
621 return add_claim(
622 reg_claims_to_str(cname),
623 std::string{cvalue.data(), cvalue.length()},
624 overwrite
625 );
626 }
627
628 /**
629 * Gets the claim value provided the claim value name.
630 * @note: The claim name used here is Case Sensitive.
631 *
632 * The template type `T` is what the user expects the value
633 * type to be. If the type provided is incompatible the underlying
634 * JSON library will throw an exception.
635 */
636 template <typename T>
637 decltype(auto) get_claim_value(const jwt::string_view cname) const
638 {
639 return payload_[cname.data()].get<T>();
640 }
641
642 /**
643 * Gets the claim value provided the claim value name.
644 * This overload takes the claim name as an instance of
645 * type `registered_claims`.
646 *
647 * The template type `T` is what the user expects the value
648 * type to be. If the type provided is incompatible the underlying
649 * JSON library will throw an exception.
650 */
651 template <typename T>
652 decltype(auto) get_claim_value(SCOPED_ENUM registered_claims cname) const
653 {
654 return get_claim_value<T>(reg_claims_to_str(cname));
655 }
656
657 /**
658 * Remove a claim identified by a claim name.
659 */
660 bool remove_claim(const jwt::string_view cname)
661 {
662 auto itr = claim_names_.find(cname);
663 if (itr == claim_names_.end()) return false;
664
665 claim_names_.erase(itr);
666 payload_.erase(cname.data());
667
668 return true;
669 }
670
671 /**
672 * Remove a claim.
673 * Overload which takes the claim name as an instance
674 * of `registered_claims` type.
675 */
676 bool remove_claim(SCOPED_ENUM registered_claims cname)
677 {
678 return remove_claim(reg_claims_to_str(cname));
679 }
680
681 /**
682 * Checks whether a claim is present in the payload
683 * or not.
684 * @note: Claim name is case sensitive for this API.
685 */
686 //TODO: Not all libc++ version agrees with this
687 //because count() is not made const for is_transparent
688 //based overload
689 bool has_claim(const jwt::string_view cname) const noexcept
690 {
691 return claim_names_.find(cname) != std::end(claim_names_);
692 }
693
694 /**
695 * Checks whether a claim is present in the payload or
696 * not.
697 * Overload which takes the claim name as an instance
698 * of `registered_claims` type.
699 */
700 bool has_claim(SCOPED_ENUM registered_claims cname) const noexcept
701 {
702 return has_claim(reg_claims_to_str(cname));
703 }
704
705 /**
706 * Checks whether there is claim with a specific
707 * value in the payload.
708 */
709 template <typename T>
710 bool has_claim_with_value(const jwt::string_view cname, T&& cvalue) const
711 {
712 auto itr = claim_names_.find(cname);
713 if (itr == claim_names_.end()) return false;
714
715 return (cvalue == payload_[cname.data()]);
716 }
717
718 /**
719 * Checks whether there is claim with a specific
720 * value in the payload.
721 * Overload which takes the claim name as an instance of
722 * type `registered_claims`.
723 */
724 template <typename T>
725 bool has_claim_with_value(const SCOPED_ENUM registered_claims cname, T&& value) const
726 {
727 return has_claim_with_value(reg_claims_to_str(cname), std::forward<T>(value));
728 }
729
730 /**
731 * Encodes the payload as URL safe Base64 encoded
732 * string.
733 */
734 std::string encode(bool pprint = false)
735 {
736 return base64_encode(pprint);
737 }
738
739 /**
740 * Decodes an encoded string and overwrites the payload
741 * as per the encoded information.
742 *
743 * This version of API reports error via std::error_code.
744 *
745 * @note: Allocation failures are still thrown out
746 * as exceptions.
747 */
748 void decode(const jwt::string_view enc_str, std::error_code& ec);
749
750 /**
751 * Overload of decode API which throws exception
752 * on any failure.
753 *
754 * Throws DecodeError on failure.
755 */
756 void decode(const jwt::string_view enc_str);
757
758 /**
759 * Creates a JSON object of the payload.
760 *
761 * The presence of this API is required for
762 * making it work with `write_interface`.
763 */
764 const json_t& create_json_obj() const
765 {
766 return payload_;
767 }
768
769 private:
770
771 /// JSON object containing payload
772 json_t payload_;
773 /// The set of claim names in the payload
774 jwt_set::header_claim_set_t claim_names_;
775 };
776
777 /**
778 * Component class for representing JWT signature.
779 *
780 * Provides APIs for:
781 * a) Encoding header and payload to JWS string parts.
782 * b) Verifying the signature by matching it with header and payload
783 * signature.
784 */
785 struct jwt_signature
786 {
787 public: // 'tors
788 /// Default constructor
789 jwt_signature() = default;
790
791 /**
792 * Constructor which takes the key.
793 */
794 jwt_signature(const jwt::string_view key)
795 : key_(key.data(), key.length())
796 {
797 }
798
799 /// Default copy and assignment operator
800 jwt_signature(const jwt_signature&) = default;
801 jwt_signature& operator=(const jwt_signature&) = default;
802
803 ~jwt_signature() = default;
804
805 public: // Exposed APIs
806 /**
807 * Encodes the header and payload to get the
808 * three part JWS signature.
809 */
810 std::string encode(const jwt_header& header,
811 const jwt_payload& payload,
812 std::error_code& ec);
813
814 /**
815 * Verifies the JWS signature.
816 * Returns `verify_result_t` which is a pair
817 * of bool and error_code.
818 */
819 verify_result_t verify(const jwt_header& header,
820 const jwt::string_view hdr_pld_sign,
821 const jwt::string_view jwt_sign);
822
823 private: // Private implementation
824 /*!
825 */
826 sign_func_t get_sign_algorithm_impl(const jwt_header& hdr) const noexcept;
827
828 /*!
829 */
830 verify_func_t get_verify_algorithm_impl(const jwt_header& hdr) const noexcept;
831
832 /*!
833 */
834 verify_result_t check_for_algo_confusion_attack(const jwt_header& hdr) const;
835
836 private: // Data members;
837
838 /// The key for creating the JWS
839 std::string key_;
840 };
841
842
843 /**
844 * The main class representing the JWT object.
845 * It is a composition of all JWT composition classes.
846 *
847 * @note: This class does not provide all the required
848 * APIs in its public interface. Instead the class provides
849 * `header()` and `payload()` APIs. Those can be used to
850 * access more public APIs specific to those components.
851 */
852 class jwt_object
853 {
854 public: // 'tors
855 /**
856 * Default constructor.
857 */
858 jwt_object() = default;
859
860 /**
861 * Takes a variadic set of parameters.
862 * Each type must satisfy the
863 * `ParameterConcept` concept.
864 *
865 * The parameters that can be passed:
866 * 1. payload : Can pass a initializer list of pairs or any associative
867 * containers which models `MappingConcept` (see `meta::is_mapping_concept`)
868 * to populate claims. Use `add_claim` for more controlled additions.
869 *
870 * 2. secret : The secret to be used for generating and verification
871 * of JWT signature. Not required for NONE algorithm.
872 *
873 * 3. algorithm : The algorithm to be used for signing and decoding.
874 *
875 * 4. headers : Can pass a initializer list of pairs or any associative
876 * containers which models `MappingConcept` (see `meta::is_mapping_concept`)
877 * to populate header. Not much useful unless JWE is supported.
878 */
879 template <typename First, typename... Rest,
880 typename=std::enable_if_t<detail::meta::is_parameter_concept<First>::value>>
881 jwt_object(First&& first, Rest&&... rest);
882
883 public: // Exposed static APIs
884 /**
885 * Splitsa JWT string into its three parts
886 * using dot('.') as the delimiter.
887 *
888 * @note: Instead of actually splitting the API
889 * simply provides an array of view.
890 */
891 static std::array<jwt::string_view, 3>
892 three_parts(const jwt::string_view enc_str);
893
894 public: // Exposed APIs
895 /**
896 * Returns the payload component object by reference.
897 */
898 jwt_payload& payload() noexcept
899 {
900 return payload_;
901 }
902
903 /**
904 * Returns the payload component object by const-reference.
905 */
906 const jwt_payload& payload() const noexcept
907 {
908 return payload_;
909 }
910
911 /**
912 * Sets the payload component object.
913 */
914 void payload(const jwt_payload& p)
915 {
916 payload_ = p;
917 }
918
919 /**
920 * Sets the payload component object.
921 * Takes the payload object as rvalue-reference.
922 */
923 void payload(jwt_payload&& p)
924 {
925 payload_ = std::move(p);
926 }
927
928 /**
929 * Sets the header component object.
930 */
931 void header(const jwt_header& h)
932 {
933 header_ = h;
934 }
935
936 /**
937 * Sets the header component object.
938 * Takes the header object as rvalue-reference.
939 */
940 void header(jwt_header&& h)
941 {
942 header_ = std::move(h);
943 }
944
945 /**
946 * Get the header component object as reference.
947 */
948 jwt_header& header() noexcept
949 {
950 return header_;
951 }
952
953 /**
954 * Get the header component object as const-reference.
955 */
956 const jwt_header& header() const noexcept
957 {
958 return header_;
959 }
960
961 /**
962 * Get the secret to be used for signing.
963 */
964 std::string secret() const
965 {
966 return secret_;
967 }
968
969 /**
970 * Set the secret to be used for signing.
971 */
972 void secret(const jwt::string_view sv)
973 {
974 secret_.assign(sv.data(), sv.length());
975 }
976
977 /**
978 * Provides the glue interface for adding claim.
979 * @note: See `jwt_payload::add_claim` for more details.
980 */
981 template <typename T,
982 typename=typename std::enable_if_t<
983 !std::is_same<system_time_t, std::decay_t<T>>::value>>
984 jwt_object& add_claim(const jwt::string_view name, T&& value)
985 {
986 payload_.add_claim(name, std::forward<T>(value));
987 return *this;
988 }
989
990 /**
991 * Provides the glue interface for adding claim.
992 *
993 * @note: See `jwt_payload::add_claim` for more details.
994 *
995 * Specialization for time points.
996 * Eg: Users can set `exp` claim to `chrono::system_clock::now()`.
997 */
998 jwt_object& add_claim(const jwt::string_view name, system_time_t time_point);
999
1000 /**
1001 * Provides the glue interface for adding claim.
1002 * Overload for taking claim name as `registered_claims` instance.
1003 *
1004 * @note: See `jwt_payload::add_claim` for more details.
1005 */
1006 template <typename T>
1007 jwt_object& add_claim(SCOPED_ENUM registered_claims cname, T&& value)
1008 {
1009 return add_claim(reg_claims_to_str(cname), std::forward<T>(value));
1010 }
1011
1012 /**
1013 * Provides the glue interface for removing claim.
1014 *
1015 * @note: See `jwt_payload::remove_claim` for more details.
1016 */
1017 jwt_object& remove_claim(const jwt::string_view name);
1018
1019 /**
1020 * Provides the glue interface for removing claim.
1021 *
1022 * @note: See `jwt_payload::remove_claim` for more details.
1023 */
1024 jwt_object& remove_claim(SCOPED_ENUM registered_claims cname)
1025 {
1026 return remove_claim(reg_claims_to_str(cname));
1027 }
1028
1029 /**
1030 * Provides the glue interface for checking if a claim is present
1031 * or not.
1032 *
1033 * @note: See `jwt_payload::has_claim` for more details.
1034 */
1035 bool has_claim(const jwt::string_view cname) const noexcept
1036 {
1037 return payload().has_claim(cname);
1038 }
1039
1040 /**
1041 * Provides the glue interface for checking if a claim is present
1042 * or not.
1043 *
1044 * @note: See `jwt_payload::has_claim` for more details.
1045 */
1046 bool has_claim(SCOPED_ENUM registered_claims cname) const noexcept
1047 {
1048 return payload().has_claim(cname);
1049 }
1050
1051 /**
1052 * Generate the JWS for the header + payload using the secret.
1053 * This version takes the error_code for reporting errors.
1054 *
1055 * @note: The API would still throw for memory allocation exceptions
1056 * (`std::bad_alloc` or `jwt::MemoryAllocationException`)
1057 * or exceptions thrown by user types.
1058 */
1059 std::string signature(std::error_code& ec) const;
1060
1061 /**
1062 * Generate the JWS for the header + payload using the secret.
1063 * Exception throwing version.
1064 */
1065 std::string signature() const;
1066
1067 /**
1068 * Verify the signature.
1069 * TODO: Returns an error_code instead of taking
1070 * by reference.
1071 */
1072 template <typename Params, typename SequenceT>
1073 std::error_code verify(
1074 const Params& dparams,
1075 const params::detail::algorithms_param<SequenceT>& algos) const;
1076
1077 private: // private APIs
1078 /**
1079 */
1080 template <typename... Args>
1081 void set_parameters(Args&&... args);
1082
1083 /**
1084 */
1085 template <typename M, typename... Rest>
1086 void set_parameters(params::detail::payload_param<M>&&, Rest&&...);
1087
1088 /**
1089 */
1090 template <typename... Rest>
1091 void set_parameters(params::detail::secret_param, Rest&&...);
1092
1093 /**
1094 */
1095 template <typename... Rest>
1096 void set_parameters(params::detail::algorithm_param, Rest&&...);
1097
1098 /**
1099 */
1100 template <typename M, typename... Rest>
1101 void set_parameters(params::detail::headers_param<M>&&, Rest&&...);
1102
1103 /**
1104 */
1105 void set_parameters();
1106
1107 public: //TODO: Not good
1108 /// Decode parameters
1109 template <typename DecodeParams, typename... Rest>
1110 static void set_decode_params(DecodeParams& dparams, params::detail::secret_param s, Rest&&... args);
1111
1112 template <typename DecodeParams, typename T, typename... Rest>
1113 static void set_decode_params(DecodeParams& dparams, params::detail::secret_function_param<T>&& s, Rest&&... args);
1114
1115 template <typename DecodeParams, typename... Rest>
1116 static void set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args);
1117
1118 template <typename DecodeParams, typename... Rest>
1119 static void set_decode_params(DecodeParams& dparams, params::detail::verify_param v, Rest&&... args);
1120
1121 template <typename DecodeParams, typename... Rest>
1122 static void set_decode_params(DecodeParams& dparams, params::detail::issuer_param i, Rest&&... args);
1123
1124 template <typename DecodeParams, typename... Rest>
1125 static void set_decode_params(DecodeParams& dparams, params::detail::audience_param a, Rest&&... args);
1126
1127 template <typename DecodeParams, typename... Rest>
1128 static void set_decode_params(DecodeParams& dparams, params::detail::subject_param a, Rest&&... args);
1129
1130 template <typename DecodeParams, typename... Rest>
1131 static void set_decode_params(DecodeParams& dparams, params::detail::validate_iat_param v, Rest&&... args);
1132
1133 template <typename DecodeParams, typename... Rest>
1134 static void set_decode_params(DecodeParams& dparams, params::detail::validate_jti_param v, Rest&&... args);
1135
1136 template <typename DecodeParams>
1137 static void set_decode_params(DecodeParams& dparams);
1138
1139 private: // Data Members
1140
1141 /// JWT header section
1142 jwt_header header_;
1143
1144 /// JWT payload section
1145 jwt_payload payload_;
1146
1147 /// The secret key
1148 std::string secret_;
1149 };
1150
1151 /**
1152 * Decode the JWT signature to create the `jwt_object`.
1153 * This version reports error back using `std::error_code`.
1154 *
1155 * If any of the registered claims are found in wrong format
1156 * then sets TypeConversion error in the error_code.
1157 *
1158 * NOTE: Memory allocation exceptions are not caught.
1159 *
1160 * Optional parameters that can be passed:
1161 * 1. verify : A boolean flag to indicate whether
1162 * the signature should be verified or not.
1163 * Set to `true` by default.
1164 *
1165 * 2. leeway : Number of seconds that can be added (in case of exp)
1166 * or subtracted (in case of nbf) to be more lenient.
1167 * Set to `0` by default.
1168 *
1169 * 3. algorithms : Takes in a sequence of algorithms which the client
1170 * expects the signature to be decoded with.
1171 *
1172 * 4. aud : The audience the client expects to be in the claim.
1173 * NOTE: It is case-sensitive.
1174 *
1175 * 5. issuer: The issuer the client expects to be in the claim.
1176 * NOTE: It is case-sensitive
1177 *
1178 * 6. sub: The subject the client expects to be in the claim.
1179 *
1180 * 7. validate_iat: Checks if IAT claim is present or not
1181 * and the type is uint64_t or not. If claim is not present
1182 * then set InvalidIAT error.
1183 *
1184 * 8. validate_jti: Checks if jti claim is present or not.
1185 */
1186 template <typename SequenceT, typename... Args>
1187 jwt_object decode(const jwt::string_view enc_str,
1188 const params::detail::algorithms_param<SequenceT>& algos,
1189 std::error_code& ec,
1190 Args&&... args);
1191
1192 /**
1193 * Decode the JWT signature to create the `jwt_object`.
1194 * This version reports error back by throwing exceptions.
1195 */
1196 template <typename SequenceT, typename... Args>
1197 jwt_object decode(const jwt::string_view enc_str,
1198 const params::detail::algorithms_param<SequenceT>& algos,
1199 Args&&... args);
1200
1201
1202 } // END namespace jwt
1203
1204
1205 #include "jwt/impl/jwt.ipp"
1206
1207 #endif