-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathhandler.go
1382 lines (1209 loc) · 52.4 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2022 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"net/http"
"reflect"
"strings"
"time"
"github.com/tidwall/gjson"
"github.com/pborman/uuid"
"github.com/ory/hydra/v2/x/events"
"github.com/ory/x/httprouterx"
"github.com/ory/x/josex"
"github.com/ory/x/stringsx"
jwtV5 "github.com/golang-jwt/jwt/v5"
"github.com/ory/x/errorsx"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/x/urlx"
"github.com/ory/hydra/v2/client"
"github.com/ory/hydra/v2/consent"
"github.com/ory/hydra/v2/driver/config"
"github.com/ory/hydra/v2/x"
)
const (
DefaultLoginPath = "/oauth2/fallbacks/login"
DefaultConsentPath = "/oauth2/fallbacks/consent"
DefaultPostLogoutPath = "/oauth2/fallbacks/logout/callback"
DefaultLogoutPath = "/oauth2/fallbacks/logout"
DefaultErrorPath = "/oauth2/fallbacks/error"
TokenPath = "/oauth2/token" // #nosec G101
AuthPath = "/oauth2/auth"
LogoutPath = "/oauth2/sessions/logout"
VerifiableCredentialsPath = "/credentials"
UserinfoPath = "/userinfo"
WellKnownPath = "/.well-known/openid-configuration"
JWKPath = "/.well-known/jwks.json"
// IntrospectPath points to the OAuth2 introspection endpoint.
IntrospectPath = "/oauth2/introspect"
RevocationPath = "/oauth2/revoke"
DeleteTokensPath = "/oauth2/tokens" // #nosec G101
)
type Handler struct {
r InternalRegistry
c *config.DefaultProvider
}
func NewHandler(r InternalRegistry, c *config.DefaultProvider) *Handler {
return &Handler{
r: r,
c: c,
}
}
func (h *Handler) SetRoutes(admin *httprouterx.RouterAdmin, public *httprouterx.RouterPublic, corsMiddleware func(http.Handler) http.Handler) {
public.Handler("OPTIONS", TokenPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", TokenPath, corsMiddleware(http.HandlerFunc(h.oauth2TokenExchange)))
public.GET(AuthPath, h.oAuth2Authorize)
public.POST(AuthPath, h.oAuth2Authorize)
public.GET(LogoutPath, h.performOidcFrontOrBackChannelLogout)
public.POST(LogoutPath, h.performOidcFrontOrBackChannelLogout)
public.GET(DefaultLoginPath, h.fallbackHandler("", "", http.StatusOK, config.KeyLoginURL))
public.GET(DefaultConsentPath, h.fallbackHandler("", "", http.StatusOK, config.KeyConsentURL))
public.GET(DefaultLogoutPath, h.fallbackHandler("", "", http.StatusOK, config.KeyLogoutURL))
public.GET(DefaultPostLogoutPath, h.fallbackHandler(
"You logged out successfully!",
"The Default Post Logout URL is not set which is why you are seeing this fallback page. Your log out request however succeeded.",
http.StatusOK,
config.KeyLogoutRedirectURL,
))
public.GET(DefaultErrorPath, h.DefaultErrorHandler)
public.Handler("OPTIONS", RevocationPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", RevocationPath, corsMiddleware(http.HandlerFunc(h.revokeOAuth2Token)))
public.Handler("OPTIONS", WellKnownPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("GET", WellKnownPath, corsMiddleware(http.HandlerFunc(h.discoverOidcConfiguration)))
public.Handler("OPTIONS", UserinfoPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("GET", UserinfoPath, corsMiddleware(http.HandlerFunc(h.getOidcUserInfo)))
public.Handler("POST", UserinfoPath, corsMiddleware(http.HandlerFunc(h.getOidcUserInfo)))
public.Handler("OPTIONS", VerifiableCredentialsPath, corsMiddleware(http.HandlerFunc(h.handleOptions)))
public.Handler("POST", VerifiableCredentialsPath, corsMiddleware(http.HandlerFunc(h.createVerifiableCredential)))
admin.POST(IntrospectPath, h.introspectOAuth2Token)
admin.DELETE(DeleteTokensPath, h.deleteOAuth2Token)
}
// swagger:route GET /oauth2/sessions/logout oidc revokeOidcSession
//
// # OpenID Connect Front- and Back-channel Enabled Logout
//
// This endpoint initiates and completes user logout at the Ory OAuth2 & OpenID provider and initiates OpenID Connect Front- / Back-channel logout:
//
// - https://openid.net/specs/openid-connect-frontchannel-1_0.html
// - https://openid.net/specs/openid-connect-backchannel-1_0.html
//
// Back-channel logout is performed asynchronously and does not affect logout flow.
//
// Schemes: http, https
//
// Responses:
// 302: emptyResponse
func (h *Handler) performOidcFrontOrBackChannelLogout(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := r.Context()
handled, err := h.r.ConsentStrategy().HandleOpenIDConnectLogout(ctx, w, r)
if errors.Is(err, consent.ErrAbortOAuth2Request) {
return
} else if err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
if len(handled.FrontChannelLogoutURLs) == 0 {
http.Redirect(w, r, handled.RedirectTo, http.StatusFound)
return
}
// TODO How are we supposed to test this? Maybe with cypress? #1368
t, err := template.New("logout").Parse(`<html>
<head>
<meta http-equiv="refresh" content="7; URL={{ .RedirectTo }}">
</head>
<style type="text/css">
iframe { position: absolute; left: 0; top: 0; height: 0; width: 0; border: none; }
</style>
<script>
var total = {{ len .FrontChannelLogoutURLs }};
var redir = {{ .RedirectTo }};
var timeouts = [];
var redirected = false;
// Cancel all pending timeouts to avoid to call the frontchannel multiple times.
window.onbeforeunload = () => {
redirected = true;
for (var i=0; i<timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
timeouts = [];
};
function setAndRegisterTimeout(fct, duration) {
if (redirected) {
return;
}
timeouts.push(setTimeout(fct, duration));
}
function redirect() {
window.location.replace(redir);
// In case replace failed try href
setAndRegisterTimeout(function () {
window.location.href = redir;
}, 250);
}
function done() {
total--;
if (total < 1) {
setAndRegisterTimeout(redirect, 500);
}
}
setAndRegisterTimeout(redirect, 7000); // redirect after 7 seconds if e.g. an iframe doesn't load
// If the redirect takes unusually long, show a message
setTimeout(function () {
document.getElementById("redir").style.display = "block";
}, 2000);
</script>
<body>
<noscript>
<p>
JavaScript is disabled - you should be redirected in 5 seconds but if not, click <a
href="{{ .RedirectTo }}">here</a> to continue.
</p>
</noscript>
<p id="redir" style="display: none">
Redirection takes unusually long. If you are not being redirected within the next seconds, click <a href="{{ .RedirectTo }}">here</a> to continue.
</p>
{{ range .FrontChannelLogoutURLs }}<iframe src="{{ . }}" onload="done(this)"></iframe>
{{ end }}
</body>
</html>`)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
if err := t.Execute(w, handled); err != nil {
x.LogError(r, err, h.r.Logger())
h.forwardError(w, r, err)
return
}
}
// OpenID Connect Discovery Metadata
//
// Includes links to several endpoints (for example `/oauth2/token`) and exposes information on supported signature algorithms
// among others.
//
// swagger:model oidcConfiguration
type oidcConfiguration struct {
// OpenID Connect Issuer URL
//
// An URL using the https scheme with no query or fragment component that the OP asserts as its IssuerURL Identifier.
// If IssuerURL discovery is supported , this value MUST be identical to the issuer value returned
// by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this IssuerURL.
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/
Issuer string `json:"issuer"`
// OAuth 2.0 Authorization Endpoint URL
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/oauth2/auth
AuthURL string `json:"authorization_endpoint"`
// OpenID Connect Dynamic Client Registration Endpoint URL
//
// example: https://playground.ory.sh/ory-hydra/admin/client
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
// OAuth 2.0 Token Endpoint URL
//
// required: true
// example: https://playground.ory.sh/ory-hydra/public/oauth2/token
TokenURL string `json:"token_endpoint"`
// OpenID Connect Well-Known JSON Web Keys URL
//
// URL of the OP's JSON Web Key Set [JWK] document. This contains the signing key(s) the RP uses to validate
// signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs
// to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use)
// parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage.
// Although some algorithms allow the same key to be used for both signatures and encryption, doing so is
// NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of
// keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
//
// required: true
// example: https://{slug}.projects.oryapis.com/.well-known/jwks.json
JWKsURI string `json:"jwks_uri"`
// OpenID Connect Supported Subject Types
//
// JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include
// pairwise and public.
//
// required: true
// example:
// - public
// - pairwise
SubjectTypes []string `json:"subject_types_supported"`
// OAuth 2.0 Supported Response Types
//
// JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID
// Providers MUST support the code, id_token, and the token id_token Response Type values.
//
// required: true
ResponseTypes []string `json:"response_types_supported"`
// OpenID Connect Supported Claims
//
// JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply
// values for. Note that for privacy or other reasons, this might not be an exhaustive list.
ClaimsSupported []string `json:"claims_supported"`
// OAuth 2.0 Supported Grant Types
//
// JSON array containing a list of the OAuth 2.0 Grant Type values that this OP supports.
GrantTypesSupported []string `json:"grant_types_supported"`
// OAuth 2.0 Supported Response Modes
//
// JSON array containing a list of the OAuth 2.0 response_mode values that this OP supports.
ResponseModesSupported []string `json:"response_modes_supported"`
// OpenID Connect Userinfo URL
//
// URL of the OP's UserInfo Endpoint.
UserinfoEndpoint string `json:"userinfo_endpoint"`
// OAuth 2.0 Supported Scope Values
//
// JSON array containing a list of the OAuth 2.0 [RFC6749] scope values that this server supports. The server MUST
// support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used
ScopesSupported []string `json:"scopes_supported"`
// OAuth 2.0 Supported Client Authentication Methods
//
// JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are
// client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt, as described in Section 9 of OpenID Connect Core 1.0
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
// OpenID Connect Supported Userinfo Signing Algorithm
//
// JSON array containing a list of the JWS [JWS] signing algorithms (alg values) [JWA] supported by the UserInfo Endpoint to encode the Claims in a JWT [JWT].
UserinfoSigningAlgValuesSupported []string `json:"userinfo_signing_alg_values_supported"`
// OpenID Connect Supported ID Token Signing Algorithms
//
// JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token
// to encode the Claims in a JWT.
//
// required: true
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
// OpenID Connect Default ID Token Signing Algorithms
//
// Algorithm used to sign OpenID Connect ID Tokens.
//
// required: true
IDTokenSignedResponseAlg []string `json:"id_token_signed_response_alg"`
// OpenID Connect User Userinfo Signing Algorithm
//
// Algorithm used to sign OpenID Connect Userinfo Responses.
//
// required: true
UserinfoSignedResponseAlg []string `json:"userinfo_signed_response_alg"`
// OpenID Connect Request Parameter Supported
//
// Boolean value specifying whether the OP supports use of the request parameter, with true indicating support.
RequestParameterSupported bool `json:"request_parameter_supported"`
// OpenID Connect Request URI Parameter Supported
//
// Boolean value specifying whether the OP supports use of the request_uri parameter, with true indicating support.
RequestURIParameterSupported bool `json:"request_uri_parameter_supported"`
// OpenID Connect Requires Request URI Registration
//
// Boolean value specifying whether the OP requires any request_uri values used to be pre-registered
// using the request_uris registration parameter.
RequireRequestURIRegistration bool `json:"require_request_uri_registration"`
// OpenID Connect Claims Parameter Parameter Supported
//
// Boolean value specifying whether the OP supports use of the claims parameter, with true indicating support.
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
// OAuth 2.0 Token Revocation URL
//
// URL of the authorization server's OAuth 2.0 revocation endpoint.
RevocationEndpoint string `json:"revocation_endpoint"`
// OpenID Connect Back-Channel Logout Supported
//
// Boolean value specifying whether the OP supports back-channel logout, with true indicating support.
BackChannelLogoutSupported bool `json:"backchannel_logout_supported"`
// OpenID Connect Back-Channel Logout Session Required
//
// Boolean value specifying whether the OP can pass a sid (session ID) Claim in the Logout Token to identify the RP
// session with the OP. If supported, the sid Claim is also included in ID Tokens issued by the OP
BackChannelLogoutSessionSupported bool `json:"backchannel_logout_session_supported"`
// OpenID Connect Front-Channel Logout Supported
//
// Boolean value specifying whether the OP supports HTTP-based logout, with true indicating support.
FrontChannelLogoutSupported bool `json:"frontchannel_logout_supported"`
// OpenID Connect Front-Channel Logout Session Required
//
// Boolean value specifying whether the OP can pass iss (issuer) and sid (session ID) query parameters to identify
// the RP session with the OP when the frontchannel_logout_uri is used. If supported, the sid Claim is also
// included in ID Tokens issued by the OP.
FrontChannelLogoutSessionSupported bool `json:"frontchannel_logout_session_supported"`
// OpenID Connect End-Session Endpoint
//
// URL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP.
EndSessionEndpoint string `json:"end_session_endpoint"`
// OpenID Connect Supported Request Object Signing Algorithms
//
// JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for Request Objects,
// which are described in Section 6.1 of OpenID Connect Core 1.0 [OpenID.Core]. These algorithms are used both when
// the Request Object is passed by value (using the request parameter) and when it is passed by reference
// (using the request_uri parameter).
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported"`
// OAuth 2.0 PKCE Supported Code Challenge Methods
//
// JSON array containing a list of Proof Key for Code Exchange (PKCE) [RFC7636] code challenge methods supported
// by this authorization server.
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`
// OpenID Connect Verifiable Credentials Endpoint
//
// Contains the URL of the Verifiable Credentials Endpoint.
CredentialsEndpointDraft00 string `json:"credentials_endpoint_draft_00"`
// OpenID Connect Verifiable Credentials Supported
//
// JSON array containing a list of the Verifiable Credentials supported by this authorization server.
CredentialsSupportedDraft00 []CredentialSupportedDraft00 `json:"credentials_supported_draft_00"`
}
// Verifiable Credentials Metadata (Draft 00)
//
// Includes information about the supported verifiable credentials.
//
// swagger:model credentialSupportedDraft00
type CredentialSupportedDraft00 struct {
// OpenID Connect Verifiable Credentials Format
//
// Contains the format that is supported by this authorization server.
Format string `json:"format"`
// OpenID Connect Verifiable Credentials Types
//
// Contains the types of verifiable credentials supported.
Types []string `json:"types"`
// OpenID Connect Verifiable Credentials Cryptographic Binding Methods Supported
//
// Contains a list of cryptographic binding methods supported for signing the proof.
CryptographicBindingMethodsSupported []string `json:"cryptographic_binding_methods_supported"`
// OpenID Connect Verifiable Credentials Cryptographic Suites Supported
//
// Contains a list of cryptographic suites methods supported for signing the proof.
CryptographicSuitesSupported []string `json:"cryptographic_suites_supported"`
}
// swagger:route GET /.well-known/openid-configuration oidc discoverOidcConfiguration
//
// # OpenID Connect Discovery
//
// A mechanism for an OpenID Connect Relying Party to discover the End-User's OpenID Provider and obtain information needed to interact with it, including its OAuth 2.0 endpoint locations.
//
// Popular libraries for OpenID Connect clients include oidc-client-js (JavaScript), go-oidc (Golang), and others.
// For a full list of clients go here: https://openid.net/developers/certified/
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: oidcConfiguration
// default: errorOAuth2
func (h *Handler) discoverOidcConfiguration(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
key, err := h.r.OpenIDJWTStrategy().GetPublicKey(ctx)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.Writer().Write(w, r, &oidcConfiguration{
Issuer: h.c.IssuerURL(ctx).String(),
AuthURL: h.c.OAuth2AuthURL(ctx).String(),
TokenURL: h.c.OAuth2TokenURL(ctx).String(),
JWKsURI: h.c.JWKSURL(ctx).String(),
RevocationEndpoint: urlx.AppendPaths(h.c.IssuerURL(ctx), RevocationPath).String(),
RegistrationEndpoint: h.c.OAuth2ClientRegistrationURL(ctx).String(),
SubjectTypes: h.c.SubjectTypesSupported(ctx),
ResponseTypes: []string{"code", "code id_token", "id_token", "token id_token", "token", "token id_token code"},
ClaimsSupported: h.c.OIDCDiscoverySupportedClaims(ctx),
ScopesSupported: h.c.OIDCDiscoverySupportedScope(ctx),
UserinfoEndpoint: h.c.OIDCDiscoveryUserinfoEndpoint(ctx).String(),
TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_basic", "private_key_jwt", "none"},
IDTokenSigningAlgValuesSupported: []string{key.Algorithm},
IDTokenSignedResponseAlg: []string{key.Algorithm},
UserinfoSignedResponseAlg: []string{key.Algorithm},
GrantTypesSupported: []string{"authorization_code", "implicit", "client_credentials", "refresh_token"},
ResponseModesSupported: []string{"query", "fragment"},
UserinfoSigningAlgValuesSupported: []string{"none", key.Algorithm},
RequestParameterSupported: true,
RequestURIParameterSupported: true,
RequireRequestURIRegistration: true,
BackChannelLogoutSupported: true,
BackChannelLogoutSessionSupported: true,
FrontChannelLogoutSupported: true,
FrontChannelLogoutSessionSupported: true,
EndSessionEndpoint: urlx.AppendPaths(h.c.IssuerURL(ctx), LogoutPath).String(),
RequestObjectSigningAlgValuesSupported: []string{"none", "RS256", "ES256"},
CodeChallengeMethodsSupported: []string{"plain", "S256"},
CredentialsEndpointDraft00: h.c.CredentialsEndpointURL(ctx).String(),
CredentialsSupportedDraft00: []CredentialSupportedDraft00{{
Format: "jwt_vc_json",
Types: []string{"VerifiableCredential", "UserInfoCredential"},
CryptographicBindingMethodsSupported: []string{"jwk"},
CryptographicSuitesSupported: []string{
"PS256", "RS256", "ES256",
"PS384", "RS384", "ES384",
"PS512", "RS512", "ES512",
"EdDSA",
},
}},
})
}
// OpenID Connect Userinfo
//
// swagger:model oidcUserInfo
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type oidcUserInfo struct {
// Subject - Identifier for the End-User at the IssuerURL.
Subject string `json:"sub"`
// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
Name string `json:"name,omitempty"`
// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
GivenName string `json:"given_name,omitempty"`
// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
FamilyName string `json:"family_name,omitempty"`
// Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.
MiddleName string `json:"middle_name,omitempty"`
// Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.
Nickname string `json:"nickname,omitempty"`
// Non-unique shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace.
PreferredUsername string `json:"preferred_username,omitempty"`
// URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.
Profile string `json:"profile,omitempty"`
// URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.
Picture string `json:"picture,omitempty"`
// URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.
Website string `json:"website,omitempty"`
// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 [RFC5322] addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
Email string `json:"email,omitempty"`
// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
EmailVerified bool `json:"email_verified,omitempty"`
// End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.
Gender string `json:"gender,omitempty"`
// End-User's birthday, represented as an ISO 8601:2004 [ISO8601‑2004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.
Birthdate string `json:"birthdate,omitempty"`
// String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.
Zoneinfo string `json:"zoneinfo,omitempty"`
// End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO639‑1] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO3166‑1] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.
Locale string `json:"locale,omitempty"`
// End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678.
PhoneNumber string `json:"phone_number,omitempty"`
// True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.
PhoneNumberVerified bool `json:"phone_number_verified,omitempty"`
// Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.
UpdatedAt int `json:"updated_at,omitempty"`
}
// swagger:route GET /userinfo oidc getOidcUserInfo
//
// # OpenID Connect Userinfo
//
// This endpoint returns the payload of the ID Token, including `session.id_token` values, of
// the provided OAuth 2.0 Access Token's consent request.
//
// In the case of authentication error, a WWW-Authenticate header might be set in the response
// with more information about the error. See [the spec](https://datatracker.ietf.org/doc/html/rfc6750#section-3)
// for more details about header format.
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// Responses:
// 200: oidcUserInfo
// default: errorOAuth2
func (h *Handler) getOidcUserInfo(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
tokenType, ar, err := h.r.OAuth2Provider().IntrospectToken(ctx, fosite.AccessTokenFromRequest(r), fosite.AccessToken, session)
if err != nil {
rfcerr := fosite.ErrorToRFC6749Error(err)
if rfcerr.StatusCode() == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer error="%s",error_description="%s"`, rfcerr.ErrorField, rfcerr.GetDescription()))
}
h.r.Writer().WriteError(w, r, err)
return
}
if tokenType != fosite.AccessToken {
errorDescription := "Only access tokens are allowed in the authorization header."
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer error="invalid_token",error_description="%s"`, errorDescription))
h.r.Writer().WriteErrorCode(w, r, http.StatusUnauthorized, errors.New(errorDescription))
return
}
c, ok := ar.GetClient().(*client.Client)
if !ok {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrServerError.WithHint("Unable to type assert to *client.Client.")))
return
}
interim := ar.GetSession().(*Session).IDTokenClaims().ToMap()
delete(interim, "nonce")
delete(interim, "at_hash")
delete(interim, "c_hash")
delete(interim, "exp")
delete(interim, "sid")
delete(interim, "jti")
aud, ok := interim["aud"].([]string)
if !ok || len(aud) == 0 {
aud = []string{c.GetID()}
} else {
found := false
for _, a := range aud {
if a == c.GetID() {
found = true
break
}
}
if !found {
aud = append(aud, c.GetID())
}
}
interim["aud"] = aud
if c.UserinfoSignedResponseAlg == "RS256" {
interim["jti"] = uuid.New()
interim["iat"] = time.Now().Unix()
keyID, err := h.r.OpenIDJWTStrategy().GetPublicKeyID(r.Context())
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
token, _, err := h.r.OpenIDJWTStrategy().Generate(ctx, interim, &jwt.Headers{
Extra: map[string]interface{}{"kid": keyID},
})
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/jwt")
_, _ = w.Write([]byte(token))
} else if c.UserinfoSignedResponseAlg == "" || c.UserinfoSignedResponseAlg == "none" {
h.r.Writer().Write(w, r, interim)
} else {
h.r.Writer().WriteError(w, r, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unsupported userinfo signing algorithm '%s'.", c.UserinfoSignedResponseAlg)))
return
}
}
// Revoke OAuth 2.0 Access or Refresh Token Request
//
// swagger:parameters revokeOAuth2Token
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type revokeOAuth2Token struct {
// in: formData
// required: true
Token string `json:"token"`
// in: formData
ClientID string `json:"client_id"`
// in: formData
ClientSecret string `json:"client_secret"`
}
// swagger:route POST /oauth2/revoke oAuth2 revokeOAuth2Token
//
// # Revoke OAuth 2.0 Access or Refresh Token
//
// Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no
// longer be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token.
// Revoking a refresh token also invalidates the access token that was created with it. A token may only be revoked by
// the client the token was generated for.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2:
//
// Responses:
// 200: emptyResponse
// default: errorOAuth2
func (h *Handler) revokeOAuth2Token(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
events.Trace(r.Context(), events.AccessTokenRevoked)
err := h.r.OAuth2Provider().NewRevocationRequest(ctx, r)
if err != nil {
x.LogError(r, err, h.r.Logger())
}
h.r.OAuth2Provider().WriteRevocationResponse(ctx, w, err)
}
// Introspect OAuth 2.0 Access or Refresh Token Request
//
// swagger:parameters introspectOAuth2Token
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type introspectOAuth2Token struct {
// The string value of the token. For access tokens, this
// is the "access_token" value returned from the token endpoint
// defined in OAuth 2.0. For refresh tokens, this is the "refresh_token"
// value returned.
//
// required: true
// in: formData
Token string `json:"token"`
// An optional, space separated list of required scopes. If the access token was not granted one of the
// scopes, the result of active will be false.
//
// in: formData
Scope string `json:"scope"`
}
// swagger:route POST /admin/oauth2/introspect oAuth2 introspectOAuth2Token
//
// # Introspect OAuth2 Access and Refresh Tokens
//
// The introspection endpoint allows to check if a token (both refresh and access) is active or not. An active token
// is neither expired nor revoked. If a token is active, additional information on the token will be included. You can
// set additional data for a token by setting `session.access_token` during the consent flow.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: introspectedOAuth2Token
// default: errorOAuth2
func (h *Handler) introspectOAuth2Token(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
if r.Method != "POST" {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf("HTTP method is \"%s\", expected \"POST\".", r.Method))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
} else if err := r.ParseMultipartForm(1 << 20); err != nil && err != http.ErrNotMultipart {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Unable to parse HTTP body, make sure to send a properly formatted form request body.").WithDebug(err.Error()))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
} else if len(r.PostForm) == 0 {
err := errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("The POST body can not be empty."))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
token := r.PostForm.Get("token")
tokenType := r.PostForm.Get("token_type_hint")
scope := r.PostForm.Get("scope")
tt, ar, err := h.r.OAuth2Provider().IntrospectToken(ctx, token, fosite.TokenType(tokenType), session, strings.Split(scope, " ")...)
if err != nil {
x.LogAudit(r, err, h.r.Logger())
err := errorsx.WithStack(fosite.ErrInactiveToken.WithHint("An introspection strategy indicated that the token is inactive.").WithDebug(err.Error()))
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
resp := &fosite.IntrospectionResponse{
Active: true,
AccessRequester: ar,
TokenUse: tt,
AccessTokenType: "Bearer",
}
exp := resp.GetAccessRequester().GetSession().GetExpiresAt(tt)
if exp.IsZero() {
if tt == fosite.RefreshToken {
exp = resp.GetAccessRequester().GetRequestedAt().Add(h.c.GetRefreshTokenLifespan(ctx))
} else {
exp = resp.GetAccessRequester().GetRequestedAt().Add(h.c.GetAccessTokenLifespan(ctx))
}
}
session, ok := resp.GetAccessRequester().GetSession().(*Session)
if !ok {
err := errorsx.WithStack(fosite.ErrServerError.WithHint("Expected session to be of type *Session, but got another type.").WithDebug(fmt.Sprintf("Got type %s", reflect.TypeOf(resp.GetAccessRequester().GetSession()))))
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteIntrospectionError(ctx, w, err)
return
}
var obfuscated string
if len(session.Claims.Subject) > 0 && session.Claims.Subject != session.Subject {
obfuscated = session.Claims.Subject
}
audience := resp.GetAccessRequester().GetGrantedAudience()
if audience == nil {
// prevent null
audience = fosite.Arguments{}
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err = json.NewEncoder(w).Encode(&Introspection{
Active: resp.IsActive(),
ClientID: resp.GetAccessRequester().GetClient().GetID(),
Scope: strings.Join(resp.GetAccessRequester().GetGrantedScopes(), " "),
ExpiresAt: exp.Unix(),
IssuedAt: resp.GetAccessRequester().GetRequestedAt().Unix(),
Subject: session.GetSubject(),
Username: session.GetUsername(),
Extra: session.Extra,
Audience: audience,
Issuer: h.c.IssuerURL(ctx).String(),
ObfuscatedSubject: obfuscated,
TokenType: resp.GetAccessTokenType(),
TokenUse: string(resp.GetTokenUse()),
NotBefore: resp.GetAccessRequester().GetRequestedAt().Unix(),
}); err != nil {
x.LogError(r, errorsx.WithStack(err), h.r.Logger())
}
events.Trace(ctx,
events.AccessTokenInspected,
events.WithSubject(session.GetSubject()),
events.WithClientID(resp.GetAccessRequester().GetClient().GetID()),
)
}
// OAuth 2.0 Token Exchange Parameters
//
// swagger:parameters oauth2TokenExchange
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type performOAuth2TokenFlow struct {
// in: formData
// required: true
GrantType string `json:"grant_type"`
// in: formData
Code string `json:"code"`
// in: formData
RefreshToken string `json:"refresh_token"`
// in: formData
RedirectURI string `json:"redirect_uri"`
// in: formData
ClientID string `json:"client_id"`
}
// OAuth2 Token Exchange Result
//
// swagger:model oAuth2TokenExchange
//
//lint:ignore U1000 Used to generate Swagger and OpenAPI definitions
type oAuth2TokenExchange struct {
// The lifetime in seconds of the access token. For
// example, the value "3600" denotes that the access token will
// expire in one hour from the time the response was generated.
ExpiresIn int `json:"expires_in"`
// The scope of the access token
Scope string `json:"scope"`
// To retrieve a refresh token request the id_token scope.
IDToken string `json:"id_token"`
// The access token issued by the authorization server.
AccessToken string `json:"access_token"`
// The refresh token, which can be used to obtain new
// access tokens. To retrieve it add the scope "offline" to your access token request.
RefreshToken string `json:"refresh_token"`
// The type of the token issued
TokenType string `json:"token_type"`
}
// swagger:route POST /oauth2/token oAuth2 oauth2TokenExchange
//
// # The OAuth 2.0 Token Endpoint
//
// Use open source libraries to perform OAuth 2.0 and OpenID Connect
// available for any programming language. You can find a list of libraries here https://oauth.net/code/
//
// The Ory SDK is not yet able to this endpoint properly.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2:
//
// Responses:
// 200: oAuth2TokenExchange
// default: errorOAuth2
func (h *Handler) oauth2TokenExchange(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := NewSessionWithCustomClaims(ctx, h.c, "")
accessRequest, err := h.r.OAuth2Provider().NewAccessRequest(ctx, r, session)
if err != nil {
h.logOrAudit(err, r)
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError)
return
}
if accessRequest.GetGrantTypes().ExactOne(string(fosite.GrantTypeClientCredentials)) ||
accessRequest.GetGrantTypes().ExactOne(string(fosite.GrantTypeJWTBearer)) {
var accessTokenKeyID string
if h.c.AccessTokenStrategy(ctx, client.AccessTokenStrategySource(accessRequest.GetClient())) == "jwt" {
accessTokenKeyID, err = h.r.AccessTokenJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
x.LogError(r, err, h.r.Logger())
h.r.OAuth2Provider().WriteAccessError(ctx, w, accessRequest, err)
events.Trace(ctx, events.TokenExchangeError, events.WithRequest(accessRequest))
return
}
}
// only for client_credentials, otherwise Authentication is included in session
if accessRequest.GetGrantTypes().ExactOne("client_credentials") {
session.Subject = accessRequest.GetClient().GetID()
}
session.ClientID = accessRequest.GetClient().GetID()
session.KID = accessTokenKeyID
session.DefaultSession.Claims.Issuer = h.c.IssuerURL(r.Context()).String()
session.DefaultSession.Claims.IssuedAt = time.Now().UTC()
scopes := accessRequest.GetRequestedScopes()
// Added for compatibility with MITREid
if h.c.GrantAllClientCredentialsScopesPerDefault(r.Context()) && len(scopes) == 0 {
for _, scope := range accessRequest.GetClient().GetScopes() {
accessRequest.GrantScope(scope)
}
}
for _, scope := range scopes {
if h.r.Config().GetScopeStrategy(ctx)(accessRequest.GetClient().GetScopes(), scope) {
accessRequest.GrantScope(scope)
}
}
for _, audience := range accessRequest.GetRequestedAudience() {
if h.r.AudienceStrategy()(accessRequest.GetClient().GetAudience(), []string{audience}) == nil {
accessRequest.GrantAudience(audience)