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