forked from go-cas/cas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
375 lines (309 loc) · 9.21 KB
/
client.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
package cas
import (
"crypto/rand"
"fmt"
"net/http"
"net/url"
"github.com/golang/glog"
)
// Options : Client configuration options
type Options struct {
URL *url.URL // URL to the CAS service
Store TicketStore // Custom TicketStore, if nil a MemoryStore will be used
Client *http.Client // Custom http client to allow options for http connections
SendService bool // Custom sendService to determine whether you need to send service param
URLScheme URLScheme // Custom url scheme, can be used to modify the request urls for the client
Cookie *http.Cookie // http.Cookie options, uses Path, Domain, MaxAge, HttpOnly, & Secure
SessionStore SessionStore
}
// Client implements the main protocol
type Client struct {
tickets TicketStore
client *http.Client
urlScheme URLScheme
cookie *http.Cookie
sessions SessionStore
sendService bool
stValidator *ServiceTicketValidator
}
// NewClient creates a Client with the provided Options.
func NewClient(options *Options) *Client {
if glog.V(2) {
glog.Infof("cas: new client with options %v", options)
}
var tickets TicketStore
if options.Store != nil {
tickets = options.Store
} else {
tickets = &MemoryStore{}
}
var sessions SessionStore
if options.SessionStore != nil {
sessions = options.SessionStore
} else {
sessions = NewMemorySessionStore()
}
var urlScheme URLScheme
if options.URLScheme != nil {
urlScheme = options.URLScheme
} else {
urlScheme = NewDefaultURLScheme(options.URL)
}
var client *http.Client
if options.Client != nil {
client = options.Client
} else {
client = &http.Client{}
}
var cookie *http.Cookie
if options.Cookie != nil {
cookie = options.Cookie
} else {
cookie = &http.Cookie{
MaxAge: 86400,
HttpOnly: false,
Secure: false,
SameSite: http.SameSiteDefaultMode,
}
}
return &Client{
tickets: tickets,
client: client,
urlScheme: urlScheme,
cookie: cookie,
sessions: sessions,
sendService: options.SendService,
stValidator: NewServiceTicketValidator(client, options.URL),
}
}
// Handle wraps a http.Handler to provide CAS authentication for the handler.
func (c *Client) Handle(h http.Handler) http.Handler {
return &clientHandler{
c: c,
h: h,
}
}
// HandleFunc wraps a function to provide CAS authentication for the handler function.
func (c *Client) HandleFunc(h func(http.ResponseWriter, *http.Request)) http.Handler {
return c.Handle(http.HandlerFunc(h))
}
// requestURL determines an absolute URL from the http.Request.
func requestURL(r *http.Request) (*url.URL, error) {
u, err := url.Parse(r.URL.String())
if err != nil {
return nil, err
}
u.Host = r.Host
if host := r.Header.Get("X-Forwarded-Host"); host != "" {
u.Host = host
}
u.Scheme = "http"
if scheme := r.Header.Get("X-Forwarded-Proto"); scheme != "" {
u.Scheme = scheme
} else if r.TLS != nil {
u.Scheme = "https"
}
return u, nil
}
// LoginUrlForRequest determines the CAS login URL for the http.Request.
func (c *Client) LoginUrlForRequest(r *http.Request) (string, error) {
u, err := c.urlScheme.Login()
if err != nil {
return "", err
}
service, err := requestURL(r)
if err != nil {
return "", err
}
q := u.Query()
q.Add("service", sanitisedURLString(service))
u.RawQuery = q.Encode()
return u.String(), nil
}
// LogoutUrlForRequest determines the CAS logout URL for the http.Request.
func (c *Client) LogoutUrlForRequest(r *http.Request) (string, error) {
u, err := c.urlScheme.Logout()
if err != nil {
return "", err
}
if c.sendService {
service, err := requestURL(r)
if err != nil {
return "", err
}
q := u.Query()
q.Add("service", sanitisedURLString(service))
u.RawQuery = q.Encode()
}
return u.String(), nil
}
// ServiceValidateUrlForRequest determines the CAS serviceValidate URL for the ticket and http.Request.
func (c *Client) ServiceValidateUrlForRequest(ticket string, r *http.Request) (string, error) {
service, err := requestURL(r)
if err != nil {
return "", err
}
return c.stValidator.ServiceValidateUrl(service, ticket)
}
// ValidateUrlForRequest determines the CAS validate URL for the ticket and http.Request.
func (c *Client) ValidateUrlForRequest(ticket string, r *http.Request) (string, error) {
service, err := requestURL(r)
if err != nil {
return "", err
}
return c.stValidator.ValidateUrl(service, ticket)
}
// RedirectToLogout replies to the request with a redirect URL to log out of CAS.
func (c *Client) RedirectToLogout(w http.ResponseWriter, r *http.Request) {
u, err := c.LogoutUrlForRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if glog.V(2) {
glog.Infof("Logging out, redirecting client to %v with status %v",
u, http.StatusFound)
}
c.clearSession(w, r)
http.Redirect(w, r, u, http.StatusFound)
}
// RedirectToLogin replies to the request with a redirect URL to authenticate with CAS.
func (c *Client) RedirectToLogin(w http.ResponseWriter, r *http.Request) {
u, err := c.LoginUrlForRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if glog.V(2) {
glog.Infof("Redirecting client to %v with status %v", u, http.StatusFound)
}
http.Redirect(w, r, u, http.StatusFound)
}
// validateTicket performs CAS ticket validation with the given ticket and service.
func (c *Client) validateTicket(ticket string, service *http.Request) error {
serviceURL, err := requestURL(service)
if err != nil {
return err
}
success, err := c.stValidator.ValidateTicket(serviceURL, ticket)
if err != nil {
return err
}
if err := c.tickets.Write(ticket, success); err != nil {
return err
}
return nil
}
// getSession finds or creates a session for the request.
//
// A cookie is set on the response if one is not provided with the request.
// Validates the ticket if the URL parameter is provided.
func (c *Client) getSession(w http.ResponseWriter, r *http.Request) {
cookie := c.getCookie(w, r)
if s, ok := c.sessions.Get(cookie.Value); ok {
if t, err := c.tickets.Read(s); err == nil {
if glog.V(1) {
glog.Infof("Re-used ticket %s for %s", s, t.User)
}
setAuthenticationResponse(r, t)
return
} else {
if glog.V(2) {
glog.Infof("Ticket %v not in %T: %v", s, c.tickets, err)
}
if glog.V(1) {
glog.Infof("Clearing ticket %s, no longer exists in ticket store", s)
}
clearCookie(w, cookie)
}
}
if ticket := r.URL.Query().Get("ticket"); ticket != "" {
if err := c.validateTicket(ticket, r); err != nil {
if glog.V(2) {
glog.Infof("Error validating ticket: %v", err)
}
return // allow ServeHTTP()
}
c.setSession(cookie.Value, ticket)
if t, err := c.tickets.Read(ticket); err == nil {
if glog.V(1) {
glog.Infof("Validated ticket %s for %s", ticket, t.User)
}
setAuthenticationResponse(r, t)
return
} else {
if glog.V(2) {
glog.Infof("Ticket %v not in %T: %v", ticket, c.tickets, err)
}
if glog.V(1) {
glog.Infof("Clearing ticket %s, no longer exists in ticket store", ticket)
}
clearCookie(w, cookie)
}
}
}
// getCookie finds or creates the session cookie on the response.
func (c *Client) getCookie(w http.ResponseWriter, r *http.Request) *http.Cookie {
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
// NOTE: Intentionally not enabling HttpOnly so the cookie can
// still be used by Ajax requests.
cookie = &http.Cookie{
Name: sessionCookieName,
Value: newSessionID(),
Path: c.cookie.Path,
Domain: c.cookie.Domain,
MaxAge: c.cookie.MaxAge,
HttpOnly: c.cookie.HttpOnly,
Secure: c.cookie.Secure,
SameSite: c.cookie.SameSite,
}
if glog.V(2) {
glog.Infof("Setting %v cookie with value: %v", cookie.Name, cookie.Value)
}
r.AddCookie(cookie) // so we can find it later if required
http.SetCookie(w, cookie)
}
return cookie
}
// newSessionId generates a new opaque session identifier for use in the cookie.
func newSessionID() string {
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// generate 64 character string
bytes := make([]byte, 64)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = alphabet[v%byte(len(alphabet))]
}
return string(bytes)
}
// clearCookie invalidates and removes the cookie from the client.
func clearCookie(w http.ResponseWriter, c *http.Cookie) {
c.MaxAge = -1
http.SetCookie(w, c)
}
// setSession stores the session id to ticket mapping in the Client.
func (c *Client) setSession(id string, ticket string) {
if glog.V(2) {
glog.Infof("Recording session, %v -> %v", id, ticket)
}
c.sessions.Set(id, ticket)
}
// clearSession removes the session from the client and clears the cookie.
func (c *Client) clearSession(w http.ResponseWriter, r *http.Request) {
cookie := c.getCookie(w, r)
if serviceTicket, ok := c.sessions.Get(cookie.Value); ok {
if err := c.tickets.Delete(serviceTicket); err != nil {
fmt.Printf("Failed to remove %v from %T: %v\n", cookie.Value, c.tickets, err)
if glog.V(2) {
glog.Errorf("Failed to remove %v from %T: %v", cookie.Value, c.tickets, err)
}
}
c.deleteSession(cookie.Value)
}
clearCookie(w, cookie)
}
// deleteSession removes the session from the client
func (c *Client) deleteSession(id string) {
c.sessions.Delete(id)
}