-
Notifications
You must be signed in to change notification settings - Fork 4
/
response_handler.go
268 lines (216 loc) · 8.47 KB
/
response_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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package oauth2
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"authelia.com/provider/oauth2/internal/consts"
"authelia.com/provider/oauth2/token/jarm"
"authelia.com/provider/oauth2/x/errorsx"
)
type DefaultResponseModeHandler struct {
Config ResponseModeHandlerConfigurator
}
// ResponseModes returns the response modes this fosite.ResponseModeHandler is responsible for.
func (h *DefaultResponseModeHandler) ResponseModes() ResponseModeTypes {
return ResponseModeTypes{
ResponseModeDefault,
ResponseModeQuery,
ResponseModeFragment,
ResponseModeFormPost,
ResponseModeJWT,
ResponseModeQueryJWT,
ResponseModeFragmentJWT,
ResponseModeFormPostJWT,
}
}
// WriteAuthorizeResponse writes authorization responses.
func (h *DefaultResponseModeHandler) WriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, responder AuthorizeResponder) {
header := rw.Header()
header.Set(consts.HeaderCacheControl, consts.CacheControlNoStore)
header.Set(consts.HeaderPragma, consts.PragmaNoCache)
rheader := responder.GetHeader()
for k := range rheader {
header.Set(k, rheader.Get(k))
}
h.handleWriteAuthorizeResponse(ctx, rw, requester, responder.GetParameters())
}
// WriteAuthorizeError writes authorization errors.
func (h *DefaultResponseModeHandler) WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, e error) {
rfc := ErrorToRFC6749Error(e).
WithLegacyFormat(h.Config.GetUseLegacyErrorFormat(ctx)).
WithExposeDebug(h.Config.GetSendDebugMessagesToClients(ctx)).
WithLocalizer(h.Config.GetMessageCatalog(ctx), getLangFromRequester(requester))
if !requester.IsRedirectURIValid() {
h.handleWriteAuthorizeErrorJSON(ctx, rw, rfc)
return
}
parameters := rfc.ToValues()
if state := requester.GetState(); len(state) != 0 {
parameters.Set(consts.FormParameterState, state)
}
h.handleWriteAuthorizeResponse(ctx, rw, requester, parameters)
}
func (h *DefaultResponseModeHandler) handleWriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, parameters url.Values) {
redirectURI := requester.GetRedirectURI()
redirectURI.Fragment = ""
var (
form url.Values
err error
location string
)
rm := requester.GetResponseMode()
switch rm {
case ResponseModeJWT:
if requester.GetResponseTypes().ExactOne(consts.ResponseTypeAuthorizationCodeFlow) {
rm = ResponseModeQueryJWT
} else {
rm = ResponseModeFragmentJWT
}
}
for _, handler := range h.Config.GetResponseModeParameterHandlers(ctx) {
if handler.ResponseModes().Has(rm) {
handler.WriteParameters(ctx, requester, parameters)
}
}
switch rm {
case ResponseModeFormPost, ResponseModeFormPostJWT:
if form, err = h.EncodeResponseForm(ctx, rm, requester, parameters); err != nil {
h.handleWriteAuthorizeErrorJSON(ctx, rw, ErrServerError.WithWrap(err).WithDebugError(err))
return
}
rw.Header().Set(consts.HeaderContentType, consts.ContentTypeTextHTML)
h.Config.GetFormPostResponseWriter(ctx)(rw, GetPostFormHTMLTemplate(ctx, h.Config), redirectURI.String(), form)
return
case ResponseModeQuery, ResponseModeDefault, ResponseModeQueryJWT, ResponseModeJWT:
for key, values := range redirectURI.Query() {
for _, value := range values {
parameters.Add(key, value)
}
}
if form, err = h.EncodeResponseForm(ctx, rm, requester, parameters); err != nil {
h.handleWriteAuthorizeErrorJSON(ctx, rw, ErrServerError.WithWrap(err).WithDebugError(err))
return
}
redirectURI.RawQuery = form.Encode()
location = redirectURI.String()
case ResponseModeFragment, ResponseModeFragmentJWT:
if form, err = h.EncodeResponseForm(ctx, rm, requester, parameters); err != nil {
h.handleWriteAuthorizeErrorJSON(ctx, rw, ErrServerError.WithWrap(err).WithDebugError(err))
return
}
location = redirectURI.String() + "#" + form.Encode()
}
rw.Header().Set(consts.HeaderLocation, location)
rw.WriteHeader(http.StatusSeeOther)
}
// EncodeResponseForm encodes the response form if necessary.
func (h *DefaultResponseModeHandler) EncodeResponseForm(ctx context.Context, rm ResponseModeType, requester AuthorizeRequester, parameters url.Values) (form url.Values, err error) {
switch rm {
case ResponseModeFormPostJWT, ResponseModeQueryJWT, ResponseModeFragmentJWT:
client := requester.GetClient()
jclient, ok := client.(JARMClient)
if !ok {
return nil, errorsx.WithStack(ErrServerError.WithDebug("The client is not capable of handling the JWT-Secured Authorization Response Mode."))
}
return jarm.EncodeParameters(jarm.Generate(ctx, h.Config, jclient, requester.GetSession(), parameters))
default:
return parameters, nil
}
}
func (h *DefaultResponseModeHandler) handleWriteAuthorizeErrorJSON(ctx context.Context, rw http.ResponseWriter, rfc *RFC6749Error) {
rw.Header().Set(consts.HeaderContentType, consts.ContentTypeApplicationJSON)
var (
data []byte
err error
)
if data, err = json.Marshal(rfc); err != nil {
if h.Config.GetSendDebugMessagesToClients(ctx) {
errorMessage := EscapeJSONString(err.Error())
http.Error(rw, fmt.Sprintf(`{"error":"server_error","error_description":"%s"}`, errorMessage), http.StatusInternalServerError)
} else {
http.Error(rw, `{"error":"server_error"}`, http.StatusInternalServerError)
}
return
}
rw.WriteHeader(rfc.CodeField)
_, _ = rw.Write(data)
}
// RFC9207ResponseModeParameterHandler adds the RFC9207
type RFC9207ResponseModeParameterHandler struct {
Config interface {
AuthorizationServerIssuerIdentificationProvider
}
}
func (h *RFC9207ResponseModeParameterHandler) ResponseModes() ResponseModeTypes {
return ResponseModeTypes{
ResponseModeDefault,
ResponseModeQuery,
ResponseModeFragment,
ResponseModeFormPost,
}
}
func (h *RFC9207ResponseModeParameterHandler) WriteParameters(ctx context.Context, requester AuthorizeRequester, parameters url.Values) {
if issuer := h.Config.GetAuthorizationServerIdentificationIssuer(ctx); len(issuer) != 0 {
parameters.Set(consts.FormParameterIssuer, issuer)
}
}
// ResponseModeHandler provides a contract for handling response modes.
type ResponseModeHandler interface {
// ResponseModes returns a set of supported response modes handled
// by the interface implementation.
//
// In an authorize request with any of the provide response modes
// methods `WriteAuthorizeResponse` and `WriteAuthorizeError` will be
// invoked to write the successful or error authorization responses respectively.
ResponseModes() ResponseModeTypes
// WriteAuthorizeResponse writes successful responses
//
// The following headers are expected to be set by implementations of this interface:
// header.Set(consts.HeaderCacheControl, consts.CacheControlNoStore)
// header.Set(consts.HeaderPragma, consts.PragmaNoCache)
WriteAuthorizeResponse(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, responder AuthorizeResponder)
// WriteAuthorizeError writes error responses
//
// The following headers are expected to be set by implementations of this interface:
// header.Set(consts.HeaderCacheControl, consts.CacheControlNoStore)
// header.Set(consts.HeaderPragma, consts.PragmaNoCache)
WriteAuthorizeError(ctx context.Context, rw http.ResponseWriter, requester AuthorizeRequester, err error)
}
type ResponseModeParameterHandler interface {
// ResponseModes returns a set of supported response modes handled
// by the interface implementation.
//
// In an authorize request with any of the provide response modes
// methods `WriteAuthorizeResponse` and `WriteAuthorizeError` will be
// invoked to write the successful or error authorization responses respectively.
ResponseModes() ResponseModeTypes
// WriteParameters is handed the parameters just before handing of to the response writer.
WriteParameters(ctx context.Context, requester AuthorizeRequester, parameters url.Values)
}
type ResponseModeTypes []ResponseModeType
func (rs ResponseModeTypes) Has(item ResponseModeType) bool {
for _, r := range rs {
if r == item {
return true
}
}
return false
}
type ResponseModeHandlerConfigurator interface {
ResponseModeParameterHandlerProvider
FormPostHTMLTemplateProvider
FormPostResponseProvider
JWTSecuredAuthorizeResponseModeIssuerProvider
JWTSecuredAuthorizeResponseModeSignerProvider
JWTSecuredAuthorizeResponseModeLifespanProvider
MessageCatalogProvider
SendDebugMessagesToClientsProvider
UseLegacyErrorFormatProvider
}
var (
_ ResponseModeHandler = (*DefaultResponseModeHandler)(nil)
)