This repository has been archived by the owner on May 13, 2024. It is now read-only.
/
oidcmiddleware.go
338 lines (267 loc) · 9.26 KB
/
oidcmiddleware.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
/* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2023 Damian Peckett <damian@pecke.tt>.
*
* 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.
*/
package oidcmiddleware
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
"golang.org/x/oauth2"
)
// Options allows configuring the OpenID Connect middleware.
type Options struct {
// IssuerURL is the URL of the OpenID Connect issuer.
IssuerURL string
// RedirectURL is the URL to redirect the user to after they've logged in.
RedirectURL string
// ClientID is the OAuth2 client ID.
ClientID string
// ClientSecret is the OAuth2 client secret.
ClientSecret string
// MaxAge is how long the users session should be valid for.
MaxAge *time.Duration
// TLSClientConfig is the TLS configuration to use when connecting to the issuer.
TLSClientConfig *tls.Config
// DiscoverIssuer is whether to discover the issuer public URL using the OpenID Connect discovery endpoint.
// This is required if connecting to the issuer on a private URL.
DiscoverIssuer bool
}
// NewAuthMiddleware returns an echo middleware that can be used to protect routes with OpenID Connect.
func NewAuthMiddleware(ctx context.Context, e *echo.Echo, store sessions.Store, opts *Options) (echo.MiddlewareFunc, error) {
issuerURL, err := url.Parse(opts.IssuerURL)
if err != nil {
return nil, fmt.Errorf("failed to parse issuer url: %w", err)
}
transport := http.DefaultTransport
if opts.TLSClientConfig != nil {
transport.(*http.Transport).TLSClientConfig = opts.TLSClientConfig
}
if opts.DiscoverIssuer {
transport = &rewritingTransport{
transport: transport,
target: issuerURL,
}
ctx = oidc.ClientContext(ctx, &http.Client{
Transport: transport,
})
publicIssuerURL, err := discoverIssuerURL(ctx, opts.IssuerURL)
if err != nil {
return nil, fmt.Errorf("failed to discover public issuer url: %w", err)
}
ctx = oidc.InsecureIssuerURLContext(ctx, publicIssuerURL)
} else {
ctx = oidc.ClientContext(ctx, &http.Client{
Transport: transport,
})
}
provider, err := oidc.NewProvider(ctx, opts.IssuerURL)
if err != nil {
return nil, fmt.Errorf("failed to get oidc provider: %w", err)
}
oauth2Config := &oauth2.Config{
ClientID: opts.ClientID,
ClientSecret: opts.ClientSecret,
RedirectURL: opts.RedirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
verifier := provider.Verifier(&oidc.Config{
ClientID: opts.ClientID,
})
e.GET("/oauth2/auth", func(c echo.Context) error {
// 1. Check if the user is already logged in.
session, err := store.Get(c.Request(), opts.ClientID)
if err != nil {
e.Logger.Error("Failed to get/create session:", err)
return echo.ErrInternalServerError
}
// If the user is already logged in, redirect them to the homepage.
if _, ok := session.Values["email"]; ok {
return c.Redirect(http.StatusFound, "/")
}
// 2. Generate a random state parameter and store it in the users session.
state, err := generateState()
if err != nil {
e.Logger.Error("Failed to generate state:", err)
return echo.ErrInternalServerError
}
session.Values["state"] = state
if err := session.Save(c.Request(), c.Response()); err != nil {
e.Logger.Error("Failed to save session:", err)
return echo.ErrInternalServerError
}
// 3. Redirect the user to the OAuth2 provider to login.
return c.Redirect(http.StatusFound, oauth2Config.AuthCodeURL(state))
})
e.GET("/oauth2/callback", func(c echo.Context) error {
// 1. Verify the random state parameter.
session, err := store.Get(c.Request(), opts.ClientID)
if err != nil {
e.Logger.Error("Failed to get session:", err)
return echo.ErrInternalServerError
}
state, ok := session.Values["state"]
if !ok || state == "" {
e.Logger.Error("Request is missing state parameter")
return echo.ErrUnauthorized
}
delete(session.Values, "state")
if err := session.Save(c.Request(), c.Response()); err != nil {
e.Logger.Error("Failed to save session:", err)
return echo.ErrInternalServerError
}
if c.QueryParam("state") != state.(string) {
e.Logger.Error("Invalid state parameter")
return echo.ErrUnauthorized
}
ctx := oidc.ClientContext(c.Request().Context(), &http.Client{
Transport: transport,
})
// 2. Exchange the authorization code for an OAuth2 token.
oauth2Token, err := oauth2Config.Exchange(ctx, c.QueryParam("code"))
if err != nil {
e.Logger.Error("Failed to exchange token:", err)
return echo.ErrUnauthorized
}
// 3. Extract, verify, and decode the ID token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
e.Logger.Error("No \"id_token\" field in the oauth2 token")
return echo.ErrUnauthorized
}
idToken, err := verifier.Verify(ctx, rawIDToken)
if err != nil {
e.Logger.Error("Failed to verify id token:", err)
return echo.ErrUnauthorized
}
var claims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
}
if err := idToken.Claims(&claims); err != nil {
e.Logger.Error("Failed to extract claims from id token:", err)
return echo.ErrInternalServerError
}
// 4. Check that the users email has been verified.
if !claims.EmailVerified {
e.Logger.Warn("Email is not verified")
return echo.NewHTTPError(http.StatusForbidden, "email is not verified")
}
// 5. Store the verified email address in the users session.
session.Options = &sessions.Options{
Path: "/",
MaxAge: 86400, // 24 hours
HttpOnly: true,
Secure: c.Request().URL.Scheme == "https",
}
if opts.MaxAge != nil {
session.Options.MaxAge = int(opts.MaxAge.Seconds())
}
session.Values["email"] = claims.Email
// 6. Retrieve the original URL from the session and redirect the user.
originalURL := session.Values["original_url"].(string)
delete(session.Values, "original_url")
if err := session.Save(c.Request(), c.Response()); err != nil {
e.Logger.Error("Failed to save session:", err)
return echo.ErrInternalServerError
}
return c.Redirect(http.StatusFound, originalURL)
})
authMiddleware := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// 1. Check if the user is logged in.
session, err := store.Get(c.Request(), opts.ClientID)
if err != nil {
e.Logger.Error("Failed to get session:", err)
return echo.ErrInternalServerError
}
email, ok := session.Values["email"]
if !ok {
// 2. Store the original URL in the session so we can redirect the user back to it after they've logged in.
session.Values["original_url"] = c.Request().URL.String()
if err := session.Save(c.Request(), c.Response()); err != nil {
e.Logger.Error("Failed to save session:", err)
return echo.ErrInternalServerError
}
// 3. Begin the OAuth2 login flow.
return c.Redirect(http.StatusFound, "/oauth2/auth")
}
c.Set("email", email.(string))
return next(c)
}
}
return authMiddleware, nil
}
func discoverIssuerURL(ctx context.Context, issuerURL string) (string, error) {
u, err := url.Parse(issuerURL)
if err != nil {
return "", fmt.Errorf("failed to parse issuer url: %w", err)
}
u.Path = path.Join(u.Path, "/.well-known/openid-configuration")
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
resp, err := getClient(ctx).Do(req)
if err != nil {
return "", fmt.Errorf("failed to get openid configuration: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to get openid configuration, unexpected status code: %d", resp.StatusCode)
}
var configJSON struct {
Issuer string `json:"issuer"`
}
if err := json.NewDecoder(resp.Body).Decode(&configJSON); err != nil {
return "", fmt.Errorf("failed to unmarshal openid configuration: %w", err)
}
return configJSON.Issuer, nil
}
func getClient(ctx context.Context) *http.Client {
if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
return c
}
return http.DefaultClient
}
func generateState() (string, error) {
var stateBytes = make([]byte, 32)
if _, err := rand.Read(stateBytes); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(stateBytes), nil
}
// rewritingTransport is an http.RoundTripper that rewrites the host of all requests to a given host.
// this allows using private issuer URLs.
type rewritingTransport struct {
transport http.RoundTripper
target *url.URL
}
func (t *rewritingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.URL.Scheme = t.target.Scheme
req.URL.Host = t.target.Host
return t.transport.RoundTrip(req)
}