-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
601 lines (535 loc) · 19 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
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Aeneas Rekkas <aeneas+oss@aeneas.io>
* @copyright 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/
package oauth2
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/julienschmidt/httprouter"
"github.com/ory/fosite"
"github.com/ory/hydra/firewall"
"github.com/ory/hydra/pkg"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
OpenIDConnectKeyName = "hydra.openid.id-token"
DefaultConsentPath = "/oauth2/consent-fallback"
TokenPath = "/oauth2/token"
AuthPath = "/oauth2/auth"
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"
FlushPath = "/oauth2/flush"
IntrospectScope = "hydra.introspect"
consentCookieName = "consent_session"
)
// swagger:model wellKnown
type WellKnown struct {
// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier.
// If Issuer 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 Issuer.
//
// required: true
Issuer string `json:"issuer"`
// URL of the OP's OAuth 2.0 Authorization Endpoint
//
// required: true
AuthURL string `json:"authorization_endpoint"`
// URL of the OP's OAuth 2.0 Token Endpoint
//
// required: true
TokenURL string `json:"token_endpoint"`
// 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
JWKsURI string `json:"jwks_uri"`
// JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include
// pairwise and public.
//
// required: true
SubjectTypes []string `json:"subject_types_supported"`
// 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"`
// 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"`
// URL of the OP's UserInfo Endpoint.
UserinfoEndpoint string `json:"userinfo_endpoint"`
// SON 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"`
// 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"`
// 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"`
}
// swagger:model flushInactiveOAuth2TokensRequest
type FlushInactiveOAuth2TokensRequest struct {
// NotAfter sets after which point tokens should not be flushed. This is useful when you want to keep a history
// of recently issued tokens for auditing.
NotAfter time.Time `json:"notAfter"`
}
func (h *Handler) SetRoutes(r *httprouter.Router) {
r.POST(TokenPath, h.TokenHandler)
r.GET(AuthPath, h.AuthHandler)
r.POST(AuthPath, h.AuthHandler)
r.GET(DefaultConsentPath, h.DefaultConsentHandler)
r.POST(IntrospectPath, h.IntrospectHandler)
r.POST(RevocationPath, h.RevocationHandler)
r.GET(WellKnownPath, h.WellKnownHandler)
r.GET(UserinfoPath, h.UserinfoHandler)
r.POST(UserinfoPath, h.UserinfoHandler)
r.POST(FlushPath, h.FlushHandler)
}
// swagger:route GET /.well-known/openid-configuration oAuth2 getWellKnown
//
// Server well known configuration
//
// The well known endpoint an be used to retrieve information for OpenID Connect clients. We encourage you to not roll
// your own OpenID Connect client but to use an OpenID Connect client library instead. You can learn more on this
// flow at https://openid.net/specs/openid-connect-discovery-1_0.html
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 200: wellKnown
// 401: genericError
// 500: genericError
func (h *Handler) WellKnownHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
userInfoEndpoint := h.Issuer + UserinfoPath
if h.UserinfoEndpoint != "" {
userInfoEndpoint = h.UserinfoEndpoint
}
claimsSupported := []string{"sub"}
if h.ClaimsSupported != "" {
claimsSupported = append(claimsSupported, strings.Split(h.ClaimsSupported, ",")...)
}
scopesSupported := []string{"offline", "openid"}
if h.ScopesSupported != "" {
scopesSupported = append(scopesSupported, strings.Split(h.ScopesSupported, ",")...)
}
h.H.Write(w, r, &WellKnown{
Issuer: h.Issuer,
AuthURL: h.Issuer + AuthPath,
TokenURL: h.Issuer + TokenPath,
JWKsURI: h.Issuer + JWKPath,
SubjectTypes: []string{"pairwise", "public"},
ResponseTypes: []string{"code", "code id_token", "id_token", "token id_token", "token", "token id_token code"},
ClaimsSupported: claimsSupported,
ScopesSupported: scopesSupported,
UserinfoEndpoint: userInfoEndpoint,
TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_basic"},
IDTokenSigningAlgValuesSupported: []string{"RS256"},
})
}
// swagger:route POST /userinfo oAuth2 userinfo
//
// OpenID Connect Userinfo
//
// This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 access token.
// The endpoint implements http://openid.net/specs/openid-connect-core-1_0.html#UserInfo .
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// Responses:
// 200: userinfoResponse
// 401: genericError
// 500: genericError
func (h *Handler) UserinfoHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
session := NewSession("")
ar, err := h.OAuth2.IntrospectToken(r.Context(), fosite.AccessTokenFromRequest(r), fosite.AccessToken, session)
if err != nil {
h.H.WriteError(w, r, err)
return
}
interim := ar.GetSession().(*Session).IDTokenClaims().ToMap()
delete(interim, "aud")
delete(interim, "iss")
delete(interim, "nonce")
delete(interim, "at_hash")
delete(interim, "c_hash")
delete(interim, "auth_time")
delete(interim, "iat")
delete(interim, "exp")
h.H.Write(w, r, interim)
}
// swagger:route POST /oauth2/revoke oAuth2 revokeOAuth2Token
//
// Revoke OAuth2 tokens
//
// 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.
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Schemes: http, https
//
// Security:
// basic:
//
// Responses:
// 200: emptyResponse
// 401: genericError
// 500: genericError
func (h *Handler) RevocationHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var ctx = fosite.NewContext()
err := h.OAuth2.NewRevocationRequest(ctx, r)
if err != nil {
pkg.LogError(err, h.L)
}
h.OAuth2.WriteRevocationResponse(w, err)
}
// swagger:route POST /oauth2/introspect oAuth2 introspectOAuth2Token
//
// Introspect OAuth2 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 `accessTokenExtra` during the consent flow.
//
// ```
// {
// "resources": ["rn:hydra:oauth2:tokens"],
// "actions": ["introspect"],
// "effect": "allow"
// }
// ```
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2: hydra.introspect
//
// Responses:
// 200: oAuth2TokenIntrospection
// 401: genericError
// 500: genericError
func (h *Handler) IntrospectHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if token := h.W.TokenFromRequest(r); token != "" {
if _, err := h.W.TokenAllowed(r.Context(), token, &firewall.TokenAccessRequest{
Resource: fmt.Sprintf(h.PrefixResource("oauth2:tokens")),
Action: "introspect",
}, IntrospectScope); err != nil {
h.H.WriteError(w, r, err)
return
}
} else if client, _, ok := r.BasicAuth(); ok {
// If no token is given, we do not need a scope.
if err := h.W.IsAllowed(r.Context(), &firewall.AccessRequest{
Subject: client,
Resource: fmt.Sprintf(h.PrefixResource("oauth2:tokens")),
Action: "introspect",
}); err != nil {
h.H.WriteError(w, r, err)
return
}
} else {
h.H.WriteError(w, r, errors.WithStack(fosite.ErrRequestUnauthorized))
return
}
var session = NewSession("")
var ctx = fosite.NewContext()
resp, err := h.OAuth2.NewIntrospectionRequest(ctx, r, session)
if err != nil {
pkg.LogError(err, h.L)
h.OAuth2.WriteIntrospectionError(w, err)
return
}
exp := resp.GetAccessRequester().GetSession().GetExpiresAt(fosite.AccessToken)
if exp.IsZero() {
exp = resp.GetAccessRequester().GetRequestedAt().Add(h.AccessTokenLifespan)
}
w.Header().Set("Content-Type", "application/json;charset=UTF-8")
if err = json.NewEncoder(w).Encode(&Introspection{
Active: true,
ClientID: resp.GetAccessRequester().GetClient().GetID(),
Scope: strings.Join(resp.GetAccessRequester().GetGrantedScopes(), " "),
ExpiresAt: exp.Unix(),
IssuedAt: resp.GetAccessRequester().GetRequestedAt().Unix(),
Subject: resp.GetAccessRequester().GetSession().GetSubject(),
Username: resp.GetAccessRequester().GetSession().GetUsername(),
Extra: resp.GetAccessRequester().GetSession().(*Session).Extra,
Issuer: h.Issuer,
}); err != nil {
pkg.LogError(err, h.L)
}
}
// swagger:route POST /oauth2/flush oAuth2 flushInactiveOAuth2Tokens
//
// Flush Expired OAuth2 Access Tokens
//
// This endpoint flushes expired OAuth2 access tokens from the database. You can set a time after which no tokens will be
// not be touched, in case you want to keep recent tokens for auditing. Refresh tokens can not be flushed as they are deleted
// automatically when performing the refresh flow.
//
//
// ```
// {
// "resources": ["rn:hydra:oauth2:tokens"],
// "actions": ["flush"],
// "effect": "allow"
// }
// ```
//
// Consumes:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2: hydra.oauth2.flush
//
// Responses:
// 204: emptyResponse
// 401: genericError
// 500: genericError
func (h *Handler) FlushHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if token := h.W.TokenFromRequest(r); token != "" {
if _, err := h.W.TokenAllowed(r.Context(), token, &firewall.TokenAccessRequest{
Resource: fmt.Sprintf(h.PrefixResource("oauth2:tokens")),
Action: "flush",
}, "hydra.oauth2.flush"); err != nil {
h.H.WriteError(w, r, err)
return
}
} else {
h.H.WriteError(w, r, errors.WithStack(fosite.ErrRequestUnauthorized))
return
}
var fr FlushInactiveOAuth2TokensRequest
if err := json.NewDecoder(r.Body).Decode(&fr); err != nil {
h.H.WriteError(w, r, err)
return
}
if fr.NotAfter.IsZero() {
fr.NotAfter = time.Now()
}
if err := h.Storage.FlushInactiveAccessTokens(context.Background(), fr.NotAfter); err != nil {
h.H.WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// swagger:route POST /oauth2/token oAuth2 oauthToken
//
// The OAuth 2.0 token endpoint
//
// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows.
// OAuth2 is a very popular protocol and a library for your programming language will exists.
//
// To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
// oauth2:
//
// Responses:
// 200: oauthTokenResponse
// 401: genericError
// 500: genericError
func (h *Handler) TokenHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var session = NewSession("")
var ctx = fosite.NewContext()
accessRequest, err := h.OAuth2.NewAccessRequest(ctx, r, session)
if err != nil {
pkg.LogError(err, h.L)
h.OAuth2.WriteAccessError(w, accessRequest, err)
return
}
if accessRequest.GetGrantTypes().Exact("client_credentials") {
session.Subject = accessRequest.GetClient().GetID()
for _, scope := range accessRequest.GetRequestedScopes() {
if h.ScopeStrategy(accessRequest.GetClient().GetScopes(), scope) {
accessRequest.GrantScope(scope)
}
}
}
accessResponse, err := h.OAuth2.NewAccessResponse(ctx, accessRequest)
if err != nil {
pkg.LogError(err, h.L)
h.OAuth2.WriteAccessError(w, accessRequest, err)
return
}
h.OAuth2.WriteAccessResponse(w, accessRequest, accessResponse)
}
// swagger:route GET /oauth2/auth oAuth2 oauthAuth
//
// The OAuth 2.0 authorize endpoint
//
// This endpoint is not documented here because you should never use your own implementation to perform OAuth2 flows.
// OAuth2 is a very popular protocol and a library for your programming language will exists.
//
// To learn more about this flow please refer to the specification: https://tools.ietf.org/html/rfc6749
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Schemes: http, https
//
// Responses:
// 302: emptyResponse
// 401: genericError
// 500: genericError
func (h *Handler) AuthHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var ctx = fosite.NewContext()
authorizeRequest, err := h.OAuth2.NewAuthorizeRequest(ctx, r)
if err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, err)
return
}
// A session_token will be available if the user was authenticated an gave consent
consent := authorizeRequest.GetRequestForm().Get("consent")
if consent == "" {
// otherwise redirect to log in endpoint
if err := h.redirectToConsent(w, r, authorizeRequest); err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, err)
return
}
return
}
cookie, err := h.CookieStore.Get(r, consentCookieName)
if err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, errors.Wrapf(fosite.ErrServerError, "Could not open session: %s", err))
return
}
// decode consent_token claims
// verify anti-CSRF (inject state) and anti-replay token (expiry time, good value would be 10 seconds)
session, err := h.Consent.ValidateConsentRequest(authorizeRequest, consent, cookie)
if err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, err)
return
}
if err := cookie.Save(r, w); err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, errors.Wrapf(fosite.ErrServerError, "Could not store session cookie: %s", err))
return
}
// done
response, err := h.OAuth2.NewAuthorizeResponse(ctx, authorizeRequest, session)
if err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, err)
return
}
h.OAuth2.WriteAuthorizeResponse(w, authorizeRequest, response)
}
func (h *Handler) redirectToConsent(w http.ResponseWriter, r *http.Request, authorizeRequest fosite.AuthorizeRequester) error {
// Error can be ignored because a session will always be returned
cookie, _ := h.CookieStore.Get(r, consentCookieName)
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
host = r.Host
}
authUrl, err := url.Parse(h.Issuer + AuthPath)
if err != nil {
return err
}
authHost, _, err := net.SplitHostPort(authUrl.Host)
if err != nil {
authHost = authUrl.Host
}
if authHost != host {
h.L.WithFields(logrus.Fields{
"request_host": host,
"issuer_host": authHost,
}).Warnln("Host from auth request does not match issuer host. The consent return redirect may fail.")
}
authUrl.RawQuery = r.URL.RawQuery
challenge, err := h.Consent.CreateConsentRequest(authorizeRequest, authUrl.String(), cookie)
if err != nil {
return err
}
p := h.ConsentURL
q := p.Query()
q.Set("consent", challenge)
p.RawQuery = q.Encode()
if err := cookie.Save(r, w); err != nil {
return err
}
http.Redirect(w, r, p.String(), http.StatusFound)
return nil
}
func (h *Handler) writeAuthorizeError(w http.ResponseWriter, ar fosite.AuthorizeRequester, err error) {
if !ar.IsRedirectURIValid() {
var rfcerr = fosite.ErrorToRFC6749Error(err)
redirectURI := h.ConsentURL
query := redirectURI.Query()
query.Add("error", rfcerr.Name)
query.Add("error_description", rfcerr.Description)
redirectURI.RawQuery = query.Encode()
w.Header().Add("Location", redirectURI.String())
w.WriteHeader(http.StatusFound)
return
}
h.OAuth2.WriteAuthorizeError(w, ar, err)
}