This repository has been archived by the owner on May 22, 2023. It is now read-only.
forked from crewjam/saml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session_cookie.go
99 lines (84 loc) · 2.42 KB
/
session_cookie.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
package samlsp
import (
"net"
"net/http"
"time"
"github.com/lightstep/saml"
)
const defaultSessionCookieName = "token"
var _ SessionProvider = CookieSessionProvider{}
// CookieSessionProvider is an implementation of SessionProvider that stores
// session tokens in an HTTP cookie.
type CookieSessionProvider struct {
Name string
Domain string
HTTPOnly bool
Secure bool
SameSite http.SameSite
MaxAge time.Duration
Codec SessionCodec
}
// CreateSession is called when we have received a valid SAML assertion and
// should create a new session and modify the http response accordingly, e.g. by
// setting a cookie.
func (c CookieSessionProvider) CreateSession(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion) error {
// Cookies should not have the port attached to them so strip it off
if domain, _, err := net.SplitHostPort(c.Domain); err == nil {
c.Domain = domain
}
session, err := c.Codec.New(assertion)
if err != nil {
return err
}
value, err := c.Codec.Encode(session)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: c.Name,
Domain: c.Domain,
Value: value,
MaxAge: int(c.MaxAge.Seconds()),
HttpOnly: c.HTTPOnly,
Secure: c.Secure || r.URL.Scheme == "https",
SameSite: c.SameSite,
Path: "/",
})
return nil
}
// DeleteSession is called to modify the response such that it removed the current
// session, e.g. by deleting a cookie.
func (c CookieSessionProvider) DeleteSession(w http.ResponseWriter, r *http.Request) error {
// Cookies should not have the port attached to them so strip it off
if domain, _, err := net.SplitHostPort(c.Domain); err == nil {
c.Domain = domain
}
cookie, err := r.Cookie(c.Name)
if err == http.ErrNoCookie {
return nil
}
if err != nil {
return err
}
cookie.Value = ""
cookie.Expires = time.Unix(1, 0) // past time as close to epoch as possible, but not zero time.Time{}
cookie.Path = "/"
cookie.Domain = c.Domain
http.SetCookie(w, cookie)
return nil
}
// GetSession returns the current Session associated with the request, or
// ErrNoSession if there is no valid session.
func (c CookieSessionProvider) GetSession(r *http.Request) (Session, error) {
cookie, err := r.Cookie(c.Name)
if err == http.ErrNoCookie {
return nil, ErrNoSession
} else if err != nil {
return nil, err
}
session, err := c.Codec.Decode(cookie.Value)
if err != nil {
return nil, ErrNoSession
}
return session, nil
}