-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
228 lines (187 loc) · 6.14 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
package oauth2
import (
"net/http"
"net/url"
"encoding/json"
"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory-am/fosite"
"github.com/ory-am/hydra/herodot"
"github.com/ory-am/hydra/pkg"
"github.com/pkg/errors"
"strings"
"time"
)
const (
OpenIDConnectKeyName = "hydra.openid.id-token"
ConsentPath = "/oauth2/consent"
TokenPath = "/oauth2/token"
AuthPath = "/oauth2/auth"
// 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.Herodot
ForcedHTTP bool
ConsentURL url.URL
AccessTokenLifespan time.Duration
CookieStore sessions.Store
}
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)
}
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.OAuth2.WriteRevocationResponse(w, err)
}
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.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(),
})
if err != nil {
pkg.LogError(err)
}
}
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.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, r, accessRequest)
if err != nil {
pkg.LogError(err)
h.OAuth2.WriteAccessError(w, accessRequest, err)
return
}
h.OAuth2.WriteAccessResponse(w, accessRequest, accessResponse)
}
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.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.writeAuthorizeError(w, authorizeRequest, err)
return
}
return
}
cookie, err := h.CookieStore.Get(r, consentCookieName)
if err != nil {
pkg.LogError(err)
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.writeAuthorizeError(w, authorizeRequest, errors.Wrap(fosite.ErrAccessDenied, ""))
return
}
if err := cookie.Save(r, w); err != nil {
pkg.LogError(err)
h.writeAuthorizeError(w, authorizeRequest, errors.Wrapf(fosite.ErrServerError, "Could not store session cookie: %s", err))
return
}
// done
response, err := h.OAuth2.NewAuthorizeResponse(ctx, r, authorizeRequest, session)
if err != nil {
pkg.LogError(err)
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 {
schema := "https"
if h.ForcedHTTP {
schema = "http"
}
cookie, err := h.CookieStore.Get(r, consentCookieName)
if err != nil {
return err
}
challenge, err := h.Consent.IssueChallenge(authorizeRequest, schema+"://"+r.Host+r.URL.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)
}