-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.go
768 lines (664 loc) · 22.1 KB
/
server.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
package main
import (
"bytes"
"encoding/json"
"errors"
"html"
"io"
"log"
"math"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/Masterminds/sprig/v3"
jwtverifier "github.com/okta/okta-jwt-verifier-golang/v2"
)
const sock = "/var/run/auth.sock"
type config struct {
clientID string //CLIENT_ID
clientSecret string //CLIENT_SECRET
endpointAuthorize string //ENDPOINT_AUTHORIZE
endpointLogout string //ENDPOINT_LOGOUT
endpointToken string //ENDPOINT_TOKEN
httpClient *http.Client
issuer string //ISSUER
ssoPath string //SSO_PATH
authScope string //AUTH_SCOPE
verifier *jwtverifier.JwtVerifier
}
var templateCache = make(map[string]*template.Template)
var templateCacheMu = &sync.Mutex{}
type jwtResponse struct {
IDToken string `json:"id_token"`
}
type metadataResponse struct {
EndpointAuthorize string `json:"authorization_endpoint"`
EndpointLogout string `json:"end_session_endpoint"`
EndpointToken string `json:"token_endpoint"`
}
func getConfig() *config {
//Populate config from env vars
clientID := os.Getenv("CLIENT_ID")
if clientID == "" {
log.Fatalln("Must specify CLIENT_ID env variable - Client ID can be found on the 'General' tab of the Web application that you created earlier in the Okta Developer Console.")
}
clientSecret := os.Getenv("CLIENT_SECRET")
if clientSecret == "" {
log.Fatalln("Must specify CLIENT_SECRET env variable - Client Secret be found on the 'General' tab of the Web application that you created earlier in the Okta Developer Console.")
}
issuer := strings.TrimRight(os.Getenv("ISSUER"), "/")
if issuer == "" {
log.Fatalln("This is the URL of the authorization server that will perform authentication. All Developer Accounts have a 'default' authorization server. The issuer is a combination of your Org URL (found in the upper right of the console home page) and /oauth2/default. For example, https://dev-1234.oktapreview.com/oauth2/default.")
}
_, err := url.Parse(issuer)
if err != nil {
log.Fatalf("ISSUER is not a valid URL, %v", issuer)
}
ssoPath := os.Getenv("SSO_PATH")
if ssoPath == "" {
ssoPath = "/sso/"
} else {
ssoPath = "/" + strings.Trim(ssoPath, "/") + "/"
}
requestTimeOutSeconds := time.Second * time.Duration(30)
requestTimeOut := os.Getenv("REQUEST_TIMEOUT")
if requestTimeOut != "" {
requestTimeoutInt, err := strconv.Atoi(os.Getenv("REQUEST_TIMEOUT"))
if err != nil {
log.Println("Unable to parse REQUEST_TIMEOUT env variable, using a default of 30 seconds")
} else {
requestTimeOutSeconds = time.Second * time.Duration(requestTimeoutInt)
}
}
authScope := os.Getenv("AUTH_SCOPE")
if authScope == "" {
authScope = "openid profile"
} else {
if !strings.Contains(authScope, "openid") {
log.Fatalln("AUTH_SCOPE must contain openid")
}
}
httpClient := &http.Client{
Timeout: requestTimeOutSeconds,
}
wellKnown := issuer + "/.well-known/openid-configuration"
metadata, err := getMetadata(httpClient, wellKnown)
if err != nil {
log.Fatalf("Unable to get issuer metadata from Okta, %v", wellKnown)
}
endpointAuthorize := os.Getenv("ENDPOINT_AUTHORIZE")
if endpointAuthorize == "" {
endpointAuthorize = metadata.EndpointAuthorize
} else {
_, err := url.Parse(issuer)
if err != nil {
log.Fatalf("ENDPOINT_AUTHORIZE is not a valid URL, %v", endpointAuthorize)
}
}
endpointLogout := os.Getenv("ENDPOINT_LOGOUT")
if endpointLogout == "" {
endpointLogout = metadata.EndpointLogout
} else {
_, err := url.Parse(issuer)
if err != nil {
log.Fatalf("ENDPOINT_LOGOUT is not a valid URL, %v", endpointLogout)
}
}
endpointToken := os.Getenv("ENDPOINT_TOKEN")
if endpointToken == "" {
endpointToken = metadata.EndpointToken
} else {
_, err := url.Parse(issuer)
if err != nil {
log.Fatalf("ENDPOINT_TOKEN is not a valid URL, %v", endpointToken)
}
}
//Initialize validator
toValidate := map[string]string{}
toValidate["iss"] = issuer
toValidate["aud"] = clientID
toValidate["nonce"] = "123"
jwtverifierSetup := jwtverifier.JwtVerifier{
Issuer: issuer,
ClaimsToValidate: toValidate,
}
verifier, err := jwtverifierSetup.New()
if err != nil {
log.Fatalf("Unable to create JWT verifier: %v", err)
}
return &config{
clientID: clientID,
clientSecret: clientSecret,
endpointAuthorize: endpointAuthorize,
endpointLogout: endpointLogout,
endpointToken: endpointToken,
httpClient: httpClient,
issuer: issuer,
ssoPath: ssoPath,
authScope: authScope,
verifier: verifier,
}
}
func main() {
runServer(getConfig())
}
func runServer(conf *config) {
//Validate cookie on /auth/validate requests
http.HandleFunc("/auth/validate", func(w http.ResponseWriter, r *http.Request) {
validateCookieHandler(w, r, conf)
})
//Authorization code callback
http.HandleFunc(conf.ssoPath+"authorization-code/callback", func(w http.ResponseWriter, r *http.Request) {
callbackHandler(w, r, conf)
})
//Refresh check
http.HandleFunc(conf.ssoPath+"refresh/check", func(w http.ResponseWriter, r *http.Request) {
refreshCheckHandler(w, r, conf)
})
http.HandleFunc(conf.ssoPath+"refresh/initiate", func(w http.ResponseWriter, r *http.Request) {
refreshInitiateHandler(w, r, conf)
})
//Refresh done
http.HandleFunc(conf.ssoPath+"refresh/done", func(w http.ResponseWriter, r *http.Request) {
refreshDoneHandler(w, r, conf)
})
//Logout
http.HandleFunc(conf.ssoPath+"logout", func(w http.ResponseWriter, r *http.Request) {
logoutHandler(w, r, conf)
})
//Error
http.HandleFunc(conf.ssoPath+"error", func(w http.ResponseWriter, r *http.Request) {
errorHandler(w, r, conf)
})
//Listen on unix socket instead of http
removeSockIfExists()
unixListener, err := net.Listen("unix", sock)
if err != nil {
log.Fatal(err)
}
defer removeSockIfExists()
if err = os.Chmod(sock, 0666); err != nil {
log.Fatal(err)
}
err = http.Serve(unixListener, nil)
if err != nil {
log.Fatalf("Error serving on socket, err: %v", err)
}
}
// validateCookieHandler calls the okta api to validate the cookie
func validateCookieHandler(w http.ResponseWriter, r *http.Request, conf *config) {
// initialize headers
w.Header().Set("X-Auth-Request-Redirect", "")
w.Header().Set("X-Auth-Request-User", "")
tokenCookie, err := r.Cookie(getCookieName(r))
switch {
case errors.Is(err, http.ErrNoCookie):
w.Header().Set("X-Auth-Request-Redirect", redirectURL(r, conf, r.Header.Get("X-Okta-Nginx-Request-Uri")))
w.WriteHeader(http.StatusUnauthorized)
return
case err != nil:
log.Printf("validateCookieHandler: Error parsing cookie, %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
jwt, err := conf.verifier.VerifyIdToken(tokenCookie.Value)
if err != nil {
w.Header().Set("X-Auth-Request-Redirect", redirectURL(r, conf, r.Header.Get("X-Okta-Nginx-Request-Uri")))
w.WriteHeader(http.StatusUnauthorized)
return
}
username, ok := jwt.Claims["preferred_username"]
if !ok {
log.Printf("validateCookieHandler: Claim 'preferred_username' not included in identity token, %v", tokenCookie.Value)
w.WriteHeader(http.StatusInternalServerError)
return
}
usernameStr, ok := username.(string)
if !ok {
log.Printf("validateCookieHandler: Unable to convert 'preferred_username' to string in identity token, %v", tokenCookie.Value)
w.WriteHeader(http.StatusInternalServerError)
return
}
validateClaimsTemplate := strings.TrimSpace(r.Header.Get("X-Okta-Nginx-Validate-Claims-Template"))
if validateClaimsTemplate != "" {
t, err := getTemplate(validateClaimsTemplate)
if err != nil {
log.Printf("validateCookieHandler: validateClaimsTemplate failed to parse template: '%v', error: %v", validateClaimsTemplate, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var resultBytes bytes.Buffer
if err := t.Execute(&resultBytes, jwt.Claims); err != nil {
claimsJSON, _ := json.Marshal(jwt.Claims)
log.Printf("validateCookieHandler: validateClaimsTemplate failed to execute template: '%v', data: '%v', error: '%v'", validateClaimsTemplate, claimsJSON, err)
w.WriteHeader(http.StatusUnauthorized)
return
}
resultString := strings.ToLower(strings.TrimSpace(resultBytes.String()))
if resultString != "true" && resultString != "1" {
log.Printf("validateCookieHandler: validateClaimsTemplate template: '%v', result: '%v', preferred_username: '%v'", validateClaimsTemplate, resultString, usernameStr)
w.WriteHeader(http.StatusUnauthorized)
return
}
}
setHeaderNames := strings.Split(r.Header.Get("X-Okta-Nginx-Proxy-Set-Header-Names"), ",")
setHeaderValues := strings.Split(r.Header.Get("X-Okta-Nginx-Proxy-Set-Header-Values"), ",")
if setHeaderNames[0] != "" && setHeaderValues[0] != "" && len(setHeaderNames) == len(setHeaderValues) {
for i := 0; i < len(setHeaderNames); i++ {
t, err := getTemplate(setHeaderValues[i])
if err != nil {
log.Printf("validateCookieHandler: setHeaderValues failed to parse template: '%v', error: %v", validateClaimsTemplate, err)
continue
}
var resultBytes bytes.Buffer
if err := t.Execute(&resultBytes, jwt.Claims); err != nil {
claimsJSON, _ := json.Marshal(jwt.Claims)
log.Printf("validateCookieHandler: setHeaderValues failed to execute template: '%v', data: '%v', error: '%v'", validateClaimsTemplate, claimsJSON, err)
continue
}
resultString := strings.ToLower(strings.TrimSpace(resultBytes.String()))
w.Header().Set(setHeaderNames[i], resultString)
}
}
w.Header().Set("X-Auth-Request-User", usernameStr)
w.WriteHeader(http.StatusOK)
}
func callbackHandler(w http.ResponseWriter, r *http.Request, conf *config) {
//Read auth code from URL Param
params := r.URL.Query()
code := params.Get("code")
ssoErr := params.Get("error")
unsetCookie := &http.Cookie{
Domain: getCookieDomain(r),
Name: getCookieName(r),
Value: "",
Path: "/",
HttpOnly: true,
}
//Redirect if error in param
if ssoErr != "" {
http.SetCookie(w, unsetCookie)
http.Redirect(w, r, getRequestOriginURL(r).String()+conf.ssoPath+"error?error="+url.QueryEscape(ssoErr), http.StatusTemporaryRedirect)
return
}
//Check for no code and no error to guard against ddos
if code == "" {
http.SetCookie(w, unsetCookie)
w.WriteHeader(http.StatusUnauthorized)
return
}
jwtStr, err := getJWT(r, code, conf)
//Redirect if error getting JWT
if err != nil {
log.Printf("callbackHandler: Error in getJWT, %v", err)
http.SetCookie(w, unsetCookie)
http.Redirect(w, r, getRequestOriginURL(r).String()+conf.ssoPath+"error?error="+url.QueryEscape(err.Error()), http.StatusTemporaryRedirect)
return
}
jwt, err := conf.verifier.VerifyIdToken(jwtStr)
if err != nil {
log.Printf("refreshHandler: JWT Validation Error, %v", err)
http.SetCookie(w, unsetCookie)
http.Redirect(w, r, getRequestOriginURL(r).String()+conf.ssoPath+"error?error="+url.QueryEscape(err.Error()), http.StatusTemporaryRedirect)
return
}
exp, ok := jwt.Claims["exp"]
if !ok {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("refreshHandler: Claim 'exp' not included in identity token, %v", jwtStr)
return
}
expFloat, ok := exp.(float64)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("refreshHandler: Unable to convert 'exp' to float64")
return
}
//Set cookie if code valid
cookie := &http.Cookie{
Domain: getCookieDomain(r),
Expires: time.Unix(int64(expFloat), 0),
Name: getCookieName(r),
Value: jwtStr,
Path: "/",
HttpOnly: true,
}
http.SetCookie(w, cookie)
//Redirect to requested page
requestOrigin := getRequestOriginURL(r).String()
state := params.Get("state")
stateURL, err := url.Parse(state)
if err != nil {
log.Printf("refreshHandler: state paramater '%v' is not a valid URL", state)
http.Redirect(w, r, requestOrigin+conf.ssoPath+"error?error="+url.QueryEscape("Unauthorized"), http.StatusTemporaryRedirect)
return
}
if (stateURL.Scheme != "" || stateURL.Host != "") && !urlMatchesCookieDomain(stateURL, getCookieDomain(r)) {
log.Printf("refreshHandler: state paramater '%v' is not valid for COOKIE_DOMAIN '%v'", state, getCookieDomain(r))
http.Redirect(w, r, requestOrigin+conf.ssoPath+"error?error="+url.QueryEscape("Unauthorized"), http.StatusTemporaryRedirect)
return
}
http.Redirect(w, r, state, http.StatusTemporaryRedirect)
}
type refreshCheckResponse struct {
ExpSeconds int `json:"expSeconds"`
}
func refreshCheckHandler(w http.ResponseWriter, r *http.Request, conf *config) {
tokenCookie, err := r.Cookie(getCookieName(r))
switch {
case errors.Is(err, http.ErrNoCookie):
log.Printf("refreshCheckHandler: No Cookie")
w.WriteHeader(http.StatusUnauthorized)
return
case err != nil:
log.Printf("refreshCheckHandler: Error parsing cookie, %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
jwt, err := conf.verifier.VerifyIdToken(tokenCookie.Value)
if err != nil {
log.Printf("refreshCheckHandler: JWT Validation Error, %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
exp, ok := jwt.Claims["exp"]
if !ok {
log.Printf("refreshCheckHandler: Claim 'exp' not included in identity token, %v", tokenCookie.Value)
w.WriteHeader(http.StatusInternalServerError)
return
}
expFloat, ok := exp.(float64)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("refreshCheckHandler: Unable to convert 'exp' to float64")
return
}
js, err := json.Marshal(&refreshCheckResponse{
ExpSeconds: int(math.Max(0.0, math.Ceil(expFloat-float64(time.Now().UTC().Unix())))),
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("refreshCheckHandler: Unable to marshal response to JSON")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, err = w.Write(js)
if err != nil {
log.Printf("refreshCheckHandler: error when writing output, %v", err)
return
}
}
func refreshInitiateHandler(w http.ResponseWriter, r *http.Request, conf *config) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
http.Redirect(w, r, redirectURL(r, conf, conf.ssoPath+"refresh/done"), http.StatusTemporaryRedirect)
}
func refreshDoneHandler(w http.ResponseWriter, r *http.Request, conf *config) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err := io.WriteString(w, `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SSO Refresh</title>
<script>
window.parent.postMessage("ssoRefreshDone", window.location.protocol + "//" + window.location.host);
</script>
</head>
<body>
SSO Refresh
</body>
</html>
`)
if err != nil {
log.Printf("refreshDoneHandler: error when writing string to output, %v", err)
return
}
}
func logoutHandler(w http.ResponseWriter, r *http.Request, conf *config) {
unsetCookie := &http.Cookie{
Domain: getCookieDomain(r),
Name: getCookieName(r),
Value: "",
Path: "/",
HttpOnly: true,
}
logoutRedirect := getLogoutRedirectURL(r).String()
tokenCookie, err := r.Cookie(unsetCookie.Name)
if err != nil {
http.Redirect(w, r, logoutRedirect, http.StatusTemporaryRedirect)
}
http.SetCookie(w, unsetCookie)
http.Redirect(w, r,
conf.endpointLogout+
"?id_token_hint="+url.QueryEscape(tokenCookie.Value)+
"&post_logout_redirect_uri="+url.QueryEscape(logoutRedirect),
http.StatusTemporaryRedirect)
}
func errorHandler(w http.ResponseWriter, r *http.Request, conf *config) {
params := r.URL.Query()
ssoErr := params.Get("error")
w.WriteHeader(http.StatusUnauthorized)
_, err := io.WriteString(w, `
<!DOCTYPE html>
<html>
<head>
<title>Sign-On Error</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
pre {
border: 1px solid #000;
padding: 3px;
background-color: #dedede;
}
</style>
</head>
<body>
<h1>Sign-On Error</h1>
<p>An error occurred with sign-on</p>
<p><strong>Error Details:</strong></p>
<pre>`+html.EscapeString(ssoErr)+`</pre>
</body>
</html>
`)
if err != nil {
log.Printf("errorHandler: error when writing string to output, %v", err)
return
}
}
// getJWT queries the okta server with an access code. A valid request will return a JWT identity token.
func getJWT(r *http.Request, code string, conf *config) (string, error) {
loginRedirect := getLoginRedirectURL(r).String()
reqBody := []byte("code=" + url.QueryEscape(code) +
"&client_id=" + url.QueryEscape(conf.clientID) +
"&client_secret=" + url.QueryEscape(conf.clientSecret) +
"&redirect_uri=" + url.QueryEscape(loginRedirect) +
"&grant_type=authorization_code" +
"&scope=" + url.QueryEscape(conf.authScope))
req, err := http.NewRequest("POST", conf.endpointToken, bytes.NewBuffer(reqBody))
if err != nil {
return "", err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := conf.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
//200 == authorization succeeded
if resp.StatusCode == http.StatusOK {
jsonResponse := &jwtResponse{}
err = json.Unmarshal(bodyBytes, &jsonResponse)
if err != nil {
return "", err
}
return jsonResponse.IDToken, nil
}
bodyStr := string(bodyBytes)
return "", errors.New(bodyStr)
}
func getMetadata(httpClient *http.Client, wellKnown string) (*metadataResponse, error) {
req, err := http.NewRequest("GET", wellKnown, nil)
if err != nil {
return nil, err
}
req.Header.Add("Accept", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusOK {
jsonResponse := &metadataResponse{}
err = json.Unmarshal(bodyBytes, &jsonResponse)
if err != nil {
return nil, err
}
return jsonResponse, nil
}
bodyStr := string(bodyBytes)
return nil, errors.New(bodyStr)
}
func removeSockIfExists() {
_, err := os.Stat(sock)
if err == nil {
err = os.Remove(sock)
if err != nil {
log.Fatal(err)
}
}
}
func urlMatchesCookieDomain(matchURL *url.URL, cookieDomain string) bool {
return cookieDomain == "" || matchURL.Hostname() == cookieDomain || strings.HasSuffix(matchURL.Hostname(), "."+cookieDomain)
}
func redirectURL(r *http.Request, conf *config, requestURI string) string {
requestURLStr := requestURI
requestOriginURL := getRequestOriginURL(r)
if requestOriginURL == nil {
log.Printf("redirectURL: redirect will not include origin")
} else {
if urlMatchesCookieDomain(requestOriginURL, getCookieDomain(r)) {
requestURLStr = requestOriginURL.String() + requestURLStr
} else {
log.Printf("redirectURL: header 'X-Forwarded-Host' hostname '%v' is not valid for COOKIE_DOMAIN '%v'", requestOriginURL.Hostname(), getCookieDomain(r))
log.Printf("redirectURL: redirect will not include origin")
}
}
appPostLoginURL := getAppPostLoginURL(r)
if appPostLoginURL != nil {
appPostLoginStruct := *appPostLoginURL
appPostLoginURL := &appPostLoginStruct
q := appPostLoginURL.Query()
q.Set("state", requestURLStr)
appPostLoginURL.RawQuery = q.Encode()
requestURLStr = appPostLoginURL.String()
}
loginRedirect := getLoginRedirectURL(r).String()
return conf.endpointAuthorize +
"?client_id=" + url.QueryEscape(conf.clientID) +
"&response_type=code" +
"&scope=" + url.QueryEscape(conf.authScope) +
"&nonce=123" +
"&redirect_uri=" + url.QueryEscape(loginRedirect) +
"&state=" + url.QueryEscape(requestURLStr)
}
func getAppPostLoginURL(r *http.Request) *url.URL {
appPostLogin := os.Getenv("APP_POST_LOGIN_URL")
if appPostLogin != "" {
appPostLoginURL, err := url.Parse(appPostLogin)
if err != nil {
log.Printf("APP_POST_LOGIN_URL is not a valid URL, %v", appPostLogin)
return nil
}
return appPostLoginURL
}
return nil
}
func getRequestOriginURL(r *http.Request) *url.URL {
requestScheme := r.Header.Get("X-Forwarded-Proto")
requestHost := r.Header.Get("X-Forwarded-Host")
if requestScheme != "" && requestHost != "" {
requestOrigin := requestScheme + "://" + requestHost
requestOriginURL, err := url.Parse(requestOrigin)
if err != nil {
log.Printf("getRequestOriginURL: headers 'X-Forwarded-Proto' and 'X-Forwarded-Host' form invalid origin '%v'", requestOrigin)
return &url.URL{}
}
return requestOriginURL
}
log.Printf("getRequestOriginURL: headers 'X-Forwarded-Proto' and/or 'X-Forwarded-Host' not set")
return &url.URL{}
}
func getCookieName(r *http.Request) string {
cookieName := r.Header.Get("X-Okta-Nginx-Cookie-Name")
if cookieName == "" {
cookieName = "okta-jwt"
}
return cookieName
}
func getCookieDomain(r *http.Request) string {
return strings.TrimLeft(r.Header.Get("X-Okta-Nginx-Cookie-Domain"), ".")
}
func getLoginRedirectURL(r *http.Request) *url.URL {
loginRedirect := r.Header.Get("X-Okta-Nginx-Login-Redirect-Url")
if loginRedirect == "" {
log.Printf("Must specify LOGIN_REDIRECT_URL env variable - These can be found on the 'General' tab of the Web application that you created earlier in the Okta Developer Console.")
return &url.URL{}
}
loginRedirectURL, err := url.Parse(loginRedirect)
if err != nil {
log.Printf("LOGIN_REDIRECT_URL is not a valid URL, %v", loginRedirect)
return &url.URL{}
}
return loginRedirectURL
}
func getLogoutRedirectURL(r *http.Request) *url.URL {
logoutRedirect := r.Header.Get("X-Okta-Nginx-Logout-Redirect-Url")
logoutRedirectURL := &url.URL{}
if logoutRedirect != "" {
var err error
logoutRedirectURL, err = url.Parse(logoutRedirect)
if err != nil {
log.Printf("LOGOUT_REDIRECT_URL is not a valid URL, %v", logoutRedirect)
logoutRedirectURL = &url.URL{}
}
}
if logoutRedirectURL.Scheme == "" || logoutRedirectURL.Host == "" {
requestOriginURL := getRequestOriginURL(r)
logoutRedirectURL.Scheme = requestOriginURL.Scheme
logoutRedirectURL.Host = requestOriginURL.Host
}
return logoutRedirectURL
}
func getTemplate(templateText string) (*template.Template, error) {
templateCacheMu.Lock()
defer templateCacheMu.Unlock()
t, ok := templateCache[templateText]
if ok {
return t, nil
}
t, err := template.New("").Funcs(sprig.TxtFuncMap()).Parse(templateText)
if err != nil {
return nil, err
}
return t, nil
}