-
Notifications
You must be signed in to change notification settings - Fork 0
/
saml_auth_provider.go
102 lines (85 loc) · 2.63 KB
/
saml_auth_provider.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
package main
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"log"
"net/http"
"net/url"
"github.com/crewjam/saml/samlsp"
)
type SamlAuthProvider struct {
samlSP *samlsp.Middleware
}
func (s SamlAuthProvider) attributesFromContext(ctx context.Context) *OSUAttributes {
session := samlsp.SessionFromContext(ctx).(samlsp.SessionWithAttributes)
attributes := session.GetAttributes()
return &OSUAttributes{
Surname: attributes.Get("sn"),
IDMUID: attributes.Get("IDMUID"),
DisplayName: attributes.Get("displayName"),
Affiliations: attributes["eduPersonScopedAffiliation"],
BuckID: attributes.Get("employeeNumber"),
GivenName: attributes.Get("givenName"),
Email: attributes.Get("mail"),
SessionIndex: attributes.Get("SessionIndex"),
}
}
func (s SamlAuthProvider) requireAuth(handler http.Handler) http.Handler {
return s.samlSP.RequireAccount(handler)
}
func (s *SamlAuthProvider) globalLogout(w http.ResponseWriter, r *http.Request) {
err := s.samlSP.Session.DeleteSession(w, r)
if err != nil {
log.Println("Failed to delete session:", err)
return
}
w.Header().Add("Location", "https://webauth.service.ohio-state.edu/cgi-bin/logout.cgi")
w.WriteHeader(http.StatusFound)
}
func (s *SamlAuthProvider) logout(w http.ResponseWriter, r *http.Request) {
err := s.samlSP.Session.DeleteSession(w, r)
if err != nil {
log.Println("Failed to delete session:", err)
return
}
}
const SAML_COOKIE_NAME string = "_saml"
func samlAuthProvider(mux *http.ServeMux, rootURL *url.URL, keyPair *tls.Certificate) (*SamlAuthProvider, error) {
var err error
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
return nil, err
}
idpMetadataURL, err := url.Parse("https://webauth.service.ohio-state.edu/OSU-idp-metadata.xml")
if err != nil {
return nil, err
}
idpMetadata, err := samlsp.FetchMetadata(context.Background(), http.DefaultClient, *idpMetadataURL)
if err != nil {
return nil, err
}
samlSP, err := samlsp.New(samlsp.Options{
URL: *rootURL,
EntityID: "https://auth.osucyber.club/shibboleth",
Key: keyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: keyPair.Leaf,
IDPMetadata: idpMetadata,
CookieName: SAML_COOKIE_NAME,
})
if err != nil {
return nil, err
}
acsUrl := *rootURL
acsUrl.Path = "/Shibboleth.sso/SAML2/POST"
samlSP.ServiceProvider.AcsURL = acsUrl
samlSP.OnError = func(w http.ResponseWriter, r *http.Request, err error) {
log.Println("SAML error:", err)
}
mux.Handle("/Shibboleth.sso/", samlSP)
mux.Handle("/metadata.xml", http.HandlerFunc(samlSP.ServeMetadata))
return &SamlAuthProvider{
samlSP,
}, nil
}