forked from noelcatt/traefik-forward-auth
-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
228 lines (193 loc) · 5.86 KB
/
main.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
package main
import (
"fmt"
"time"
"strings"
"net/url"
"net/http"
"github.com/namsral/flag"
"github.com/op/go-logging"
)
// Vars
var fw *ForwardAuth;
var log = logging.MustGetLogger("traefik-forward-auth")
// Primary handler
func handler(w http.ResponseWriter, r *http.Request) {
// Parse uri
uri, err := url.Parse(r.Header.Get("X-Forwarded-Uri"))
if err != nil {
log.Error("Error parsing url")
http.Error(w, "Service unavailable", 503)
return
}
// Handle callback
if uri.Path == fw.Path {
handleCallback(w, r, uri.Query())
return
}
// Get auth cookie
c, err := r.Cookie(fw.CookieName)
if err != nil {
// Error indicates no cookie, generate nonce
err, nonce := fw.Nonce()
if err != nil {
log.Error("Error generating nonce")
http.Error(w, "Service unavailable", 503)
return
}
// Set the CSRF cookie
http.SetCookie(w, fw.MakeCSRFCookie(r, nonce))
log.Debug("Set CSRF cookie and redirecting to google login")
// Forward them on
http.Redirect(w, r, fw.GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
return
}
// Validate cookie
valid, email, err := fw.ValidateCookie(r, c)
if !valid {
log.Debugf("Invalid cookie: %s", err)
http.Error(w, "Not authorized", 401)
return
}
// Validate user
valid = fw.ValidateEmail(email)
if !valid {
log.Debugf("Invalid email: %s", email)
http.Error(w, "Not authorized", 401)
return
}
// Valid request
w.WriteHeader(200)
}
// Authenticate user after they have come back from google
func handleCallback(w http.ResponseWriter, r *http.Request, qs url.Values) {
// Check for CSRF cookie
csrfCookie, err := r.Cookie(fw.CSRFCookieName)
if err != nil {
log.Debug("Missing csrf cookie")
http.Error(w, "Not authorized", 401)
return
}
// Validate state
state := qs.Get("state")
valid, redirect, err := fw.ValidateCSRFCookie(csrfCookie, state)
if !valid {
log.Debugf("Invalid oauth state, expected '%s', got '%s'\n", csrfCookie.Value, state)
http.Error(w, "Not authorized", 401)
return
}
// Clear CSRF cookie
http.SetCookie(w, fw.ClearCSRFCookie(r))
// Exchange code for token
token, err := fw.ExchangeCode(r, qs.Get("code"))
if err != nil {
log.Debugf("Code exchange failed with: %s\n", err)
http.Error(w, "Service unavailable", 503)
return
}
// Get user
user, err := fw.GetUser(token)
if err != nil {
log.Debugf("Error getting user: %s\n", err)
return
}
// Generate cookie
http.SetCookie(w, fw.MakeCookie(r, user.Email))
log.Debugf("Generated auth cookie for %s\n", user.Email)
// Redirect
http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
}
// Main
func main() {
// Parse options
flag.String(flag.DefaultConfigFlagname, "", "Path to config file")
path := flag.String("url-path", "_oauth", "Callback URL")
lifetime := flag.Int("lifetime", 43200, "Session length in seconds")
secret := flag.String("secret", "", "*Secret used for signing (required)")
authHost := flag.String("auth-host", "", "Central auth login")
clientId := flag.String("client-id", "", "*Google Client ID (required)")
clientSecret := flag.String("client-secret", "", "*Google Client Secret (required)")
cookieName := flag.String("cookie-name", "_forward_auth", "Cookie Name")
cSRFCookieName := flag.String("csrf-cookie-name", "_forward_auth_csrf", "CSRF Cookie Name")
cookieDomainList := flag.String("cookie-domains", "", "Comma separated list of cookie domains") //todo
cookieSecret := flag.String("cookie-secret", "", "Deprecated")
cookieSecure := flag.Bool("cookie-secure", true, "Use secure cookies")
domainList := flag.String("domain", "", "Comma separated list of email domains to allow")
emailWhitelist := flag.String("whitelist", "", "Comma separated list of emails to allow")
prompt := flag.String("prompt", "", "Space separated list of OpenID prompt options")
flag.Parse()
// Backwards compatability
if *secret == "" && *cookieSecret != "" {
*secret = *cookieSecret
}
// Check for show stopper errors
stop := false
if *clientId == "" {
stop = true
log.Critical("client-id must be set")
}
if *clientSecret == "" {
stop = true
log.Critical("client-secret must be set")
}
if *secret == "" {
stop = true
log.Critical("secret must be set")
}
if stop {
return
}
// Parse lists
var cookieDomains []CookieDomain
if *cookieDomainList != "" {
for _, d := range strings.Split(*cookieDomainList, ",") {
cookieDomain := NewCookieDomain(d)
cookieDomains = append(cookieDomains, *cookieDomain)
}
}
var domain []string
if *domainList != "" {
domain = strings.Split(*domainList, ",")
}
var whitelist []string
if *emailWhitelist != "" {
whitelist = strings.Split(*emailWhitelist, ",")
}
// Setup
fw = &ForwardAuth{
Path: fmt.Sprintf("/%s", *path),
Lifetime: time.Second * time.Duration(*lifetime),
Secret: []byte(*secret),
AuthHost: *authHost,
ClientId: *clientId,
ClientSecret: *clientSecret,
Scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
LoginURL: &url.URL{
Scheme: "https",
Host: "accounts.google.com",
Path: "/o/oauth2/auth",
},
TokenURL: &url.URL{
Scheme: "https",
Host: "www.googleapis.com",
Path: "/oauth2/v3/token",
},
UserURL: &url.URL{
Scheme: "https",
Host: "www.googleapis.com",
Path: "/oauth2/v2/userinfo",
},
CookieName: *cookieName,
CSRFCookieName: *cSRFCookieName,
CookieDomains: cookieDomains,
CookieSecure: *cookieSecure,
Domain: domain,
Whitelist: whitelist,
Prompt: *prompt,
}
// Attach handler
http.HandleFunc("/", handler)
log.Debugf("Starting with options: %#v", fw)
log.Notice("Listening on :4181")
log.Notice(http.ListenAndServe(":4181", nil))
}