forked from ory/hydra
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
427 lines (373 loc) · 12.3 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
package oauth2
import (
"encoding/json"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory/fosite"
"github.com/ory/herodot"
"github.com/ory/hydra/pkg"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
OpenIDConnectKeyName = "hydra.openid.id-token"
ConsentPath = "/oauth2/consent"
TokenPath = "/oauth2/token"
AuthPath = "/oauth2/auth"
WellKnownPath = "/.well-known/openid-configuration"
JWKPath = "/.well-known/jwks.json"
// IntrospectPath points to the OAuth2 introspection endpoint.
IntrospectPath = "/oauth2/introspect"
RevocationPath = "/oauth2/revoke"
consentCookieName = "consent_session"
)
type Handler struct {
OAuth2 fosite.OAuth2Provider
Consent ConsentStrategy
H herodot.Writer
ForcedHTTP bool
ConsentURL url.URL
AccessTokenLifespan time.Duration
CookieStore sessions.Store
L logrus.FieldLogger
Issuer string
}
// 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 JWS signing algorithms (alg values) supported by the OP for the ID Token
// to encode the Claims in a JWT [JWT]. The algorithm RS256 MUST be included. The value none MAY be supported,
// but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint
// (such as when using the Authorization Code Flow).
//
// required: true
SigningAlgs []string `json:"id_token_signing_alg_values_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"`
}
func (h *Handler) SetRoutes(r *httprouter.Router) {
r.POST(TokenPath, h.TokenHandler)
r.GET(AuthPath, h.AuthHandler)
r.POST(AuthPath, h.AuthHandler)
r.GET(ConsentPath, h.DefaultConsentHandler)
r.POST(IntrospectPath, h.IntrospectHandler)
r.POST(RevocationPath, h.RevocationHandler)
r.GET(WellKnownPath, h.WellKnownHandler)
}
// swagger:route GET /.well-known/openid-configuration oauth2 openid-connect WellKnownHandler
//
// Server well known configuration
//
// For more information, please refer to https://openid.net/specs/openid-connect-discovery-1_0.html
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// Responses:
// 200: WellKnown
// 401: genericError
// 500: genericError
func (h *Handler) WellKnownHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
wellKnown := WellKnown{
Issuer: h.Issuer,
AuthURL: h.Issuer + AuthPath,
TokenURL: h.Issuer + TokenPath,
JWKsURI: h.Issuer + JWKPath,
SubjectTypes: []string{"pairwise", "public"},
SigningAlgs: []string{"RS256"},
ResponseTypes: []string{"code", "code id_token", "id_token", "token id_token", "token"},
}
h.H.Write(w, r, wellKnown)
}
// swagger:route POST /oauth2/revoke oauth2 revokeOAuthToken
//
// Revoke an OAuth2 access token
//
// For more information, please refer to https://tools.ietf.org/html/rfc7009
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// 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 introspectOAuthToken
//
// Introspect an OAuth2 access token
//
// For more information, please refer to https://tools.ietf.org/html/rfc7662
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// oauth2:
//
// Responses:
// 200: introspectOAuthTokenResponse
// 401: genericError
// 500: genericError
func (h *Handler) IntrospectHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
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")
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,
Audience: resp.GetAccessRequester().GetClient().GetID(),
Issuer: h.Issuer,
})
if err != nil {
pkg.LogError(err, h.L)
}
}
// swagger:route POST /oauth2/token oauth2 oauthToken
//
// The OAuth 2.0 Token endpoint
//
// For more information, please refer to https://tools.ietf.org/html/rfc6749#section-4
//
// Consumes:
// - application/x-www-form-urlencoded
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Security:
// basic:
//
// 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 fosite.HierarchicScopeStrategy(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 Auth endpoint
//
// For more information, please refer to https://tools.ietf.org/html/rfc6749#section-4
//
// 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
consentToken := authorizeRequest.GetRequestForm().Get("consent")
if consentToken == "" {
// 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
} else if consentToken == "denied" {
err := errors.New("The resource owner denied consent for this request")
h.writeAuthorizeError(w, authorizeRequest, &fosite.RFC6749Error{
Name: "Resource owner denied consent",
Description: err.Error(),
Debug: err.Error(),
Hint: "Token validation failed.",
Code: http.StatusUnauthorized,
})
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.ValidateResponse(authorizeRequest, consentToken, cookie)
if err != nil {
pkg.LogError(err, h.L)
h.writeAuthorizeError(w, authorizeRequest, errors.Wrap(fosite.ErrAccessDenied, ""))
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.IssueChallenge(authorizeRequest, authUrl.String(), cookie)
if err != nil {
return err
}
p := h.ConsentURL
q := p.Query()
q.Set("challenge", 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)
}