-
Notifications
You must be signed in to change notification settings - Fork 28
/
token_endpoint.go
393 lines (354 loc) · 12.9 KB
/
token_endpoint.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
package oauth2
import (
"net/http"
vd "github.com/go-ozzo/ozzo-validation/v4"
"github.com/gofrs/uuid"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"github.com/traPtitech/traQ/repository"
"github.com/traPtitech/traQ/router/extension"
)
type oauth2ErrorResponse struct {
ErrorType string `json:"error"`
ErrorDescription string `json:"error_description,omitempty"`
ErrorURI string `json:"error_uri,omitempty"`
}
type tokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
Scope string `json:"scope,omitempty"`
}
// TokenEndpointHandler トークンエンドポイントのハンドラ
func (h *Handler) TokenEndpointHandler(c echo.Context) error {
c.Response().Header().Set("Cache-Control", "no-store")
c.Response().Header().Set("Pragma", "no-cache")
switch c.FormValue("grant_type") {
case grantTypeAuthorizationCode:
return h.tokenEndpointAuthorizationCodeHandler(c)
case grantTypePassword:
return h.tokenEndpointPasswordHandler(c)
case grantTypeClientCredentials:
return h.tokenEndpointClientCredentialsHandler(c)
case grantTypeRefreshToken:
return h.tokenEndpointRefreshTokenHandler(c)
default:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errUnsupportedGrantType})
}
}
type tokenEndpointAuthorizationCodeHandlerRequest struct {
Code string `form:"code"`
RedirectURI string `form:"redirect_uri"`
ClientID string `form:"client_id"`
ClientSecret string `form:"client_secret"`
CodeVerifier string `form:"code_verifier"`
}
func (r tokenEndpointAuthorizationCodeHandlerRequest) Validate() error {
return vd.ValidateStruct(&r,
vd.Field(&r.Code, vd.Required),
)
}
func (h *Handler) tokenEndpointAuthorizationCodeHandler(c echo.Context) error {
var req tokenEndpointAuthorizationCodeHandlerRequest
if err := extension.BindAndValidate(c, &req); err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidRequest})
}
// 認可コード確認
code, err := h.Repo.GetAuthorize(req.Code)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidGrant})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
// 認可コードは2回使えない
if err := h.Repo.DeleteAuthorize(code.Code); err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
if code.IsExpired() {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidGrant})
}
// クライアント確認
client, err := h.Repo.GetClient(code.ClientID)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
id, pw, ok := c.Request().BasicAuth()
if !ok { // Request Payload
if len(req.ClientID) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
id = req.ClientID
pw = req.ClientSecret
}
if client.ID != id || (client.Confidential && client.Secret != pw) {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
// リダイレクトURI確認
if (len(code.RedirectURI) > 0 && client.RedirectURI != req.RedirectURI) || (len(code.RedirectURI) == 0 && len(req.RedirectURI) > 0) {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidGrant})
}
// PKCE確認
if ok, _ := code.ValidatePKCE(req.CodeVerifier); !ok {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidRequest})
}
// トークン発行
newToken, err := h.Repo.IssueToken(client, code.UserID, client.RedirectURI, code.Scopes, h.AccessTokenExp, h.IsRefreshEnabled)
if err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
res := &tokenResponse{
TokenType: authScheme,
AccessToken: newToken.AccessToken,
ExpiresIn: newToken.ExpiresIn,
}
if len(code.OriginalScopes) != len(newToken.Scopes) {
res.Scope = newToken.Scopes.String()
}
if newToken.IsRefreshEnabled() {
res.RefreshToken = newToken.RefreshToken
}
return c.JSON(http.StatusOK, res)
}
type tokenEndpointPasswordHandlerRequest struct {
Scope string `form:"scope"`
Username string `form:"username"`
Password string `form:"password"`
ClientID string `form:"client_id"`
ClientSecret string `form:"client_secret"`
}
func (r tokenEndpointPasswordHandlerRequest) Validate() error {
return vd.ValidateStruct(&r,
vd.Field(&r.Username, vd.Required),
vd.Field(&r.Password, vd.Required),
)
}
func (h *Handler) tokenEndpointPasswordHandler(c echo.Context) error {
var req tokenEndpointPasswordHandlerRequest
if err := extension.BindAndValidate(c, &req); err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidRequest})
}
cid, cpw, ok := c.Request().BasicAuth()
if !ok { // Request Payload
if len(req.ClientID) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
cid = req.ClientID
cpw = req.ClientSecret
}
// クライアント確認
client, err := h.Repo.GetClient(cid)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
if client.Confidential && client.Secret != cpw {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
// ユーザー確認
user, err := h.Repo.GetUserByName(req.Username, false)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidGrant})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
if user.Authenticate(req.Password) != nil {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidGrant})
}
// 要求スコープ確認
reqScopes, err := h.splitAndValidateScope(req.Scope)
if err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
validScopes := client.GetAvailableScopes(reqScopes)
if len(reqScopes) == 0 {
validScopes = client.Scopes
} else if len(validScopes) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
// トークン発行
newToken, err := h.Repo.IssueToken(client, user.GetID(), client.RedirectURI, validScopes, h.AccessTokenExp, h.IsRefreshEnabled)
if err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
res := &tokenResponse{
TokenType: authScheme,
AccessToken: newToken.AccessToken,
ExpiresIn: newToken.ExpiresIn,
}
if len(reqScopes) != len(validScopes) {
res.Scope = newToken.Scopes.String()
}
if newToken.IsRefreshEnabled() {
res.RefreshToken = newToken.RefreshToken
}
return c.JSON(http.StatusOK, res)
}
func (h *Handler) tokenEndpointClientCredentialsHandler(c echo.Context) error {
var req struct {
Scope string `form:"scope"`
ClientID string `form:"client_id"`
ClientSecret string `form:"client_secret"`
}
if err := extension.BindAndValidate(c, &req); err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidRequest})
}
id, pw, ok := c.Request().BasicAuth()
if !ok { // Request Payload
if len(req.ClientID) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
id = req.ClientID
pw = req.ClientSecret
}
// クライアント確認
client, err := h.Repo.GetClient(id)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
if !client.Confidential {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errUnauthorizedClient})
}
if client.Secret != pw {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
// 要求スコープ確認
reqScopes, err := h.splitAndValidateScope(req.Scope)
if err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
validScopes := client.GetAvailableScopes(reqScopes)
if len(reqScopes) == 0 {
validScopes = client.Scopes
} else if len(validScopes) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
// トークン発行
newToken, err := h.Repo.IssueToken(client, uuid.Nil, client.RedirectURI, validScopes, h.AccessTokenExp, false)
if err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
res := &tokenResponse{
TokenType: authScheme,
AccessToken: newToken.AccessToken,
ExpiresIn: newToken.ExpiresIn,
}
if len(reqScopes) != len(validScopes) {
res.Scope = newToken.Scopes.String()
}
return c.JSON(http.StatusOK, res)
}
type tokenEndpointRefreshTokenHandlerRequest struct {
Scope string `form:"scope"`
RefreshToken string `form:"refresh_token"`
ClientID string `form:"client_id"`
ClientSecret string `form:"client_secret"`
}
func (r tokenEndpointRefreshTokenHandlerRequest) Validate() error {
return vd.ValidateStruct(&r,
vd.Field(&r.RefreshToken, vd.Required),
)
}
func (h *Handler) tokenEndpointRefreshTokenHandler(c echo.Context) error {
var req tokenEndpointRefreshTokenHandlerRequest
if err := extension.BindAndValidate(c, &req); err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidRequest})
}
// リフレッシュトークン確認
token, err := h.Repo.GetTokenByRefresh(req.RefreshToken)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidGrant})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
// クライアント確認
client, err := h.Repo.GetClient(token.ClientID)
if err != nil {
switch err {
case repository.ErrNotFound:
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
default:
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
}
if client.Confidential { // need to authenticate client
id, pw, ok := c.Request().BasicAuth()
if !ok { // Request Payload
if len(req.ClientID) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
id = req.ClientID
pw = req.ClientSecret
}
if client.ID != id || client.Secret != pw {
return c.JSON(http.StatusUnauthorized, oauth2ErrorResponse{ErrorType: errInvalidClient})
}
}
// 要求スコープ確認
reqScopes, err := h.splitAndValidateScope(req.Scope)
if err != nil {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
newScopes := token.GetAvailableScopes(reqScopes)
if len(reqScopes) == 0 {
newScopes = token.Scopes
} else if len(newScopes) == 0 {
return c.JSON(http.StatusBadRequest, oauth2ErrorResponse{ErrorType: errInvalidScope})
}
// トークン発行
newToken, err := h.Repo.IssueToken(client, token.UserID, token.RedirectURI, newScopes, h.AccessTokenExp, h.IsRefreshEnabled)
if err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
if err := h.Repo.DeleteTokenByRefresh(req.RefreshToken); err != nil {
h.L(c).Error(err.Error(), zap.Error(err))
return c.JSON(http.StatusInternalServerError, oauth2ErrorResponse{ErrorType: errServerError})
}
res := &tokenResponse{
TokenType: authScheme,
AccessToken: newToken.AccessToken,
ExpiresIn: newToken.ExpiresIn,
}
if len(token.Scopes) != len(newToken.Scopes) {
res.Scope = newToken.Scopes.String()
}
if newToken.IsRefreshEnabled() {
res.RefreshToken = newToken.RefreshToken
}
return c.JSON(http.StatusOK, res)
}