-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathjwt.ipp
905 lines (768 loc) · 23.1 KB
/
jwt.ipp
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
/*
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_IPP
#define JWT_IPP
#include "jwt/config.hpp"
#include "jwt/detail/meta.hpp"
#include <algorithm>
#include <iomanip>
namespace jwt {
/**
*/
static inline void jwt_throw_exception(const std::error_code& ec);
template <typename T, typename Cond>
std::string to_json_str(const T& obj, bool pretty)
{
return pretty ? obj.create_json_obj().dump(2)
: obj.create_json_obj().dump()
;
}
template <typename T>
std::ostream& write(std::ostream& os, const T& obj, bool pretty)
{
pretty ? (os << std::setw(2) << obj.create_json_obj())
: (os << obj.create_json_obj())
;
return os;
}
template <typename T, typename Cond>
std::ostream& operator<< (std::ostream& os, const T& obj)
{
os << obj.create_json_obj();
return os;
}
//========================================================================
inline void jwt_header::decode(const jwt::string_view enc_str, std::error_code& ec)
{
ec.clear();
std::string json_str = base64_decode(enc_str);
try {
payload_ = json_t::parse(std::move(json_str));
} catch(const std::exception&) {
ec = DecodeErrc::JsonParseError;
return;
}
//Look for the algorithm field
auto alg_itr = payload_.find("alg");
if (alg_itr == payload_.end()) {
ec = DecodeErrc::AlgHeaderMiss;
return;
}
alg_ = str_to_alg(alg_itr.value().get<std::string>());
if (alg_ != algorithm::NONE)
{
auto itr = payload_.find("typ");
if (itr != payload_.end()) {
const auto& typ = itr.value().get<std::string>();
if (strcasecmp(typ.c_str(), "JWT")) {
ec = DecodeErrc::TypMismatch;
return;
}
typ_ = str_to_type(typ);
}
} else {
//TODO:
}
// Populate header
for (auto it = payload_.begin(); it != payload_.end(); ++it) {
auto ret = headers_.insert(it.key());
if (!ret.second) {
ec = DecodeErrc::DuplClaims;
//ATTN: Dont stop the decode here
//Not a hard error.
}
}
return;
}
inline void jwt_header::decode(const jwt::string_view enc_str)
{
std::error_code ec;
decode(enc_str, ec);
if (ec) {
throw DecodeError(ec.message());
}
return;
}
inline void jwt_payload::decode(const jwt::string_view enc_str, std::error_code& ec)
{
ec.clear();
std::string json_str = base64_decode(enc_str);
try {
payload_ = json_t::parse(std::move(json_str));
} catch(const std::exception&) {
ec = DecodeErrc::JsonParseError;
return;
}
//populate the claims set
for (auto it = payload_.begin(); it != payload_.end(); ++it) {
auto ret = claim_names_.insert(it.key());
if (!ret.second) {
ec = DecodeErrc::DuplClaims;
break;
}
}
return;
}
inline void jwt_payload::decode(const jwt::string_view enc_str)
{
std::error_code ec;
decode(enc_str, ec);
if (ec) {
throw DecodeError(ec.message());
}
return;
}
inline std::string jwt_signature::encode(const jwt_header& header,
const jwt_payload& payload,
std::error_code& ec)
{
std::string jwt_msg;
ec.clear();
//TODO: Optimize allocations
sign_func_t sign_fn = get_sign_algorithm_impl(header);
std::string hdr_sign = header.base64_encode();
std::string pld_sign = payload.base64_encode();
std::string data = hdr_sign + '.' + pld_sign;
auto res = sign_fn(key_, data);
if (res.second && res.second != AlgorithmErrc::NoneAlgorithmUsed) {
ec = res.second;
return {};
}
std::string b64hash;
if (!res.second) {
b64hash = base64_encode(res.first.c_str(), res.first.length());
}
auto new_len = base64_uri_encode(&b64hash[0], b64hash.length());
b64hash.resize(new_len);
jwt_msg = data + '.' + b64hash;
return jwt_msg;
}
inline verify_result_t jwt_signature::verify(const jwt_header& header,
const jwt::string_view hdr_pld_sign,
const jwt::string_view jwt_sign)
{
auto check_res = check_for_algo_confusion_attack(header);
if (check_res.first) {
return {false, VerificationErrc::AlgoConfusionAttack};
}
verify_func_t verify_fn = get_verify_algorithm_impl(header);
return verify_fn(key_, hdr_pld_sign, jwt_sign);
}
inline verify_result_t jwt_signature::check_for_algo_confusion_attack(
const jwt_header& hdr) const
{
switch (hdr.algo()) {
case algorithm::RS256:
case algorithm::RS384:
case algorithm::RS512:
case algorithm::ES256:
case algorithm::ES384:
case algorithm::ES512:
return {false, std::error_code{}};
default:
// For all other cases make sure that the secret provided
// is not the public key.
return is_secret_a_public_key(key_);
}
}
inline sign_func_t
jwt_signature::get_sign_algorithm_impl(const jwt_header& hdr) const noexcept
{
sign_func_t ret = nullptr;
switch (hdr.algo()) {
case algorithm::HS256:
ret = HMACSign<algo::HS256>::sign;
break;
case algorithm::HS384:
ret = HMACSign<algo::HS384>::sign;
break;
case algorithm::HS512:
ret = HMACSign<algo::HS512>::sign;
break;
case algorithm::NONE:
ret = HMACSign<algo::NONE>::sign;
break;
case algorithm::RS256:
ret = PEMSign<algo::RS256>::sign;
break;
case algorithm::RS384:
ret = PEMSign<algo::RS384>::sign;
break;
case algorithm::RS512:
ret = PEMSign<algo::RS512>::sign;
break;
case algorithm::ES256:
ret = PEMSign<algo::ES256>::sign;
break;
case algorithm::ES384:
ret = PEMSign<algo::ES384>::sign;
break;
case algorithm::ES512:
ret = PEMSign<algo::ES512>::sign;
break;
default:
assert (0 && "Code not reached");
};
return ret;
}
inline verify_func_t
jwt_signature::get_verify_algorithm_impl(const jwt_header& hdr) const noexcept
{
verify_func_t ret = nullptr;
switch (hdr.algo()) {
case algorithm::HS256:
ret = HMACSign<algo::HS256>::verify;
break;
case algorithm::HS384:
ret = HMACSign<algo::HS384>::verify;
break;
case algorithm::HS512:
ret = HMACSign<algo::HS512>::verify;
break;
case algorithm::NONE:
ret = HMACSign<algo::NONE>::verify;
break;
case algorithm::RS256:
ret = PEMSign<algo::RS256>::verify;
break;
case algorithm::RS384:
ret = PEMSign<algo::RS384>::verify;
break;
case algorithm::RS512:
ret = PEMSign<algo::RS512>::verify;
break;
case algorithm::ES256:
ret = PEMSign<algo::ES256>::verify;
break;
case algorithm::ES384:
ret = PEMSign<algo::ES384>::verify;
break;
case algorithm::ES512:
ret = PEMSign<algo::ES512>::verify;
break;
default:
assert (0 && "Code not reached");
};
return ret;
}
//
template <typename First, typename... Rest,
typename SFINAE_COND>
jwt_object::jwt_object(
First&& first, Rest&&... rest)
{
static_assert (detail::meta::is_parameter_concept<First>::value &&
detail::meta::are_all_params<Rest...>::value,
"All constructor argument types must model ParameterConcept");
set_parameters(std::forward<First>(first), std::forward<Rest>(rest)...);
}
template <typename Map, typename... Rest>
void jwt_object::set_parameters(
params::detail::payload_param<Map>&& payload, Rest&&... rargs)
{
for (const auto& elem : payload.get()) {
payload_.add_claim(std::move(elem.first), std::move(elem.second));
}
set_parameters(std::forward<Rest>(rargs)...);
}
template <typename... Rest>
void jwt_object::set_parameters(
params::detail::secret_param secret, Rest&&... rargs)
{
secret_.assign(secret.get().data(), secret.get().length());
set_parameters(std::forward<Rest>(rargs)...);
}
template <typename... Rest>
void jwt_object::set_parameters(
params::detail::algorithm_param alg, Rest&&... rargs)
{
header_.algo(alg.get());
set_parameters(std::forward<Rest>(rargs)...);
}
template <typename Map, typename... Rest>
void jwt_object::set_parameters(
params::detail::headers_param<Map>&& header, Rest&&... rargs)
{
for (const auto& elem : header.get()) {
header_.add_header(std::move(elem.first), std::move(elem.second));
}
set_parameters(std::forward<Rest>(rargs)...);
}
inline void jwt_object::set_parameters()
{
//sentinel call
return;
}
inline jwt_object& jwt_object::add_claim(const jwt::string_view name, system_time_t tp)
{
return add_claim(
name,
std::chrono::duration_cast<
std::chrono::seconds>(tp.time_since_epoch()).count()
);
}
inline jwt_object& jwt_object::remove_claim(const jwt::string_view name)
{
payload_.remove_claim(name);
return *this;
}
inline std::string jwt_object::signature(std::error_code& ec) const
{
ec.clear();
//key/secret should be set for any algorithm except NONE
if (header().algo() != jwt::algorithm::NONE) {
if (secret_.length() == 0) {
ec = AlgorithmErrc::KeyNotFoundErr;
return {};
}
}
jwt_signature jws{secret_};
return jws.encode(header_, payload_, ec);
}
inline std::string jwt_object::signature() const
{
std::error_code ec;
std::string res = signature(ec);
if (ec) {
throw SigningError(ec.message());
}
return res;
}
template <typename Params, typename SequenceT>
std::error_code jwt_object::verify(
const Params& dparams,
const params::detail::algorithms_param<SequenceT>& algos) const
{
std::error_code ec{};
//Verify if the algorithm set in the header
//is any of the one expected by the client.
auto fitr = std::find_if(algos.get().begin(),
algos.get().end(),
[this](const auto& elem)
{
return jwt::str_to_alg(elem) == this->header().algo();
});
if (fitr == algos.get().end()) {
ec = VerificationErrc::InvalidAlgorithm;
return ec;
}
//Check for the expiry timings
if (has_claim(registered_claims::expiration)) {
auto curr_time =
std::chrono::duration_cast<
std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
auto p_exp = payload()
.get_claim_value<uint64_t>(registered_claims::expiration);
if (static_cast<uint64_t>(curr_time) > static_cast<uint64_t>(p_exp + dparams.leeway)) {
ec = VerificationErrc::TokenExpired;
return ec;
}
}
//Check for issuer
if (dparams.has_issuer)
{
if (has_claim(registered_claims::issuer))
{
const std::string& p_issuer = payload()
.get_claim_value<std::string>(registered_claims::issuer);
if (p_issuer != dparams.issuer) {
ec = VerificationErrc::InvalidIssuer;
return ec;
}
} else {
ec = VerificationErrc::InvalidIssuer;
return ec;
}
}
//Check for audience
if (dparams.has_aud)
{
if (has_claim(registered_claims::audience))
{
const std::string& p_aud = payload()
.get_claim_value<std::string>(registered_claims::audience);
if (p_aud != dparams.aud) {
ec = VerificationErrc::InvalidAudience;
return ec;
}
} else {
ec = VerificationErrc::InvalidAudience;
return ec;
}
}
//Check the subject
if (dparams.has_sub)
{
if (has_claim(registered_claims::subject))
{
const std::string& p_sub = payload()
.get_claim_value<std::string>(registered_claims::subject);
if (p_sub != dparams.sub) {
ec = VerificationErrc::InvalidSubject;
return ec;
}
} else {
ec = VerificationErrc::InvalidSubject;
return ec;
}
}
//Check for NBF
if (has_claim(registered_claims::not_before))
{
auto curr_time =
std::chrono::duration_cast<
std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
auto p_exp = payload()
.get_claim_value<uint64_t>(registered_claims::not_before);
if (static_cast<uint64_t>(p_exp - dparams.leeway) > static_cast<uint64_t>(curr_time)) {
ec = VerificationErrc::ImmatureSignature;
return ec;
}
}
//Check IAT validation
if (dparams.validate_iat) {
if (!has_claim(registered_claims::issued_at)) {
ec = VerificationErrc::InvalidIAT;
return ec;
} else {
// Will throw type conversion error
auto val = payload()
.get_claim_value<uint64_t>(registered_claims::issued_at);
(void)val;
}
}
//Check JTI validation
if (dparams.validate_jti) {
if (!has_claim("jti")) {
ec = VerificationErrc::InvalidJTI;
return ec;
}
}
return ec;
}
inline std::array<jwt::string_view, 3>
jwt_object::three_parts(const jwt::string_view enc_str)
{
std::array<jwt::string_view, 3> result;
size_t fpos = enc_str.find_first_of('.');
assert (fpos != jwt::string_view::npos);
result[0] = jwt::string_view{&enc_str[0], fpos};
size_t spos = enc_str.find_first_of('.', fpos + 1);
result[1] = jwt::string_view{&enc_str[fpos + 1], spos - fpos - 1};
if (spos + 1 != enc_str.length()) {
result[2] = jwt::string_view{&enc_str[spos + 1], enc_str.length() - spos - 1};
}
return result;
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_param s, Rest&&... args)
{
dparams.secret.assign(s.get().data(), s.get().length());
dparams.has_secret = true;
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename T, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::secret_function_param<T>&& s, Rest&&... args)
{
dparams.secret = s.get(*dparams.payload_ptr);
dparams.has_secret = true;
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::leeway_param l, Rest&&... args)
{
dparams.leeway = l.get();
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::verify_param v, Rest&&... args)
{
dparams.verify = v.get();
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::issuer_param i, Rest&&... args)
{
dparams.issuer = std::move(i).get();
dparams.has_issuer = true;
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::audience_param a, Rest&&... args)
{
dparams.aud = std::move(a).get();
dparams.has_aud = true;
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::subject_param s, Rest&&... args)
{
dparams.sub = std::move(s).get();
dparams.has_sub = true;
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::validate_iat_param v, Rest&&... args)
{
dparams.validate_iat = v.get();
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams, typename... Rest>
void jwt_object::set_decode_params(DecodeParams& dparams, params::detail::validate_jti_param v, Rest&&... args)
{
dparams.validate_jti = v.get();
jwt_object::set_decode_params(dparams, std::forward<Rest>(args)...);
}
template <typename DecodeParams>
void jwt_object::set_decode_params(DecodeParams& dparams)
{
(void) dparams; // prevent -Wunused-parameter with gcc
return;
}
//==================================================================
template <typename SequenceT, typename... Args>
jwt_object decode(const jwt::string_view enc_str,
const params::detail::algorithms_param<SequenceT>& algos,
std::error_code& ec,
Args&&... args)
{
ec.clear();
jwt_object obj;
if (algos.get().size() == 0) {
ec = DecodeErrc::EmptyAlgoList;
return obj;
}
struct decode_params
{
/// key to decode the JWS
bool has_secret = false;
std::string secret;
/// Verify parameter. Defaulted to true.
bool verify = true;
/// Leeway parameter. Defaulted to zero seconds.
uint32_t leeway = 0;
///The issuer
//TODO: optional type
bool has_issuer = false;
std::string issuer;
///The audience
//TODO: optional type
bool has_aud = false;
std::string aud;
//The subject
//TODO: optional type
bool has_sub = false;
std::string sub;
//Validate IAT
bool validate_iat = false;
//Validate JTI
bool validate_jti = false;
const jwt_payload* payload_ptr = 0;
};
decode_params dparams{};
//Signature must have atleast 2 dots
auto dot_cnt = std::count_if(std::begin(enc_str), std::end(enc_str),
[](char ch) { return ch == '.'; });
if (dot_cnt < 2) {
ec = DecodeErrc::SignatureFormatError;
return obj;
}
auto parts = jwt_object::three_parts(enc_str);
//throws decode error
jwt_header hdr{};
hdr.decode(parts[0], ec);
if (ec) {
return obj;
}
//obj.header(jwt_header{parts[0]});
obj.header(std::move(hdr));
//If the algorithm is not NONE, it must not
//have more than two dots ('.') and the split
//must result in three strings with some length.
if (obj.header().algo() != jwt::algorithm::NONE) {
if (dot_cnt > 2) {
ec = DecodeErrc::SignatureFormatError;
return obj;
}
if (parts[2].length() == 0) {
ec = DecodeErrc::SignatureFormatError;
return obj;
}
}
//throws decode error
jwt_payload payload{};
payload.decode(parts[1], ec);
if (ec) {
return obj;
}
obj.payload(std::move(payload));
dparams.payload_ptr = & obj.payload();
jwt_object::set_decode_params(dparams, std::forward<Args>(args)...);
if (dparams.verify) {
try {
ec = obj.verify(dparams, algos);
} catch (const json_ns::detail::type_error&) {
ec = VerificationErrc::TypeConversionError;
}
if (ec) return obj;
//Verify the signature only if some algorithm was used
if (obj.header().algo() != algorithm::NONE)
{
if (!dparams.has_secret) {
ec = DecodeErrc::KeyNotPresent;
return obj;
}
jwt_signature jsign{dparams.secret};
// Length of the encoded header and payload only.
// Addition of '1' to account for the '.' character.
auto l = parts[0].length() + 1 + parts[1].length();
//MemoryAllocationError is not caught
verify_result_t res = jsign.verify(obj.header(), enc_str.substr(0, l), parts[2]);
if (res.second) {
ec = res.second;
return obj;
}
if (!res.first) {
ec = VerificationErrc::InvalidSignature;
return obj;
}
} else {
ec = AlgorithmErrc::NoneAlgorithmUsed;
}
}
return obj;
}
template <typename SequenceT, typename... Args>
jwt_object decode(const jwt::string_view enc_str,
const params::detail::algorithms_param<SequenceT>& algos,
Args&&... args)
{
std::error_code ec{};
auto jwt_obj = decode(enc_str,
algos,
ec,
std::forward<Args>(args)...);
if (ec) {
jwt_throw_exception(ec);
}
return jwt_obj;
}
void jwt_throw_exception(const std::error_code& ec)
{
const auto& cat = ec.category();
if (&cat == &theVerificationErrorCategory ||
std::string(cat.name()) == std::string(theVerificationErrorCategory.name()))
{
switch (static_cast<VerificationErrc>(ec.value()))
{
case VerificationErrc::InvalidAlgorithm:
{
throw InvalidAlgorithmError(ec.message());
}
case VerificationErrc::TokenExpired:
{
throw TokenExpiredError(ec.message());
}
case VerificationErrc::InvalidIssuer:
{
throw InvalidIssuerError(ec.message());
}
case VerificationErrc::InvalidAudience:
{
throw InvalidAudienceError(ec.message());
}
case VerificationErrc::InvalidSubject:
{
throw InvalidSubjectError(ec.message());
}
case VerificationErrc::InvalidIAT:
{
throw InvalidIATError(ec.message());
}
case VerificationErrc::InvalidJTI:
{
throw InvalidJTIError(ec.message());
}
case VerificationErrc::ImmatureSignature:
{
throw ImmatureSignatureError(ec.message());
}
case VerificationErrc::InvalidSignature:
{
throw InvalidSignatureError(ec.message());
}
case VerificationErrc::TypeConversionError:
{
throw TypeConversionError(ec.message());
}
default:
assert (0 && "Unknown error code");
};
}
if (&cat == &theDecodeErrorCategory ||
std::string(cat.name()) == std::string(theDecodeErrorCategory.name()))
{
switch (static_cast<DecodeErrc>(ec.value()))
{
case DecodeErrc::SignatureFormatError:
{
throw SignatureFormatError(ec.message());
}
case DecodeErrc::KeyNotPresent:
{
throw KeyNotPresentError(ec.message());
}
case DecodeErrc::KeyNotRequiredForNoneAlg:
{
// Not an error. Just to be ignored.
break;
}
default:
{
throw DecodeError(ec.message());
}
};
assert (0 && "Unknown error code");
}
if (&cat == &theAlgorithmErrCategory ||
std::string(cat.name()) == std::string(theAlgorithmErrCategory.name()))
{
switch (static_cast<AlgorithmErrc>(ec.value()))
{
case AlgorithmErrc::InvalidKeyErr:
{
throw InvalidKeyError(ec.message());
}
case AlgorithmErrc::VerificationErr:
{
throw InvalidSignatureError(ec.message());
}
case AlgorithmErrc::NoneAlgorithmUsed:
{
//Not an error actually.
break;
}
default:
assert (0 && "Unknown error code or not to be treated as an error");
};
}
return;
}
} // END namespace jwt
#endif