-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathoidcc_token.erl
1230 lines (1098 loc) · 43 KB
/
oidcc_token.erl
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
-module(oidcc_token).
-feature(maybe_expr, enable).
-include("internal/doc.hrl").
?MODULEDOC("""
Facilitate OpenID Code/Token Exchanges.
## Records
To use the records, import the definition:
```erlang
-include_lib(["oidcc/include/oidcc_token.hrl"]).
```
## Telemetry
See [`Oidcc.Token`](`m:'Elixir.Oidcc.Token'`).
""").
?MODULEDOC(#{since => <<"3.0.0">>}).
-include("oidcc_client_context.hrl").
-include("oidcc_provider_configuration.hrl").
-include("oidcc_token.hrl").
-include_lib("jose/include/jose_jwe.hrl").
-include_lib("jose/include/jose_jwk.hrl").
-include_lib("jose/include/jose_jws.hrl").
-include_lib("jose/include/jose_jwt.hrl").
-export([client_credentials/2]).
-export([jwt_profile/4]).
-export([refresh/3]).
-export([retrieve/3]).
-export([validate_jarm/3]).
-export([validate_id_token/3]).
-export([validate_jwt/3]).
-export([authorization_headers/4]).
-export([authorization_headers/5]).
-export_type([access/0]).
-export_type([authorization_headers_opts/0]).
-export_type([client_credentials_opts/0]).
-export_type([error/0]).
-export_type([id/0]).
-export_type([jwt_profile_opts/0]).
-export_type([refresh/0]).
-export_type([refresh_opts/0]).
-export_type([refresh_opts_no_sub/0]).
-export_type([retrieve_opts/0]).
-export_type([validate_jarm_opts/0]).
-export_type([validate_jwt_opts/0]).
-export_type([t/0]).
?DOC("""
ID Token Wrapper.
## Fields
* `token` - The retrieved token.
* `claims` - Unpacked claims of the verified token.
""").
?DOC(#{since => <<"3.0.0">>}).
-type id() :: #oidcc_token_id{token :: binary(), claims :: oidcc_jwt_util:claims()}.
?DOC("""
Access Token Wrapper.
## Fields
* `token` - The retrieved token.
* `expires` - Number of seconds the token is valid.
""").
?DOC(#{since => <<"3.0.0">>}).
-type access() ::
#oidcc_token_access{token :: binary(), expires :: pos_integer() | undefined, type :: binary()}.
?DOC("""
Refresh Token Wrapper.
## Fields
* `token` - The retrieved token.
""").
?DOC(#{since => <<"3.0.0">>}).
-type refresh() :: #oidcc_token_refresh{token :: binary()}.
?DOC("""
Token Response Wrapper.
## Fields
* `id` - `t:id/0`.
* `access` - `t:access/0`.
* `refresh` - `t:refresh/0`.
* `scope` - `t:oidcc_scope:scopes/0`.
""").
?DOC(#{since => <<"3.0.0">>}).
-type t() ::
#oidcc_token{
id :: oidcc_token:id() | none,
access :: oidcc_token:access() | none,
refresh :: oidcc_token:refresh() | none,
scope :: oidcc_scope:scopes()
}.
?DOC("""
Options for retrieving a token.
See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3.
## Fields
* `pkce_verifier` - PKCE verifier (random string previously given to
`m:oidcc_authorization`), see
https://datatracker.ietf.org/doc/html/rfc7636#section-4.1.
* `require_pkce` - whether to require PKCE when getting the token.
* `nonce` - Nonce to check.
* `scope` - Scope to store with the token.
* `refresh_jwks` - How to handle tokens with an unknown `kid`.
See `t:oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun/0`.
* `redirect_uri` - Redirect URI given to `oidcc_authorization:create_redirect_url/2`.
* `dpop_nonce` - if using DPoP, the `nonce` value to use in the proof claim.
* `trusted_audiences` - if present, a list of additional audience values to
accept. Defaults to `any` which allows any additional values.
""").
?DOC(#{since => <<"3.0.0">>}).
-type retrieve_opts() ::
#{
pkce_verifier => binary(),
require_pkce => boolean(),
nonce => binary() | any,
scope => oidcc_scope:scopes(),
preferred_auth_methods => [oidcc_auth_util:auth_method(), ...],
refresh_jwks => oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun(),
redirect_uri => uri_string:uri_string(),
request_opts => oidcc_http_util:request_opts(),
url_extension => oidcc_http_util:query_params(),
body_extension => oidcc_http_util:query_params(),
dpop_nonce => binary(),
trusted_audiences => [binary()] | any
}.
?DOC("See `t:refresh_opts_no_sub/0`.").
?DOC(#{since => <<"3.0.0">>}).
-type refresh_opts_no_sub() ::
#{
scope => oidcc_scope:scopes(),
refresh_jwks => oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun(),
request_opts => oidcc_http_util:request_opts(),
url_extension => oidcc_http_util:query_params(),
body_extension => oidcc_http_util:query_params()
}.
?DOC(#{since => <<"3.0.0">>}).
-type refresh_opts() ::
#{
scope => oidcc_scope:scopes(),
refresh_jwks => oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun(),
expected_subject := binary(),
request_opts => oidcc_http_util:request_opts(),
url_extension => oidcc_http_util:query_params(),
body_extension => oidcc_http_util:query_params()
}.
?DOC("""
Options for refreshing a token.
See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.3.
## Fields
* `scope` - Scope to store with the token.
* `refresh_jwks` - How to handle tokens with an unknown `kid`.
See `t:oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun/0`.
* `expected_subject` - `sub` of the original token.
""").
?DOC(#{since => <<"3.2.0">>}).
-type validate_jarm_opts() ::
#{
trusted_audiences => [binary()] | any
}.
?DOC(#{since => <<"3.0.0">>}).
-type jwt_profile_opts() :: #{
scope => oidcc_scope:scopes(),
refresh_jwks => oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun(),
request_opts => oidcc_http_util:request_opts(),
kid => binary(),
url_extension => oidcc_http_util:query_params(),
body_extension => oidcc_http_util:query_params()
}.
?DOC(#{since => <<"3.0.0">>}).
-type client_credentials_opts() :: #{
scope => oidcc_scope:scopes(),
refresh_jwks => oidcc_jwt_util:refresh_jwks_for_unknown_kid_fun(),
request_opts => oidcc_http_util:request_opts(),
url_extension => oidcc_http_util:query_params(),
body_extension => oidcc_http_util:query_params()
}.
?DOC(#{since => <<"3.0.0">>}).
-type authorization_headers_opts() :: #{
dpop_nonce => binary()
}.
?DOC(#{since => <<"3.2.0">>}).
-type validate_jwt_opts() ::
#{
signing_algs => [binary()] | undefined,
encryption_algs => [binary()] | undefined,
encryption_encs => [binary()] | undefined
}.
?DOC(#{since => <<"3.0.0">>}).
-type error() ::
{missing_claim, MissingClaim :: binary(), Claims :: oidcc_jwt_util:claims()}
| pkce_verifier_required
| no_supported_auth_method
| bad_access_token_hash
| sub_invalid
| token_expired
| token_not_yet_valid
| {none_alg_used, Token :: t()}
| {missing_claim, ExpClaim :: {binary(), term()}, Claims :: oidcc_jwt_util:claims()}
| {grant_type_not_supported,
authorization_code | refresh_token | jwt_bearer | client_credentials}
| {invalid_property, {
Field :: id_token | refresh_token | access_token | expires_in | scopes, GivenValue :: term()
}}
| oidcc_jwt_util:error()
| oidcc_http_util:error().
-telemetry_event(#{
event => [oidcc, request_token, start],
description => <<"Emitted at the start of requesting a code token">>,
measurements => <<"#{system_time => non_neg_integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, request_token, stop],
description => <<"Emitted at the end of requesting a code token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, request_token, exception],
description => <<"Emitted at the end of requesting a code token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, refresh_token, start],
description => <<"Emitted at the start of refreshing a token">>,
measurements => <<"#{system_time => non_neg_integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, refresh_token, stop],
description => <<"Emitted at the end of refreshing a token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, refresh_token, exception],
description => <<"Emitted at the end of refreshing a token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, jwt_profile_token, start],
description => <<"Emitted at the start of exchanging a JWT profile token">>,
measurements => <<"#{system_time => non_neg_integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, jwt_profile_token, stop],
description => <<"Emitted at the end of exchanging a JWT profile token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, jwt_profile_token, exception],
description => <<"Emitted at the end of exchanging a JWT profile token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, client_credentials, start],
description => <<"Emitted at the start of exchanging a client credentials token">>,
measurements => <<"#{system_time => non_neg_integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, client_credentials, stop],
description => <<"Emitted at the end of exchanging a client credentials token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
-telemetry_event(#{
event => [oidcc, client_credentials, exception],
description => <<"Emitted at the end of exchanging a client credentials token">>,
measurements => <<"#{duration => integer(), monotonic_time => integer()}">>,
metadata => <<"#{issuer => uri_string:uri_string(), client_id => binary()}">>
}).
?DOC("""
Retrieve the token using the authcode received before and directly validate
the result.
The authcode was sent to the local endpoint by the OpenId Connect provider,
using redirects.
For a high level interface using `m:oidcc_provider_configuration_worker`
see `oidcc:retrieve_token/5`.
## Examples
```erlang
{ok, ClientContext} =
oidcc_client_context:from_configuration_worker(provider_name,
<<"client_id">>,
<<"client_secret">>),
%% Get AuthCode from Redirect
{ok, #oidcc_token{}} =
oidcc:retrieve(AuthCode, ClientContext, #{
redirect_uri => <<"https://example.com/callback">>}).
```
""").
?DOC(#{since => <<"3.0.0">>}).
-spec retrieve(AuthCode, ClientContext, Opts) ->
{ok, t()} | {error, error()}
when
AuthCode :: binary(),
ClientContext :: oidcc_client_context:t(),
Opts :: retrieve_opts().
retrieve(AuthCode, ClientContext, Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
client_id = ClientId
} = ClientContext,
#oidcc_provider_configuration{issuer = Issuer, grant_types_supported = GrantTypesSupported} =
Configuration,
case lists:member(<<"authorization_code">>, GrantTypesSupported) of
true ->
PkceVerifier = maps:get(pkce_verifier, Opts, none),
QsBody =
[
{<<"grant_type">>, <<"authorization_code">>},
{<<"code">>, AuthCode},
{<<"redirect_uri">>, maps:get(redirect_uri, Opts)}
],
TelemetryOpts = #{
topic => [oidcc, request_token],
extra_meta => #{issuer => Issuer, client_id => ClientId}
},
maybe
{ok, Token} ?=
retrieve_a_token(
QsBody, PkceVerifier, ClientContext, Opts, TelemetryOpts, true
),
extract_response(Token, ClientContext, Opts)
end;
false ->
{error, {grant_type_not_supported, authorization_code}}
end.
?DOC("""
Validate the JARM response, returning the valid claims as a map.
The response was sent to the local endpoint by the OpenId Connect provider,
using redirects.
## Examples
```erlang
{ok, ClientContext} =
oidcc_client_context:from_configuration_worker(provider_name,
<<"client_id">>,
<<"client_secret">>),
%% Get Response from Redirect
{ok, #{<<"code">> := AuthCode}} =
oidcc:validate_jarm(Response, ClientContext, #{}),
{ok, #oidcc_token{}} = oidcc:retrieve(AuthCode, ClientContext,
#{redirect_uri => <<"https://redirect.example/">>}).
```
""").
?DOC(#{since => <<"3.2.0">>}).
-spec validate_jarm(Response, ClientContext, Opts) ->
{ok, oidcc_jwt_util:claims()} | {error, error()}
when
Response :: binary(),
ClientContext :: oidcc_client_context:t(),
Opts :: validate_jarm_opts().
validate_jarm(Response, ClientContext, Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
client_id = ClientId,
client_secret = ClientSecret,
client_jwks = ClientJwks,
jwks = Jwks0
} = ClientContext,
#oidcc_provider_configuration{
issuer = Issuer,
authorization_signing_alg_values_supported = SigningAlgSupported,
authorization_encryption_alg_values_supported = EncryptionAlgSupported,
authorization_encryption_enc_values_supported = EncryptionEncSupported
} =
Configuration,
Jwks1 =
case ClientJwks of
none -> Jwks0;
#jose_jwk{} -> oidcc_jwt_util:merge_jwks(Jwks0, ClientJwks)
end,
Jwks2 = oidcc_jwt_util:merge_client_secret_oct_keys(Jwks1, SigningAlgSupported, ClientSecret),
Jwks = oidcc_jwt_util:merge_client_secret_oct_keys(
Jwks2, EncryptionAlgSupported, ClientSecret
),
ExpClaims = [{<<"iss">>, Issuer}],
TrustedAudience = maps:get(trusted_audiences, Opts, any),
%% https://openid.net/specs/oauth-v2-jarm-final.html#name-processing-rules
%% 1. decrypt if necessary
%% 2. validate <<"iss">> claim
%% 3. validate <<"aud">> claim
%% 4. validate <<"exp">> claim
%% 5. validate signature (valid, not <<"none">> alg)
%% 6. continue processing
maybe
{ok, {#jose_jwt{fields = Claims}, Jws}} ?=
oidcc_jwt_util:decrypt_and_verify(
Response, Jwks, SigningAlgSupported, EncryptionAlgSupported, EncryptionEncSupported
),
ok ?= oidcc_jwt_util:verify_claims(Claims, ExpClaims),
ok ?= verify_aud_claim(Claims, ClientId, TrustedAudience),
ok ?= verify_exp_claim(Claims),
ok ?= verify_nbf_claim(Claims),
ok ?= oidcc_jwt_util:verify_not_none_alg(Jws),
{ok, Claims}
end.
?DOC("""
Refresh Token
For a high level interface using `m:oidcc_provider_configuration_worker`
see `oidcc:refresh_token/5`.
## Examples
```erlang
{ok, ClientContext} =
oidcc_client_context:from_configuration_worker(provider_name,
<<"client_id">>,
<<"client_secret">>),
%% Get AuthCode from Redirect
{ok, Token} =
oidcc_token:retrieve(AuthCode, ClientContext, #{
redirect_uri => <<"https://example.com/callback">>}).
%% Later
{ok, #oidcc_token{}} =
oidcc_token:refresh(Token,
ClientContext,
#{expected_subject => <<"sub_from_initial_id_token">>}).
```
""").
?DOC(#{since => <<"3.0.0">>}).
-spec refresh
(RefreshToken, ClientContext, Opts) ->
{ok, t()} | {error, error()}
when
RefreshToken :: binary(),
ClientContext :: oidcc_client_context:t(),
Opts :: refresh_opts();
(Token, ClientContext, Opts) ->
{ok, t()} | {error, error()}
when
Token :: oidcc_token:t(),
ClientContext :: oidcc_client_context:t(),
Opts :: refresh_opts_no_sub().
refresh(
#oidcc_token{
refresh = #oidcc_token_refresh{token = RefreshToken},
id = #oidcc_token_id{claims = #{<<"sub">> := ExpectedSubject}}
},
ClientContext,
Opts
) ->
refresh(RefreshToken, ClientContext, maps:put(expected_subject, ExpectedSubject, Opts));
refresh(RefreshToken, ClientContext, Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
client_id = ClientId
} = ClientContext,
#oidcc_provider_configuration{issuer = Issuer, grant_types_supported = GrantTypesSupported} =
Configuration,
case lists:member(<<"refresh_token">>, GrantTypesSupported) of
true ->
ExpectedSub = maps:get(expected_subject, Opts),
Scope = maps:get(scope, Opts, []),
QueryString =
[{<<"refresh_token">>, RefreshToken}, {<<"grant_type">>, <<"refresh_token">>}],
QueryString1 = oidcc_scope:query_append_scope(Scope, QueryString),
TelemetryOpts = #{
topic => [oidcc, refresh_token],
extra_meta => #{issuer => Issuer, client_id => ClientId}
},
maybe
{ok, Token} ?=
retrieve_a_token(QueryString1, none, ClientContext, Opts, TelemetryOpts, true),
{ok, TokenRecord} ?=
extract_response(Token, ClientContext, maps:put(nonce, any, Opts)),
case TokenRecord of
#oidcc_token{id = #oidcc_token_id{claims = #{<<"sub">> := ExpectedSub}}} ->
{ok, TokenRecord};
#oidcc_token{} ->
{error, sub_invalid}
end
end;
false ->
{error, {grant_type_not_supported, refresh_token}}
end.
?DOC("""
Retrieve JSON Web Token (JWT) Profile Token
See [https://datatracker.ietf.org/doc/html/rfc7523#section-4]
For a high level interface using {@link oidcc_provider_configuration_worker}
see {@link oidcc:jwt_profile_token/6}.
## Examples
```erlang
{ok, ClientContext} =
oidcc_client_context:from_configuration_worker(provider_name,
<<"client_id">>,
<<"client_secret">>),
{ok, KeyJson} = file:read_file("jwt-profile.json"),
KeyMap = jose:decode(KeyJson),
Key = jose_jwk:from_pem(maps:get(<<"key">>, KeyMap)),
{ok, #oidcc_token{}} =
oidcc_token:jwt_profile(<<"subject">>,
ClientContext,
Key,
#{scope => [<<"scope">>],
kid => maps:get(<<"keyId">>, KeyMap)}).
```
""").
?DOC(#{since => <<"3.0.0">>}).
-spec jwt_profile(Subject, ClientContext, Jwk, Opts) -> {ok, t()} | {error, error()} when
Subject :: binary(),
ClientContext :: oidcc_client_context:t(),
Jwk :: jose_jwk:key(),
Opts :: jwt_profile_opts().
jwt_profile(Subject, ClientContext, Jwk, Opts) ->
#oidcc_client_context{provider_configuration = Configuration, client_id = ClientId} =
ClientContext,
#oidcc_provider_configuration{issuer = Issuer, grant_types_supported = GrantTypesSupported} =
Configuration,
case lists:member(<<"urn:ietf:params:oauth:grant-type:jwt-bearer">>, GrantTypesSupported) of
true ->
Iat = os:system_time(seconds),
Exp = Iat + 60,
AssertionClaims = #{
<<"iss">> => Subject,
<<"sub">> => Subject,
<<"aud">> => [Issuer],
<<"exp">> => Exp,
<<"iat">> => Iat,
<<"nbf">> => Iat
},
AssertionJwt = jose_jwt:from(AssertionClaims),
AssertionJws0 = #{
<<"alg">> => <<"RS256">>,
<<"typ">> => <<"JWT">>
},
AssertionJws =
case maps:get(kid, Opts, none) of
none -> AssertionJws0;
Kid -> maps:put(<<"kid">>, Kid, AssertionJws0)
end,
{_Jws, Assertion} = jose_jws:compact(jose_jwt:sign(Jwk, AssertionJws, AssertionJwt)),
Scope = maps:get(scope, Opts, []),
QueryString =
[
{<<"assertion">>, Assertion},
{<<"grant_type">>, <<"urn:ietf:params:oauth:grant-type:jwt-bearer">>}
],
QueryString1 = oidcc_scope:query_append_scope(Scope, QueryString),
TelemetryOpts = #{
topic => [oidcc, jwt_profile_token],
extra_meta => #{issuer => Issuer, client_id => ClientId}
},
maybe
{ok, Token} ?=
retrieve_a_token(QueryString1, none, ClientContext, Opts, TelemetryOpts, false),
{ok, TokenRecord} ?=
extract_response(Token, ClientContext, maps:put(nonce, any, Opts)),
case TokenRecord of
#oidcc_token{id = none} ->
{ok, TokenRecord};
#oidcc_token{id = #oidcc_token_id{claims = #{<<"sub">> := Subject}}} ->
{ok, TokenRecord};
#oidcc_token{} ->
{error, sub_invalid}
end
end;
false ->
{error, {grant_type_not_supported, jwt_bearer}}
end.
%% @doc Retrieve Client Credential Token
%%
%% See [https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.4]
%%
%% For a high level interface using {@link oidcc_provider_configuration_worker}
%% see {@link oidcc:client_credentials_token/4}.
%%
%% <h2>Examples</h2>
%%
%% ```
%% {ok, ClientContext} =
%% oidcc_client_context:from_configuration_worker(provider_name,
%% <<"client_id">>,
%% <<"client_secret">>),
%%
%% {ok, #oidcc_token{}} =
%% oidcc_token:client_credentials(ClientContext,
%% #{scope => [<<"scope">>]}).
%% '''
%% @end
%% @since 3.0.0
-spec client_credentials(ClientContext, Opts) -> {ok, t()} | {error, error()} when
ClientContext :: oidcc_client_context:authenticated_t(),
Opts :: client_credentials_opts().
client_credentials(ClientContext, Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
client_id = ClientId
} = ClientContext,
#oidcc_provider_configuration{issuer = Issuer, grant_types_supported = GrantTypesSupported} =
Configuration,
case lists:member(<<"client_credentials">>, GrantTypesSupported) of
true ->
Scope = maps:get(scope, Opts, []),
QueryString = [{<<"grant_type">>, <<"client_credentials">>}],
QueryString1 = oidcc_scope:query_append_scope(Scope, QueryString),
TelemetryOpts = #{
topic => [oidcc, client_credentials],
extra_meta => #{issuer => Issuer, client_id => ClientId}
},
maybe
{ok, Token} ?=
retrieve_a_token(QueryString1, none, ClientContext, Opts, TelemetryOpts, true),
extract_response(Token, ClientContext, maps:put(nonce, any, Opts))
end;
false ->
{error, {grant_type_not_supported, client_credentials}}
end.
-spec extract_response(TokenResponseBody, ClientContext, Opts) ->
{ok, t()} | {error, error()}
when
TokenResponseBody :: map(),
ClientContext :: oidcc_client_context:t(),
Opts :: retrieve_opts().
extract_response(TokenResponseBody, ClientContext, Opts) ->
RefreshJwksFun = maps:get(refresh_jwks, Opts, undefined),
maybe
{ok, Token} ?= int_extract_response(TokenResponseBody, ClientContext, Opts),
{ok, Token}
else
{error, {no_matching_key_with_kid, Kid}} when RefreshJwksFun =/= undefined ->
#oidcc_client_context{jwks = OldJwks} = ClientContext,
maybe
{ok, RefreshedJwks} ?= RefreshJwksFun(OldJwks, Kid),
RefreshedClientContext = ClientContext#oidcc_client_context{jwks = RefreshedJwks},
int_extract_response(TokenResponseBody, RefreshedClientContext, Opts)
end;
{error, Reason} ->
{error, Reason}
end.
-spec int_extract_response(TokenMap, ClientContext, Opts) ->
{ok, t()} | {error, error()}
when
TokenMap :: map(),
ClientContext :: oidcc_client_context:t(),
Opts :: retrieve_opts().
int_extract_response(TokenMap, ClientContext, Opts) ->
maybe
{ok, Scopes} ?= extract_scope(TokenMap, Opts),
{ok, AccessExpire} ?= extract_expiry(TokenMap),
{ok, AccessTokenRecord} ?= extract_access_token(TokenMap, AccessExpire),
{ok, RefreshTokenRecord} ?= extract_refresh_token(TokenMap),
{ok, {IdTokenRecord, NoneUsed}} ?= extract_id_token(TokenMap, ClientContext, Opts),
TokenRecord = #oidcc_token{
id = IdTokenRecord,
access = AccessTokenRecord,
refresh = RefreshTokenRecord,
scope = Scopes
},
ok ?= verify_access_token_map_hash(TokenRecord),
%% If none alg was used, continue with checks to allow the user to decide
%% if he wants to use the result
case NoneUsed of
true ->
{error, {none_alg_used, TokenRecord}};
false ->
{ok, TokenRecord}
end
end.
-spec extract_scope(TokenMap, Opts) -> {ok, oidcc_scope:scopes()} | {error, error()} when
TokenMap :: map(), Opts :: retrieve_opts().
extract_scope(TokenMap, Opts) ->
Scopes = maps:get(scope, Opts, []),
case maps:get(<<"scope">>, TokenMap, oidcc_scope:scopes_to_bin(Scopes)) of
ScopeBinary when is_binary(ScopeBinary) ->
{ok, oidcc_scope:parse(ScopeBinary)};
ScopeOther ->
{error, {invalid_property, {scope, ScopeOther}}}
end.
-spec extract_expiry(TokenMap) -> {ok, undefined | integer()} | {error, error()} when
TokenMap :: map().
extract_expiry(TokenMap) ->
case maps:get(<<"expires_in">>, TokenMap, undefined) of
undefined ->
{ok, undefined};
ExpiresInNum when is_integer(ExpiresInNum) ->
{ok, ExpiresInNum};
ExpiresInBinary when is_binary(ExpiresInBinary) ->
try
{ok, binary_to_integer(ExpiresInBinary)}
catch
error:badarg ->
{error, {invalid_property, {expires_in, ExpiresInBinary}}}
end;
ExpiresInOther ->
{error, {invalid_property, {expires_in, ExpiresInOther}}}
end.
-spec extract_access_token(TokenMap, Expiry) -> {ok, access()} | {error, error()} when
TokenMap :: map(),
Expiry :: integer().
extract_access_token(TokenMap, Expiry) ->
case maps:get(<<"access_token">>, TokenMap, none) of
none ->
{ok, none};
Token when is_binary(Token) ->
TokenType = maps:get(<<"token_type">>, TokenMap, <<"Bearer">>),
{ok, #oidcc_token_access{token = Token, expires = Expiry, type = TokenType}};
Other ->
{error, {invalid_property, {access_token, Other}}}
end.
-spec extract_refresh_token(TokenMap) -> {ok, refresh()} | {error, error()} when
TokenMap :: map().
extract_refresh_token(TokenMap) ->
case maps:get(<<"refresh_token">>, TokenMap, none) of
none ->
{ok, none};
Token when is_binary(Token) ->
{ok, #oidcc_token_refresh{token = Token}};
Other ->
{error, {invalid_property, {refresh_token, Other}}}
end.
-spec extract_id_token(TokenMap, ClientContext, Opts) ->
{ok, {TokenRecord, NoneUsed}} | {error, error()}
when
TokenMap :: map(),
ClientContext :: oidcc_client_context:t(),
Opts :: retrieve_opts(),
TokenRecord :: id(),
NoneUsed :: boolean().
extract_id_token(TokenMap, ClientContext, Opts) ->
case maps:get(<<"id_token">>, TokenMap, none) of
none ->
{ok, {none, false}};
Token when is_binary(Token) ->
case validate_id_token(Token, ClientContext, Opts) of
{ok, OkClaims} ->
{ok, {#oidcc_token_id{token = Token, claims = OkClaims}, false}};
{error, {none_alg_used, NoneClaims}} ->
{ok, {#oidcc_token_id{token = Token, claims = NoneClaims}, true}};
{error, Reason} ->
{error, Reason}
end;
Other ->
{error, {invalid_property, {id_token, Other}}}
end.
-spec verify_access_token_map_hash(TokenRecord :: t()) ->
ok | {error, error()}.
verify_access_token_map_hash(#oidcc_token{
id =
#oidcc_token_id{
claims =
#{<<"at_hash">> := ExpectedHash}
},
access = #oidcc_token_access{token = AccessToken}
}) ->
<<BinHash:16/binary, _Rest/binary>> = crypto:hash(sha256, AccessToken),
case base64:encode(BinHash, #{mode => urlsafe, padding => false}) of
ExpectedHash ->
ok;
_Other ->
{error, bad_access_token_hash}
end;
verify_access_token_map_hash(#oidcc_token{}) ->
ok.
%% @doc Validate ID Token
%%
%% Usually the id token is validated using {@link retrieve/3}.
%% If you get the token passed from somewhere else, this function can validate it.
%%
%% <h2>Examples</h2>
%%
%% ```
%% {ok, ClientContext} =
%% oidcc_client_context:from_configuration_worker(provider_name,
%% <<"client_id">>,
%% <<"client_secret">>),
%%
%% %% Get IdToken from somewhere
%%
%% {ok, Claims} =
%% oidcc:validate_id_token(IdToken, ClientContext, ExpectedNonce).
%% '''
%% @end
%% @since 3.0.0
-spec validate_id_token(IdToken, ClientContext, NonceOrOpts) ->
{ok, Claims} | {error, error()}
when
IdToken :: binary(),
ClientContext :: oidcc_client_context:t(),
NonceOrOpts :: Nonce | retrieve_opts(),
Nonce :: binary() | any,
Claims :: oidcc_jwt_util:claims().
validate_id_token(IdToken, ClientContext, Nonce) when is_binary(Nonce) ->
validate_id_token(IdToken, ClientContext, #{nonce => Nonce});
validate_id_token(IdToken, ClientContext, any) ->
validate_id_token(IdToken, ClientContext, #{nonce => any});
validate_id_token(IdToken, ClientContext, Opts) when is_map(Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
jwks = #jose_jwk{} = Jwks0,
client_id = ClientId,
client_secret = ClientSecret,
client_jwks = ClientJwks
} =
ClientContext,
#oidcc_provider_configuration{
id_token_signing_alg_values_supported = AllowAlgorithms,
id_token_encryption_alg_values_supported = EncryptionAlgs,
id_token_encryption_enc_values_supported = EncryptionEncs,
issuer = Issuer
} =
Configuration,
Nonce = maps:get(nonce, Opts, any),
TrustedAudience = maps:get(trusted_audiences, Opts, any),
maybe
ExpClaims0 = [{<<"iss">>, Issuer}],
ExpClaims =
case Nonce of
any ->
ExpClaims0;
Bin when is_binary(Bin) ->
[{<<"nonce">>, Nonce} | ExpClaims0]
end,
Jwks1 =
case ClientJwks of
none -> Jwks0;
#jose_jwk{} -> oidcc_jwt_util:merge_jwks(Jwks0, ClientJwks)
end,
Jwks2 = oidcc_jwt_util:merge_client_secret_oct_keys(Jwks1, AllowAlgorithms, ClientSecret),
Jwks = oidcc_jwt_util:merge_client_secret_oct_keys(Jwks2, EncryptionAlgs, ClientSecret),
MaybeVerified = oidcc_jwt_util:decrypt_and_verify(
IdToken, Jwks, AllowAlgorithms, EncryptionAlgs, EncryptionEncs
),
{ok, {#jose_jwt{fields = Claims}, Jws}} ?=
case MaybeVerified of
{ok, Valid} ->
{ok, Valid};
{error, {none_alg_used, Jwt0, Jws0}} ->
{ok, {Jwt0, Jws0}};
Other ->
Other
end,
ok ?= oidcc_jwt_util:verify_claims(Claims, ExpClaims),
ok ?= verify_missing_required_claims(Claims),
ok ?= verify_aud_claim(Claims, ClientId, TrustedAudience),
ok ?= verify_azp_claim(Claims, ClientId),
ok ?= verify_exp_claim(Claims),
ok ?= verify_nbf_claim(Claims),
case Jws of
#jose_jws{alg = {jose_jws_alg_none, none}} ->
{error, {none_alg_used, Claims}};
#jose_jws{} ->
{ok, Claims};
#jose_jwe{} ->
{ok, Claims}
end
end.
?DOC("""
Validate JWT
Validates a generic JWT (such as an access token) from the given provider.
Useful if the issuer is shared between multiple applications, and the access token
generated for a user at one client is used to validate their access at another client.
## Examples
```erlang
{ok, ClientContext} =
oidcc_client_context:from_configuration_worker(provider_name,
<<"client_id">>,
<<"client_secret">>),
%% Get Jwt from Authorization header
{ok, Claims} =
oidcc:validate_jwt(Jwt, ClientContext, Opts).
```
""").
?DOC(#{since => <<"3.2.0">>}).
-spec validate_jwt(Jwt, ClientContext, Opts) ->
{ok, Claims} | {error, error()}
when
Jwt :: binary(),
ClientContext :: oidcc_client_context:t(),
Opts :: validate_jwt_opts(),
Claims :: oidcc_jwt_util:claims().
validate_jwt(Jwt, ClientContext, Opts) when is_map(Opts) ->
#oidcc_client_context{
provider_configuration = Configuration,
jwks = #jose_jwk{} = Jwks0,
client_id = ClientId,
client_secret = ClientSecret,
client_jwks = ClientJwks
} =
ClientContext,
#oidcc_provider_configuration{
issuer = Issuer
} =
Configuration,
SigningAlgs = maps:get(signing_algs, Opts, []),
EncryptionAlgs = maps:get(encryption_algs, Opts, []),
EncryptionEncs = maps:get(encryption_encs, Opts, []),
ExpClaims = [{<<"iss">>, Issuer}],
Jwks1 =
case ClientJwks of
none -> Jwks0;
#jose_jwk{} -> oidcc_jwt_util:merge_jwks(Jwks0, ClientJwks)