-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-frontend.go
More file actions
403 lines (328 loc) · 12.8 KB
/
Copy pathexample-frontend.go
File metadata and controls
403 lines (328 loc) · 12.8 KB
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
/* author: B1 Systems GmbH
* authoremail: info@b1-systems.de
* license: MIT License <https://opensource.org/licenses/MIT>
* summary: OpenID Connect example
* */
/* 1. Demonstration of OAuth2 Authorization Code Grant
See also: https://oauth.net/2/grant-types/authorization-code/
2. Demonstration of "state" parameter to authentication code request and authorization response
See also: https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes
3. Demonstration of "nonce" parameter to authentication code request and ID token claim
See also: https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes
4. Demonstration of "code_challenge" parameter to authentication code request and
"code_verifier" parameter to token exchange (Proof Key for Code Exchange, PKCE)
See also: https://oauth.net/2/pkce/
See also (code example): https://github.com/zjutjh/User-Center/blob/main/test/test_client.go
5. Demonstration of OpenID Connect Back-Channel Logout 1.0
See also: https://openid.net/specs/openid-connect-backchannel-1_0.html */
package main
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/kataras/go-sessions/v3"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/creasty/defaults"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"example-frontend/ini"
"example-frontend/secret"
)
type PageData struct{
Title string `default:"example-frontend"`
User string `default:""`
AccessToken string `default:""`
IDToken string `default:""`
Claims string `default:""`
ExampleBackend string `default:""`
ExampleResource string `default:""`
}
var (
clientName = "example-frontend"
clientID = ""
clientSecret = ""
providerUrl = ""
homeUrl = ""
backendUrl = ""
resourceUrl = ""
listenAddress = ""
)
func randString(nByte int) (string, error) {
b := make([]byte, nByte)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func GenerateCodeVerifier(length int) (string, error) {
if length > 128 {
length = 128
} else if length < 43 {
length = 43
}
result, err := randString(length)
if err != nil {
log.Printf("Could not generate random string of length %d for PKCE code verifier", length)
return result, err
}
return result, nil
}
func ComputePkceChallenge(verifier string) string {
sum := sha256.Sum256([]byte(verifier))
challenge := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(sum[:])
return (challenge)
}
func redirectToLogin(config oauth2.Config, currentSession *sessions.Session, w http.ResponseWriter, r *http.Request) {
state, err := randString(16)
if err != nil {
log.Fatal(err)
http.Error(w, "Internal error", http.StatusInternalServerError)
} else {
nonce, err := randString(16)
if err != nil {
log.Fatal(err)
http.Error(w, "Internal error", http.StatusInternalServerError)
} else {
codeVerifier, err := GenerateCodeVerifier(43)
if err != nil {
log.Fatal(err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
codeChallenge := ComputePkceChallenge(codeVerifier)
currentSession.Set("state", state)
currentSession.Set("nonce", nonce)
currentSession.Set("codeVerifier", codeVerifier)
url := config.AuthCodeURL(
state,
oidc.Nonce(nonce),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
oauth2.SetAuthURLParam("code_challenge", codeChallenge))
oauth2.SetAuthURLParam("claims", "{\"id_token\":{\"acr\":{\"essential\": true,\"values\": [\"gold\"]}}}")
oauth2.SetAuthURLParam("test", "xyz")
http.Redirect(w, r, url, http.StatusFound)
}
}
}
func main() {
arr := []ini.Ref{
{Name: "clientID", Value: &clientID},
{Name: "clientSecret", Value: &clientSecret},
{Name: "providerUrl", Value: &providerUrl},
{Name: "homeUrl", Value: &homeUrl},
{Name: "backendUrl", Value: &backendUrl},
{Name: "resourceUrl", Value: &resourceUrl},
{Name: "listenAddress", Value: &listenAddress}}
ini.ReadIni(clientName, arr)
content, err := secret.ReadSecret("clientSecret")
if err == nil {
clientSecret = content
}
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, providerUrl)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
idTokenVerifyerConfig := &oidc.Config{
ClientID: clientID,
}
idTokenVerifier := provider.Verifier(idTokenVerifyerConfig)
logoutTokenVerifyerConfig := &oidc.Config{
ClientID: clientID,
SkipExpiryCheck: true,
}
logoutTokenVerifier := provider.Verifier(logoutTokenVerifyerConfig)
oidc_sid_to_session := make(map[string]string)
config := oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Endpoint: provider.Endpoint(),
RedirectURL: homeUrl + "/auth/oidc/callback",
Scopes: []string{oidc.ScopeOpenID, "profile", "email", "roles"},
}
sess := sessions.New(sessions.Config{
Cookie: clientID,
Expires: time.Hour * 2,
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
currentSession := sess.Start(w, r)
if auth, _ := currentSession.GetBoolean("authenticated"); !auth {
redirectToLogin(config, currentSession, w, r);
} else {
access_token := currentSession.GetString("access_token")
id_token := currentSession.GetString("id_token")
idToken, err := idTokenVerifier.Verify(ctx, id_token)
if err != nil {
currentSession.Set("authenticated", false)
log.Printf("Unable to verify ID token: %s; redirecting user agent to login", err)
redirectToLogin(config, currentSession, w, r);
} else {
pageData := PageData{}
defaults.Set(&pageData)
pageData.IDToken = id_token
err = idToken.VerifyAccessToken(access_token)
if err != nil {
currentSession.Set("authenticated", false)
log.Printf("Unable to verify access token: %s; redirecting user agent to login", err)
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
pageData.AccessToken = access_token
var claims struct {
Sid string `json:"sid"`
Expires int64 `json:"exp"`
Audience []string `json:"aud"`
PreferredUsername string `json:"preferred_username"`
Email string `json:"email"`
Verified bool `json:"email_verified"`
}
if err := idToken.Claims(&claims); err != nil {
log.Printf("Unable to parse claims from ID token: %s", err)
log.Printf("ID token: %s", id_token)
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
pageData.Claims = fmt.Sprintf(
"sid = %s\r\n" +
"exp = %s\r\n" +
"aud = %s\r\n" +
"preferred_username = %s\r\n" +
"email = %s\r\n" +
"email_verified = %t\r\n\r\n",
claims.Sid,
time.Unix(claims.Expires, 0).UTC(),
claims.Audience,
claims.PreferredUsername,
claims.Email,
claims.Verified)
pageData.User = claims.PreferredUsername
// Remember OIDC session ID -> Kataras session ID
oidc_sid_to_session[claims.Sid] = currentSession.ID()
req, err := http.NewRequest("GET", backendUrl, nil)
req.Header = http.Header{
"Authorization": {"Bearer " + id_token},
}
client := http.Client{}
res , err := client.Do(req)
if err != nil {
log.Printf("Web request to %s failed: %s (status: %d)", backendUrl, err, res.StatusCode)
pageData.ExampleBackend = "Making web request to " + backendUrl + " failed."
} else {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Reading result of web request to %s failed: %s (status: %d)", backendUrl, err, res.StatusCode)
pageData.ExampleBackend = "Reading result of web request to " + backendUrl + " failed."
} else {
sb := string(body)
pageData.ExampleBackend = sb
}
}
req, err = http.NewRequest("GET", resourceUrl, nil)
req.Header = http.Header{
"Authorization": {"Bearer " + access_token},
}
res , err = client.Do(req)
if err != nil {
log.Printf("Web request to %s failed: %s (status: %d)", resourceUrl, err, res.StatusCode)
pageData.ExampleResource = "Making web request to " + resourceUrl + " failed."
} else {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Reading result of web request to %s failed: %s (status: %d)", resourceUrl, err, res.StatusCode)
pageData.ExampleResource = "Reading result of web request to " + resourceUrl + " failed."
} else {
sb := string(body)
pageData.ExampleResource = sb
log.Printf("Processed web request for /")
}
}
}
}
tpl := template.Must(template.ParseFiles("views/index.html"))
_ = tpl.Execute(w, pageData)
}
}
})
http.HandleFunc("/auth/oidc/callback", func(w http.ResponseWriter, r *http.Request) {
currentSession := sess.Start(w, r)
state := currentSession.GetString("state")
if r.URL.Query().Get("state") != state {
log.Printf("\"state\" did not match, possible clickjack attempt")
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
codeVerifier := currentSession.GetString("codeVerifier")
if err != nil {
log.Printf("\"codeVerifier\" not set, possible clickjack attempt")
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
oauth2Token, err := config.Exchange(
ctx,
r.URL.Query().Get("code"),
oauth2.SetAuthURLParam("code_verifier", codeVerifier))
if err != nil {
log.Printf("Failed to exchange token: %s", err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
} else {
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
log.Printf("No id_token field in oauth2 token")
http.Error(w, "Internal server error", http.StatusInternalServerError)
} else {
idToken, err := idTokenVerifier.Verify(ctx, rawIDToken)
if err != nil {
log.Printf("Failed to verify ID Token: %s", err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
} else {
nonce := currentSession.GetString("nonce")
if idToken.Nonce != nonce {
log.Printf("\"nonce\" did not match, possible clickjack attempt")
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
currentSession.Set("authenticated", true)
currentSession.Set("access_token", oauth2Token.AccessToken);
currentSession.Set("id_token", rawIDToken);
http.Redirect(w, r, homeUrl, http.StatusFound)
log.Printf("Processed web request for /auth/oidc/callback")
}
}
}
}
}
}
})
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
logout_token := r.Form.Get("logout_token")
log.Printf("The /logout handler was called; logout_token = %s", string(logout_token))
if logoutToken, err := logoutTokenVerifier.Verify(ctx, logout_token) ; err != nil {
log.Printf("logout_token could not be verified: %s", err)
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
var claims struct {
Sid string `json:"sid"`
}
if err := logoutToken.Claims(&claims); err != nil {
log.Printf("Unable to parse claims from ID token: %s", err)
http.Error(w, "Bad request", http.StatusBadRequest)
} else {
log.Printf("Received backchannel logout request for sid = %s", claims.Sid)
if session_id, ok := oidc_sid_to_session[claims.Sid] ; ok {
sess.DestroyByID(session_id)
log.Printf("Requested destruction of browser session %s (OIDC sid=%s)", session_id, claims.Sid)
} else {
log.Printf("No browser session found for sid = %s", claims.Sid)
}
}
}
})
log.Printf("Listening on http://%s/", listenAddress)
log.Fatal(http.ListenAndServe(listenAddress, nil))
}
/* vim: set tabstop=2 shiftwidth=2 softtabstop=2 expandtab: */