forked from sony/nmos-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorization_operation.cpp
More file actions
2019 lines (1716 loc) · 123 KB
/
authorization_operation.cpp
File metadata and controls
2019 lines (1716 loc) · 123 KB
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
#include "nmos/authorization_operation.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/range/join.hpp>
#include "cpprest/code_challenge_method.h"
#include "cpprest/json_validator.h"
#include "cpprest/response_type.h"
#include "cpprest/token_endpoint_auth_method.h"
#include "nmos/api_utils.h"
#include "nmos/authorization.h"
#include "nmos/authorization_scopes.h"
#include "nmos/authorization_state.h"
#include "nmos/authorization_utils.h"
#include "nmos/client_utils.h"
#include "nmos/is10_versions.h"
#include "nmos/json_schema.h"
#include "nmos/jwt_generator.h"
#include "nmos/jwk_utils.h"
#include "nmos/model.h"
#include "nmos/random.h"
#include "nmos/slog.h"
namespace nmos
{
namespace experimental
{
// authorization operation
namespace details
{
static const web::json::experimental::json_validator& authapi_validator()
{
static const web::json::experimental::json_validator validator
{
nmos::experimental::load_json_schema,
boost::copy_range<std::vector<web::uri>>(boost::join(boost::join(boost::join(boost::join(boost::join(
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_auth_metadata_schema_uri),
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_jwks_response_schema_uri)),
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_register_client_response_uri)),
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_token_error_response_uri)),
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_token_response_schema_uri)),
is10_versions::all | boost::adaptors::transformed(experimental::make_authapi_token_schema_schema_uri)))
};
return validator;
}
// build the scope string with given list of scopes
utility::string_t make_scope(const std::set<nmos::experimental::scope>& scopes_)
{
utility::string_t scopes;
for (const auto& scope : scopes_)
{
if (!scopes.empty()) { scopes += U(" "); }
scopes += scope.name;
}
return scopes;
}
// build grant array with given list of grants
web::json::value make_grant_types(const std::set<web::http::oauth2::experimental::grant_type>& grants)
{
auto grant_types = web::json::value::array();
for (const auto& grant : grants)
{
web::json::push_back(grant_types, grant.name);
}
return grant_types;
}
// generate SHA256 with the given string
std::vector<uint8_t> sha256(const std::string& text)
{
#if OPENSSL_VERSION_NUMBER < 0x30000000L
uint8_t hash[SHA256_DIGEST_LENGTH];
SHA256_CTX ctx;
if (SHA256_Init(&ctx) && SHA256_Update(&ctx, text.c_str(), text.size()) && SHA256_Final(hash, &ctx))
{
return{ hash, hash + SHA256_DIGEST_LENGTH };
}
#else
typedef std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> EVP_MD_CTX_ptr;
uint8_t hash[EVP_MAX_MD_SIZE];
uint32_t md_len{ 0 };
EVP_MD_CTX_ptr mdctx(EVP_MD_CTX_new(), &EVP_MD_CTX_free);
if (EVP_DigestInit_ex(mdctx.get(), EVP_sha256(), NULL) && EVP_DigestUpdate(mdctx.get(), text.c_str(), text.size()) && EVP_DigestFinal_ex(mdctx.get(), hash, &md_len))
{
return{ hash, hash + md_len };
}
#endif
return{};
}
// use the authorization URI on a web browser to start the authorization code flow
web::uri make_authorization_code_uri(const web::uri& authorization_endpoint, const utility::string_t& client_id, const web::uri& redirect_uri, const web::http::oauth2::experimental::response_type& response_type, const std::set<scope>& scopes, const web::json::array& code_challenge_methods_supported, utility::string_t& state, utility::string_t& code_verifier)
{
using web::http::oauth2::details::oauth2_strings;
web::uri_builder ub(authorization_endpoint);
ub.append_query(oauth2_strings::client_id, client_id);
ub.append_query(oauth2_strings::redirect_uri, redirect_uri.to_string());
ub.append_query(oauth2_strings::response_type, response_type.name);
// using PKCE?
if (code_challenge_methods_supported.size())
{
const auto found = std::find_if(code_challenge_methods_supported.begin(), code_challenge_methods_supported.end(), [&](const web::json::value& code_challenge_method)
{
return web::http::oauth2::experimental::code_challenge_methods::S256.name == code_challenge_method.as_string();
});
const auto code_challenge_method = (code_challenge_methods_supported.end() != found) ? web::http::oauth2::experimental::code_challenge_methods::S256 : web::http::oauth2::experimental::code_challenge_methods::plain;
// code_verifier = high-entropy cryptographic random STRING using the
// unreserved characters[A - Z] / [a - z] / [0 - 9] / "-" / "." / "_" / "~"
// from Section 2.3 of[RFC3986], with a minimum length of 43 characters
// and a maximum length of 128 characters
// see https://tools.ietf.org/html/rfc7636#section-4.1
{
utility::nonce_generator generator(128);
code_verifier = generator.generate();
}
// creates code challenge from code verifier
// see https://tools.ietf.org/html/rfc7636#section-4.2
utility::string_t code_challenge{};
if (web::http::oauth2::experimental::code_challenge_methods::plain == code_challenge_method)
{
code_challenge = code_verifier;
}
else
{
const auto sha256 = nmos::experimental::details::sha256(utility::us2s(code_verifier));
code_challenge = utility::conversions::to_base64url(sha256);
}
ub.append_query(U("code_challenge"), code_challenge);
ub.append_query(U("code_challenge_method"), code_challenge_method.name);
}
utility::nonce_generator generator;
state = generator.generate();
ub.append_query(oauth2_strings::state, state);
if (scopes.size())
{
ub.append_query(oauth2_strings::scope, make_scope(scopes));
}
return ub.to_uri();
}
// used to strip the trailing dot of the FQDN if it is presented
utility::string_t strip_trailing_dot(const utility::string_t& host_)
{
auto host = host_;
if (!host.empty() && U('.') == host.back())
{
host.pop_back();
}
return host;
}
// construct the redirect URI from settings
// format of the authorization_redirect_uri "<http scheme>://<FQDN>:<port>/x-authorization/callback/"
web::uri make_authorization_redirect_uri(const nmos::settings& settings)
{
return web::uri_builder()
.set_scheme(web::http_scheme(nmos::experimental::fields::client_secure(settings)))
.set_host(nmos::experimental::fields::no_trailing_dot_for_authorization_callback_uri(settings) ? strip_trailing_dot(get_host(settings)) : get_host(settings))
.set_port(nmos::experimental::fields::authorization_redirect_port(settings))
.set_path(U("/x-authorization/callback"))
.to_uri();
}
// construct the jwks URI from settings
// format of the jwks_uri "<http scheme>://<FQDN>:<port>/x-authorization/jwks/"
web::uri make_jwks_uri(const nmos::settings& settings)
{
return web::uri_builder()
.set_scheme(web::http_scheme(nmos::experimental::fields::client_secure(settings)))
.set_host(nmos::experimental::fields::no_trailing_dot_for_authorization_callback_uri(settings) ? strip_trailing_dot(get_host(settings)) : get_host(settings))
.set_port(nmos::experimental::fields::jwks_uri_port(settings))
.set_path(U("/x-authorization/jwks"))
.to_uri();
}
// construct the authorization server URI using the given URI authority
// format of the authorization_service_uri "<http scheme>://<FQDN>:<port>/.well-known/oauth-authorization-server[/<api_selector>]"
web::uri make_authorization_service_uri(const web::uri& uri, const utility::string_t& api_selector = {})
{
return web::uri_builder(uri.authority()).set_path(U("/.well-known/oauth-authorization-server")).append_path(!api_selector.empty() ? U("/") + api_selector : U("")).to_uri();
}
// construct authorization client config based on settings
// with the remaining options defaulted, e.g. authorization request timeout
web::http::client::http_client_config make_authorization_http_client_config(const nmos::settings& settings, load_ca_certificates_handler load_ca_certificates, const web::http::oauth2::experimental::oauth2_token& bearer_token, slog::base_gate& gate)
{
auto config = nmos::make_http_client_config(settings, load_ca_certificates, bearer_token, gate);
config.set_timeout(std::chrono::seconds(nmos::experimental::fields::authorization_request_max(settings)));
return config;
}
struct authorization_exception {};
// parse the given json to obtain bearer token
// this function is based on the oauth2_config::_parse_token_from_json(const json::value& token_json) from cpprestsdk's oauth2.cpp
web::http::oauth2::experimental::oauth2_token parse_token_from_json(const web::json::value& token_json)
{
using web::http::oauth2::details::oauth2_strings;
using web::http::oauth2::experimental::oauth2_token;
using web::http::oauth2::experimental::oauth2_exception;
oauth2_token result;
if (token_json.has_string_field(oauth2_strings::access_token))
{
result.set_access_token(token_json.at(oauth2_strings::access_token).as_string());
}
else
{
#if defined (NDEBUG)
throw oauth2_exception(U("response json contains no 'access_token'"));
#else
throw oauth2_exception(U("response json contains no 'access_token': ") + token_json.serialize());
#endif
}
if (token_json.has_string_field(oauth2_strings::token_type))
{
result.set_token_type(token_json.at(oauth2_strings::token_type).as_string());
}
else
{
// Some services don't return 'token_type' even though it's required by the OAuth 2.0 spec:
// http://tools.ietf.org/html/rfc6749#section-5.1
// As workaround we act as if 'token_type=bearer' was received.
result.set_token_type(oauth2_strings::bearer);
}
if (!utility::details::str_iequal(result.token_type(), oauth2_strings::bearer))
{
#if defined (NDEBUG)
throw oauth2_exception(U("only bearer tokens are currently supported"));
#else
throw oauth2_exception(U("only bearer tokens are currently supported: ") + token_json.serialize());
#endif
}
if (token_json.has_string_field(oauth2_strings::refresh_token))
{
result.set_refresh_token(token_json.at(oauth2_strings::refresh_token).as_string());
}
else
{
// Do nothing. Preserves the old refresh token
}
if (token_json.has_field(oauth2_strings::expires_in))
{
const auto& json_expires_in_val = token_json.at(oauth2_strings::expires_in);
if (json_expires_in_val.is_number())
{
result.set_expires_in(json_expires_in_val.as_number().to_int64());
}
else
{
// Handle the case of a number as a JSON "string"
int64_t expires;
utility::istringstream_t iss(json_expires_in_val.as_string());
iss.exceptions(std::ios::badbit | std::ios::failbit);
iss >> expires;
result.set_expires_in(expires);
}
}
else
{
result.set_expires_in(oauth2_token::undefined_expiration);
}
if (token_json.has_string_field(oauth2_strings::scope))
{
// The authorization server may return different scope from the one requested
// This however doesn't necessarily mean the token authorization scope is different
// See: http://tools.ietf.org/html/rfc6749#section-3.3
result.set_scope(token_json.at(oauth2_strings::scope).as_string());
}
return result;
}
// make an asynchronously GET request on the Authorization API to fetch authorization server metadata
pplx::task<web::json::value> request_authorization_server_metadata(web::http::client::http_client client, const std::set<nmos::experimental::scope>& scopes, const std::set<web::http::oauth2::experimental::grant_type>& grants, const web::http::oauth2::experimental::token_endpoint_auth_method& token_endpoint_auth_method, const nmos::api_version& version, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Requesting authorization server metadata at " << client.base_uri().to_string();
using namespace web::http;
// <api_proto>://<hostname>:<port>/.well-known/oauth-authorization-server[/<api_selector>]
// see https://specs.amwa.tv/is-10/releases/v1.0.0/docs/3.0._Discovery.html#authorization-server-metadata-endpoint
return nmos::api_request(client, methods::GET, gate, token).then([=, &gate](pplx::task<http_response> response_task)
{
namespace response_types = web::http::oauth2::experimental::response_types;
namespace grant_types = web::http::oauth2::experimental::grant_types;
auto response = response_task.get(); // may throw http_exception
if (status_codes::OK == response.status_code())
{
if (response.body())
{
return response.extract_json().then([=, &gate](web::json::value metadata)
{
// validate server metadata
authapi_validator().validate(metadata, experimental::make_authapi_auth_metadata_schema_uri(version)); // may throw json_exception
// hmm, verify Authorization server meets the minimum client requirement.
// are the required response_types supported by the Authorization server?
std::set<web::http::oauth2::experimental::response_type> response_types = { response_types::code };
if (grants.end() != std::find_if(grants.begin(), grants.end(), [](const web::http::oauth2::experimental::grant_type& grant) { return grant_types::implicit == grant; }))
{
response_types.insert(response_types::token);
}
if (response_types.size())
{
const auto supported = std::all_of(response_types.begin(), response_types.end(), [&](const web::http::oauth2::experimental::response_type& response_type)
{
const auto& response_types_supported = nmos::experimental::fields::response_types_supported(metadata);
const auto found = std::find_if(response_types_supported.begin(), response_types_supported.end(), [&response_type](const web::json::value& response_type_) { return response_type_.as_string() == response_type.name; });
return response_types_supported.end() != found;
});
if (!supported)
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: server does not supporting all the required response types";
throw authorization_exception();
}
}
// scopes_supported is optional
if (scopes.size() && metadata.has_array_field(nmos::experimental::fields::scopes_supported))
{
// are the required scopes supported by the Authorization server?
const auto supported = std::all_of(scopes.begin(), scopes.end(), [&](const nmos::experimental::scope& scope)
{
const auto& scopes_supported = nmos::experimental::fields::scopes_supported(metadata);
const auto found = std::find_if(scopes_supported.begin(), scopes_supported.end(), [&scope](const web::json::value& scope_) { return scope_.as_string() == scope.name; });
return scopes_supported.end() != found;
});
if (!supported)
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: server does not support all the required scopes: " << [&scopes]() { std::stringstream ss; for (auto scope : scopes) ss << utility::us2s(scope.name) << " "; return ss.str(); }();
throw authorization_exception();
}
}
// grant_types_supported is optional
if (grants.size() && metadata.has_array_field(nmos::experimental::fields::grant_types_supported))
{
// are the required grants supported by the Authorization server?
const auto supported = std::all_of(grants.begin(), grants.end(), [&](const web::http::oauth2::experimental::grant_type& grant)
{
const auto& grants_supported = nmos::experimental::fields::grant_types_supported(metadata);
const auto found = std::find_if(grants_supported.begin(), grants_supported.end(), [&grant](const web::json::value& grant_) { return grant_.as_string() == grant.name; });
return grants_supported.end() != found;
});
if (!supported)
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: server does not support all the required grants: " << [&grants]() { std::stringstream ss; for (auto grant : grants) ss << utility::us2s(grant.name) << " "; return ss.str(); }();
throw authorization_exception();
}
}
// token_endpoint_auth_methods_supported is optional
if (metadata.has_array_field(nmos::experimental::fields::token_endpoint_auth_methods_supported))
{
// is the required token_endpoint_auth_method supported by the Authorization server?
const auto& supported = nmos::experimental::fields::token_endpoint_auth_methods_supported(metadata);
const auto found = std::find_if(supported.begin(), supported.end(), [&token_endpoint_auth_method](const web::json::value& token_endpoint_auth_method_) { return token_endpoint_auth_method_.as_string() == token_endpoint_auth_method.name; });
if (supported.end() == found)
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: server does not supporting the required token_endpoint_auth_method:" << token_endpoint_auth_method.name;
throw authorization_exception();
}
}
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Received authorization server metadata: " << utility::us2s(metadata.serialize());
return metadata;
}, token);
}
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: no response body";
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization server metadata error: " << response.status_code() << " " << response.reason_phrase();
}
throw authorization_exception();
}, token);
}
// make an asynchronously POST request on the Authorization API to register a client
// see https://tools.ietf.org/html/rfc6749#section-2
// see https://tools.ietf.org/html/rfc7591#section-3.1
// e.g. curl -X POST "https://authorization.server.example.com/register" -H "Content-Type: application/json" -d "{\"redirect_uris\": [\"https://client.example.com/callback/\"],\"client_name\": \"My Example Client\",\"client_uri\": \"https://client.example.com/details.html\",\"token_endpoint_auth_method\": \"client_secret_basic\",\"response_types\": [\"code\",\"token\"],\"scope\": \"registration query node connection\",\"grant_types\": [\"authorization_code\",\"refresh_token\",\"client_credentials\"],\"token_endpoint_auth_method\": \"client_secret_basic\"}"
pplx::task<web::json::value> request_client_registration(web::http::client::http_client client, const utility::string_t& client_name, const std::vector<web::uri>& redirect_uris, const web::uri& client_uri, const std::set<web::http::oauth2::experimental::response_type>& response_types, const std::set<scope>& scopes, const std::set<web::http::oauth2::experimental::grant_type>& grants, const web::http::oauth2::experimental::token_endpoint_auth_method& token_endpoint_auth_method, const web::json::value& jwk, const web::uri& jwks_uri, const nmos::api_version& version, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Requesting authorization client registration at " << client.base_uri().to_string();
using namespace web;
using namespace web::http;
using web::json::value;
using web::json::value_of;
const auto make_uris = [](const std::vector<web::uri>& uris)
{
auto result = value::array();
for (const auto& uri : uris) { web::json::push_back(result, uri.to_string()); }
return result;
};
const auto make_response_types = [](const std::set<web::http::oauth2::experimental::response_type>& response_types)
{
auto result = value::array();
for (const auto& response_type : response_types) { web::json::push_back(result, response_type.name); }
return result;
};
const auto make_scope = [](const std::set<scope>& scopes)
{
std::ostringstream os;
int idx{ 0 };
for (const auto& scope : scopes)
{
if (idx++) { os << " "; }
os << utility::us2s(scope.name);
}
return value(utility::s2us(os.str()));
};
const auto make_grant_type = [](const std::set<web::http::oauth2::experimental::grant_type>& grants)
{
auto result = value::array();
for (const auto& grant : grants) { web::json::push_back(result, grant.name); }
return result;
};
// required
auto metadata = value_of({
{ nmos::experimental::fields::client_name, client_name }
});
// optional
if (grants.end() != std::find_if(grants.begin(), grants.end(), [](const web::http::oauth2::experimental::grant_type& grant) { return web::http::oauth2::experimental::grant_types::authorization_code == grant; }))
{
metadata[nmos::experimental::fields::redirect_uris] = make_uris(redirect_uris);
}
if (!client_uri.is_empty())
{
metadata[nmos::experimental::fields::client_uri] = value::string(client_uri.to_string());
}
if (response_types.size())
{
metadata[nmos::experimental::fields::response_types] = make_response_types(response_types);
}
if (scopes.size())
{
metadata[nmos::experimental::fields::scope] = make_scope(scopes);
}
if (grants.size())
{
metadata[nmos::experimental::fields::grant_types] = make_grant_type(grants);
}
metadata[nmos::experimental::fields::token_endpoint_auth_method] = value::string(token_endpoint_auth_method.name);
if (web::http::oauth2::experimental::token_endpoint_auth_methods::private_key_jwt == token_endpoint_auth_method)
{
if (!jwks_uri.is_empty())
{
metadata[nmos::experimental::fields::jwks_uri] = value::string(jwks_uri.to_string());
}
else
{
metadata[nmos::experimental::fields::jwks] = value_of({
{ nmos::experimental::fields::keys, value_of({ jwk }) }
});
}
}
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Request to register client metadata: " << utility::us2s(metadata.serialize()) << " at " << client.base_uri().to_string();
return nmos::api_request(client, methods::POST, {}, metadata, gate, token).then([=, &gate](pplx::task<http_response> response_task)
{
auto response = response_task.get(); // may throw http_exception
if (response.body())
{
return response.extract_json().then([=, &gate](web::json::value client_metadata)
{
if (status_codes::Created == response.status_code())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Registered client metadata: " << utility::us2s(client_metadata.serialize());
// validate client metadata
authapi_validator().validate(client_metadata, experimental::make_authapi_register_client_response_uri(version)); // may throw json_exception
return client_metadata;
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request client registration error: " << response.status_code() << " " << response.reason_phrase() << " " << utility::us2s(client_metadata.serialize());
throw authorization_exception();
}
}, token);
}
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request client registration error: " << response.status_code() << " " << response.reason_phrase();
throw authorization_exception();
}, token);
}
// make an asynchronously GET request on the Authorization API to fetch the authorization JSON Web Keys (public keys)
pplx::task<web::json::value> request_jwks(web::http::client::http_client client, const nmos::api_version& version, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Requesting authorization jwks at " << client.base_uri().to_string();
using namespace web::http;
using oauth2::experimental::oauth2_exception;
return nmos::api_request(client, methods::GET, gate, token).then([=, &gate](pplx::task<http_response> response_task)
{
auto response = response_task.get(); // may throw http_exception
if (status_codes::OK == response.status_code())
{
if (response.body())
{
return nmos::details::extract_json(response, gate).then([version, &gate](web::json::value body)
{
// validate jwks JSON
authapi_validator().validate(body, experimental::make_authapi_jwks_response_schema_uri(version)); // may throw json_exception
// MUST have a "keys" member!
// see https://tools.ietf.org/html/rfc7517#section-5
if (!body.has_array_field(U("keys"))) throw web::http::http_exception(U("jwks contains no 'keys': ") + body.serialize());
const auto jwks = body.at(U("keys"));
jwks.as_array().size() ? slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Received authorization jwks: " << utility::us2s(jwks.serialize()) :
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Request authorization jwks: no jwk";
return jwks;
}, token);
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization jwks error: no response body";
}
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Request authorization jwks error: " << response.status_code() << " " << response.reason_phrase();
}
throw authorization_exception();
}, token);
}
// make an asynchronously GET request on the OpenID Connect Authorization API to fetch the client metdadata
pplx::task<web::json::value> request_client_metadata_from_openid_connect(web::http::client::http_client client, const nmos::api_version& version, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Requesting OpenID Connect client metadata at " << client.base_uri().to_string();
using namespace web::http;
return api_request(client, methods::GET, gate, token).then([=, &gate](pplx::task<http_response> response_task)
{
auto response = response_task.get(); // may throw http_exception
if (response.body())
{
return nmos::details::extract_json(response, gate).then([=, &gate](web::json::value body)
{
if (status_codes::OK == response.status_code())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Received OpenID Connect client metadata: " << utility::us2s(body.serialize());
// validate client metadata JSON
authapi_validator().validate(body, experimental::make_authapi_register_client_response_uri(version)); // may throw json_exception
return body;
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Requesting OpenID Connect client metadata error: " << response.status_code() << " " << response.reason_phrase() << " " << utility::us2s(body.serialize());
throw authorization_exception();
}
});
}
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Requesting OpenID Connect client metadata error: no response json: no client metadata";
throw authorization_exception();
}, token);
}
// make an asynchronously POST request on the Authorization API to fetch the bearer token,
// this is a helper function which is used by the request_token_from_client_credentials and request_token_from_refresh_token
// see https://medium.com/@software_factotum/pkce-public-clients-and-refresh-token-d1faa4ef6965#:~:text=Refresh%20Token%20are%20credentials%20that,application%20needs%20additional%20access%20tokens.&text=Authorization%20Server%20may%20issue%20a,Client%20it%20was%20issued%20to.
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token(web::http::client::http_client client, const nmos::api_version& version, web::uri_builder& request_body_ub, const utility::string_t& client_id, const utility::string_t& client_secret, const utility::string_t& scope, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token at " << client.base_uri().to_string();
using namespace web::http;
using oauth2::details::oauth2_strings;
using oauth2::experimental::oauth2_exception;
using oauth2::experimental::oauth2_token;
using web::http::details::mime_types;
if (!scope.empty())
{
request_body_ub.append_query(oauth2_strings::scope, uri::encode_data_string(scope), false);
}
http_request req(methods::POST);
if (client_secret.empty())
{
if (!client_id.empty())
{
// for Public Client or using private_key_jwt just append the client_id to query
request_body_ub.append_query(oauth2_strings::client_id, client_id, false);
}
}
else
{
// for Confidential Client and not using private_key_jwt
// Build HTTP Basic authorization header with 'client_id' and 'client_secret'
const std::string creds_utf8(utility::conversions::to_utf8string(uri::encode_data_string(client_id) + U(":") + uri::encode_data_string(client_secret)));
req.headers().add(header_names::authorization, U("Basic ") + utility::conversions::to_base64(std::vector<unsigned char>(creds_utf8.begin(), creds_utf8.end())));
}
req.set_body(request_body_ub.query(), mime_types::application_x_www_form_urlencoded);
return nmos::api_request(client, req, gate, token).then([=, &gate](pplx::task<http_response> response_task)
{
auto response = response_task.get(); // may throw http_exception
if (response.body())
{
return nmos::details::extract_json(response, gate).then([=, &gate](web::json::value body)
{
if (status_codes::OK == response.status_code())
{
#if defined (NDEBUG)
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Received bearer token";
#else
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Received bearer token: " << utility::us2s(body.serialize());
#endif
// validate bearer token JSON
authapi_validator().validate(body, experimental::make_authapi_token_response_schema_uri(version)); // may throw json_exception
return parse_token_from_json(body); // may throw oauth2_exception
}
else
{
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token error: " << response.status_code() << " " << utility::us2s(body.serialize());
// validate token error response JSON
authapi_validator().validate(body, experimental::make_authapi_token_error_response_uri(version)); // may throw json_exception
throw authorization_exception();
}
});
}
slog::log<slog::severities::error>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token error: no response json: no bearer token";
throw authorization_exception();
}, token);
}
// make an asynchronously POST request on the Authorization API to fetch the bearer token using client_credentials grant
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_client_credentials(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& client_secret, const utility::string_t& scope, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token using client_credentials grant at " << client.base_uri().to_string();
using web::http::oauth2::details::oauth2_strings;
web::uri_builder ub;
ub.append_query(oauth2_strings::grant_type, U("client_credentials"), false);
return request_token(client, version, ub, client_id, client_secret, scope, gate, token);
}
// make an asynchronously POST request on the Authorization API to fetch the bearer token using client_credentials grant with private_key_jwt for client authentication
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_client_credentials_using_private_key_jwt(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& scope, const utility::string_t& client_assertion, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token using client_credentials grant with private_key_jwt at " << client.base_uri().to_string();
using web::http::oauth2::details::oauth2_strings;
web::uri_builder ub;
ub.append_query(oauth2_strings::grant_type, U("client_credentials"), false);
// use private_key_jwt client authentication
// see https://tools.ietf.org/html/rfc7523#section-2.2
ub.append_query(U("client_assertion_type"), U("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), false);
ub.append_query(U("client_assertion"), client_assertion, false);
return request_token(client, version, ub, client_id, {}, scope, gate, token);
}
web::uri_builder make_request_token_base_query(const utility::string_t& code, const utility::string_t& redirect_uri, const utility::string_t& code_verifier)
{
using web::http::oauth2::details::oauth2_strings;
web::uri_builder ub;
ub.append_query(oauth2_strings::grant_type, oauth2_strings::authorization_code, false);
ub.append_query(oauth2_strings::code, web::uri::encode_data_string(code), false);
ub.append_query(oauth2_strings::redirect_uri, web::uri::encode_data_string(redirect_uri), false);
ub.append_query(U("code_verifier"), code_verifier, false);
return ub;
}
// make an asynchronously POST request on the Authorization API to exchange authorization code for bearer token
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_authorization_code(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& client_secret, const utility::string_t& scope, const utility::string_t& code, const utility::string_t& redirect_uri, const utility::string_t& code_verifier, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Exchanging authorization code: " << utility::us2s(code) << " for bearer token with code_verifier: " << utility::us2s(code_verifier) << " at " << client.base_uri().to_string();
auto ub = make_request_token_base_query(code, redirect_uri, code_verifier);
return request_token(client, version, ub, client_id, client_secret, scope, gate, token);
}
// make an asynchronously POST request on the Authorization API to exchange authorization code for bearer token with private_key_jwt for client authentication
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_authorization_code_with_private_key_jwt(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& scope, const utility::string_t& code, const utility::string_t& redirect_uri, const utility::string_t& code_verifier, const utility::string_t& client_assertion, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::too_much_info>(gate, SLOG_FLF) << "Exchanging authorization code: " << utility::us2s(code) << " for bearer token with private_key_jwt and code_verifier: " << utility::us2s(code_verifier) << " and client_assertion: " << utility::us2s(client_assertion) << " at " << client.base_uri().to_string();
auto ub = make_request_token_base_query(code, redirect_uri, code_verifier);
// use private_key_jwt client authentication
// see https://tools.ietf.org/html/rfc7523#section-2.2
ub.append_query(U("client_assertion_type"), U("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), false);
ub.append_query(U("client_assertion"), client_assertion, false);
return request_token(client, version, ub, client_id, {}, scope, gate, token);
}
web::uri_builder make_request_token_base_query(const utility::string_t& refresh_token)
{
using web::http::oauth2::details::oauth2_strings;
web::uri_builder ub;
ub.append_query(oauth2_strings::grant_type, oauth2_strings::refresh_token, false);
ub.append_query(oauth2_strings::refresh_token, web::uri::encode_data_string(refresh_token), false);
return ub;
}
// make an asynchronously POST request on the Authorization API to fetch the bearer token using refresh_token grant
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_refresh_token(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& client_secret, const utility::string_t& scope, const utility::string_t& refresh_token, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token using refresh_token grant at " << client.base_uri().to_string();
auto ub = make_request_token_base_query(refresh_token);
return request_token(client, version, ub, client_id, client_secret, scope, gate, token);
}
// make an asynchronously POST request on the Authorization API to fetch the bearer token using refresh_token grant with private_key_jwt for client authentication
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_refresh_token_using_private_key_jwt(web::http::client::http_client client, const nmos::api_version& version, const utility::string_t& client_id, const utility::string_t& scope, const utility::string_t& refresh_token, const utility::string_t& client_assertion, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
slog::log<slog::severities::info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token using refresh_token grant with private_key_jwt at " << client.base_uri().to_string();
using web::http::oauth2::details::oauth2_strings;
auto ub = make_request_token_base_query(refresh_token);
// use private_key_jwt client authentication
// see https://tools.ietf.org/html/rfc7523#section-2.2
ub.append_query(U("client_assertion_type"), U("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"), false);
ub.append_query(U("client_assertion"), client_assertion, false);
return request_token(client, version, ub, client_id, {}, scope, gate, token);
}
// verify the redirect URI and make an asynchronously POST request on the Authorization API to exchange authorization code for bearer token with private_key_jwt for client authentication
// this function is based on the oauth2_config::token_from_redirected_uri
pplx::task<web::http::oauth2::experimental::oauth2_token> request_token_from_redirected_uri(web::http::client::http_client client, const nmos::api_version& version, const web::uri& redirected_uri, const utility::string_t& response_type, const utility::string_t& client_id, const utility::string_t& client_secret, const utility::string_t& scope, const utility::string_t& redirect_uri, const utility::string_t& state, const utility::string_t& code_verifier, const web::http::oauth2::experimental::token_endpoint_auth_method& token_endpoint_auth_method, const utility::string_t& client_assertion, slog::base_gate& gate, const pplx::cancellation_token& token)
{
using web::http::oauth2::experimental::oauth2_exception;
using web::http::oauth2::details::oauth2_strings;
namespace response_types = web::http::oauth2::experimental::response_types;
std::map<utility::string_t, utility::string_t> query;
// for Authorization Code Grant Type Response (response_type = code)
// "If the resource owner grants the access request, the authorization
// server issues an authorization codeand delivers it to the client by
// adding the following parameters to the query component of the
// redirection URI using the "application/x-www-form-urlencoded" format
//
// For example, the authorization server redirects the user-agent by
// sending the following HTTP response :
// HTTP / 1.1 302 Found
// Location : https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA&state=xyz
// see https://tools.ietf.org/html/rfc6749#section-4.1.2
if (response_type == response_types::code.name)
{
query = web::uri::split_query(redirected_uri.query());
}
// for Implicit Grant Type Response (response_type = token)
// "If the resource owner grants the access request, the authorization
// server issues an access tokenand delivers it to the client by adding
// the following parameters to the fragment component of the redirection
// URI using the "application/x-www-form-urlencoded" format"
//
// For example, the authorization server redirects the user-agent by
// sending the following HTTP response
// HTTP / 1.1 302 Found
// Location : http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600
else if (response_type == response_types::token.name)
{
query = web::uri::split_query(redirected_uri.fragment());
}
else
{
throw oauth2_exception(U("response_type: '") + response_type + U("' is not supported"));
}
auto state_param = query.find(oauth2_strings::state);
if (state_param == query.end())
{
throw oauth2_exception(U("parameter 'state' missing from redirected URI"));
}
if (state != state_param->second)
{
throw oauth2_exception(U("parameter 'state': '") + state_param->second + U("' does not match with the expected 'state': '") + state + U("'"));
}
// for Authorization Code Grant Type Response (response_type = code)
// do request_token_from_authorization_code
if (response_type == response_types::code.name)
{
auto code_param = query.find(oauth2_strings::code);
if (code_param == query.end())
{
throw oauth2_exception(U("parameter 'code' missing from redirected URI"));
}
if (web::http::oauth2::experimental::token_endpoint_auth_methods::private_key_jwt == token_endpoint_auth_method)
{
return request_token_from_authorization_code_with_private_key_jwt(client, version, client_id, scope, code_param->second, redirect_uri, code_verifier, client_assertion, gate, token);
}
else if (web::http::oauth2::experimental::token_endpoint_auth_methods::client_secret_basic == token_endpoint_auth_method)
{
return request_token_from_authorization_code(client, version, client_id, client_secret, scope, code_param->second, redirect_uri, code_verifier, gate, token);
}
else
{
throw oauth2_exception(U("token_endpoint_auth_method: '") + token_endpoint_auth_method.name + U("' is not curently supported"));
}
}
// for Implicit Grant Type Response (response_type = token)
// extract access token from query parameters
auto token_type_param = query.find(oauth2_strings::token_type);
if (token_type_param == query.end())
{
throw oauth2_exception(U("parameter 'token_type' missing from redirected URI"));
}
if (boost::algorithm::to_lower_copy(token_type_param->second) != U("bearer"))
{
throw oauth2_exception(U("invalid parameter 'token_type': '") + token_type_param->second + U("', expecting 'bearer'"));
}
auto token_param = query.find(oauth2_strings::access_token);
if (token_param == query.end())
{
throw oauth2_exception(U("parameter 'access_token' missing from redirected URI"));
}
return pplx::task_from_result(web::http::oauth2::experimental::oauth2_token(token_param->second));
}
struct token_shared_state
{
web::http::oauth2::experimental::grant_type grant_type;
web::http::oauth2::experimental::oauth2_token bearer_token;
std::unique_ptr<web::http::client::http_client> client;
nmos::api_version version; // issuer version
load_rsa_private_keys_handler load_rsa_private_keys;
bool immediate; // true = do an immediate fetch; false = loop based on time interval
explicit token_shared_state(web::http::oauth2::experimental::grant_type grant_type, web::http::oauth2::experimental::oauth2_token bearer_token, web::http::client::http_client client, nmos::api_version version, load_rsa_private_keys_handler load_rsa_private_keys, bool immediate)
: grant_type(std::move(grant_type))
, bearer_token(std::move(bearer_token))
, client(std::unique_ptr<web::http::client::http_client>(new web::http::client::http_client(client)))
, version(std::move(version))
, load_rsa_private_keys(std::move(load_rsa_private_keys))
, immediate(immediate) {}
};
// task to continuously fetch the bearer token on a time interval until failure or cancellation
pplx::task<void> do_token_requests(nmos::base_model& model, nmos::experimental::authorization_state& authorization_state, token_shared_state& token_state, bool& authorization_service_error, slog::base_gate& gate, const pplx::cancellation_token& token = pplx::cancellation_token::none())
{
const auto access_token_refresh_interval = nmos::experimental::fields::access_token_refresh_interval(model.settings);
const auto authorization_server_metadata = nmos::experimental::get_authorization_server_metadata(authorization_state);
const auto client_metadata = nmos::experimental::get_client_metadata(authorization_state);
const auto client_id = nmos::experimental::fields::client_id(client_metadata);
const auto client_secret = client_metadata.has_string_field(nmos::experimental::fields::client_secret) ? nmos::experimental::fields::client_secret(client_metadata) : U("");
const auto scope = nmos::experimental::fields::scope(client_metadata);
const auto token_endpoint_auth_method = client_metadata.has_string_field(nmos::experimental::fields::token_endpoint_auth_method) ?
web::http::oauth2::experimental::to_token_endpoint_auth_method(nmos::experimental::fields::token_endpoint_auth_method(client_metadata)) : web::http::oauth2::experimental::token_endpoint_auth_methods::client_secret_basic;
const auto token_endpoint = nmos::experimental::fields::token_endpoint(authorization_server_metadata);
const auto client_assertion_lifespan = std::chrono::seconds(nmos::experimental::fields::authorization_request_max(model.settings));
// start a background task for continuous fetching bearer token in a time interval
return pplx::do_while([=, &model, &authorization_state, &token_state, &gate]
{
auto fetch_interval = std::chrono::seconds(0);
if (!token_state.immediate && token_state.bearer_token.is_valid_access_token())
{
// RECOMMENDED to attempt a refresh at least 15 seconds before expiry (i.e the half-life of the shortest-lived token possible)
// see https://specs.amwa.tv/is-10/releases/v1.0.0/docs/4.2._Behaviour_-_Clients.html#refreshing-a-token
fetch_interval = access_token_refresh_interval < 0 ? std::chrono::seconds(token_state.bearer_token.expires_in() / 2) : std::chrono::seconds(access_token_refresh_interval);
}
token_state.immediate = false;
slog::log<slog::severities::more_info>(gate, SLOG_FLF) << "Requesting '" << utility::us2s(scope) << "' bearer token for about " << fetch_interval.count() << " seconds";
auto fetch_time = std::chrono::steady_clock::now();
return pplx::complete_at(fetch_time + fetch_interval, token).then([=, &model, &token_state, &gate]()
{
// create client assertion using private key jwt
utility::string_t client_assertion;
with_read_lock(model.mutex, [&]
{
if (web::http::oauth2::experimental::token_endpoint_auth_methods::private_key_jwt == token_endpoint_auth_method)
{
// use the 1st RSA private key from RSA private keys list to create the client_assertion
if (!token_state.load_rsa_private_keys)
{
throw web::http::oauth2::experimental::oauth2_exception(U("missing RSA private key loader to extract RSA private key"));
}
auto rsa_private_keys = token_state.load_rsa_private_keys();
if (rsa_private_keys.empty() || rsa_private_keys[0].empty())
{
throw web::http::oauth2::experimental::oauth2_exception(U("no RSA key to create client assertion"));
}
client_assertion = jwt_generator::create_client_assertion(client_id, client_id, token_endpoint, client_assertion_lifespan, rsa_private_keys[0], U("1"));
}
});
if (web::http::oauth2::experimental::grant_types::authorization_code == token_state.grant_type)
{
if (web::http::oauth2::experimental::token_endpoint_auth_methods::private_key_jwt == token_endpoint_auth_method)
{
return request_token_from_refresh_token_using_private_key_jwt(*token_state.client, token_state.version, client_id, scope, token_state.bearer_token.refresh_token(), client_assertion, gate, token);
}
else
{
return request_token_from_refresh_token(*token_state.client, token_state.version, client_id, client_secret, scope, token_state.bearer_token.refresh_token(), gate, token);
}
}
else if (web::http::oauth2::experimental::grant_types::client_credentials == token_state.grant_type)
{
if (web::http::oauth2::experimental::token_endpoint_auth_methods::private_key_jwt == token_endpoint_auth_method)
{
return request_token_from_client_credentials_using_private_key_jwt(*token_state.client, token_state.version, client_id, scope, client_assertion, gate, token);
}
else
{
return request_token_from_client_credentials(*token_state.client, token_state.version, client_id, client_secret, scope, gate, token);
}
}
else
{
throw web::http::oauth2::experimental::oauth2_exception(U("Unsupported grant: ") + token_state.grant_type.name);
}
}).then([=, &authorization_state, &token_state, &gate](const web::http::oauth2::experimental::oauth2_token& bearer_token)
{
token_state.bearer_token = bearer_token;
// update token in authorization settings
auto lock = authorization_state.write_lock();
authorization_state.bearer_token = token_state.bearer_token;
slog::log<slog::severities::info>(gate, SLOG_FLF) << "'" << utility::us2s(scope) << "' bearer token updated";
return true;
});
}).then([&](pplx::task<void> finally)
{
auto lock = model.write_lock(); // in order to update local state
try
{
finally.get();
}
catch (const web::http::http_exception& e)