github.com/crewjam/saml@v0.4.14/example/trivial/trivial.go (about) 1 // Package main contains an example service provider implementation. 2 package main 3 4 import ( 5 "context" 6 "crypto/rsa" 7 "crypto/tls" 8 "crypto/x509" 9 "fmt" 10 "log" 11 "net/http" 12 "net/url" 13 "time" 14 15 "github.com/crewjam/saml/samlsp" 16 ) 17 18 var samlMiddleware *samlsp.Middleware 19 20 func hello(w http.ResponseWriter, r *http.Request) { 21 fmt.Fprintf(w, "Hello, %s!", samlsp.AttributeFromContext(r.Context(), "displayName")) 22 } 23 24 func logout(w http.ResponseWriter, r *http.Request) { 25 nameID := samlsp.AttributeFromContext(r.Context(), "urn:oasis:names:tc:SAML:attribute:subject-id") 26 url, err := samlMiddleware.ServiceProvider.MakeRedirectLogoutRequest(nameID, "") 27 if err != nil { 28 panic(err) // TODO handle error 29 } 30 31 err = samlMiddleware.Session.DeleteSession(w, r) 32 if err != nil { 33 panic(err) // TODO handle error 34 } 35 36 w.Header().Add("Location", url.String()) 37 w.WriteHeader(http.StatusFound) 38 } 39 40 func main() { 41 keyPair, err := tls.LoadX509KeyPair("myservice.cert", "myservice.key") 42 if err != nil { 43 panic(err) // TODO handle error 44 } 45 keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0]) 46 if err != nil { 47 panic(err) // TODO handle error 48 } 49 50 idpMetadataURL, err := url.Parse("https://samltest.id/saml/idp") 51 if err != nil { 52 panic(err) // TODO handle error 53 } 54 idpMetadata, err := samlsp.FetchMetadata(context.Background(), http.DefaultClient, 55 *idpMetadataURL) 56 if err != nil { 57 panic(err) // TODO handle error 58 } 59 60 rootURL, err := url.Parse("http://localhost:8000") 61 if err != nil { 62 panic(err) // TODO handle error 63 } 64 65 samlMiddleware, _ = samlsp.New(samlsp.Options{ 66 URL: *rootURL, 67 Key: keyPair.PrivateKey.(*rsa.PrivateKey), 68 Certificate: keyPair.Leaf, 69 IDPMetadata: idpMetadata, 70 SignRequest: true, // some IdP require the SLO request to be signed 71 }) 72 app := http.HandlerFunc(hello) 73 slo := http.HandlerFunc(logout) 74 75 http.Handle("/hello", samlMiddleware.RequireAccount(app)) 76 http.Handle("/saml/", samlMiddleware) 77 http.Handle("/logout", slo) 78 79 server := &http.Server{ 80 Addr: ":8080", 81 ReadHeaderTimeout: 5 * time.Second, 82 } 83 log.Fatal(server.ListenAndServe()) 84 }