forked from crewjam/saml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trivial.go
76 lines (65 loc) · 1.91 KB
/
trivial.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
package main
import (
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"fmt"
"log"
"net/http"
"net/url"
"github.com/kevcoxe/grafanaSaml/samlsp"
)
var samlMiddleware *samlsp.Middleware
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", samlsp.AttributeFromContext(r.Context(), "displayName"))
}
func logout(w http.ResponseWriter, r *http.Request) {
nameID := samlsp.AttributeFromContext(r.Context(), "urn:oasis:names:tc:SAML:attribute:subject-id")
url, err := samlMiddleware.ServiceProvider.MakeRedirectLogoutRequest(nameID, "")
if err != nil {
panic(err) // TODO handle error
}
err = samlMiddleware.Session.DeleteSession(w, r)
if err != nil {
panic(err) // TODO handle error
}
w.Header().Add("Location", url.String())
w.WriteHeader(http.StatusFound)
}
func main() {
keyPair, err := tls.LoadX509KeyPair("myservice.cert", "myservice.key")
if err != nil {
panic(err) // TODO handle error
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
panic(err) // TODO handle error
}
idpMetadataURL, err := url.Parse("https://samltest.id/saml/idp")
if err != nil {
panic(err) // TODO handle error
}
idpMetadata, err := samlsp.FetchMetadata(context.Background(), http.DefaultClient,
*idpMetadataURL)
if err != nil {
panic(err) // TODO handle error
}
rootURL, err := url.Parse("http://localhost:8000")
if err != nil {
panic(err) // TODO handle error
}
samlMiddleware, _ = samlsp.New(samlsp.Options{
URL: *rootURL,
Key: keyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: keyPair.Leaf,
IDPMetadata: idpMetadata,
SignRequest: true, // some IdP require the SLO request to be signed
})
app := http.HandlerFunc(hello)
slo := http.HandlerFunc(logout)
http.Handle("/hello", samlMiddleware.RequireAccount(app))
http.Handle("/saml/", samlMiddleware)
http.Handle("/logout", slo)
log.Fatal(http.ListenAndServe(":8000", nil))
}