-
Notifications
You must be signed in to change notification settings - Fork 421
/
samlsp.go
93 lines (81 loc) · 2.12 KB
/
samlsp.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
// Package samlsp provides helpers that can be used to protect web
// services using SAML.
package samlsp
import (
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/crewjam/saml"
)
// Options represents the parameters for creating a new middleware
type Options struct {
URL string
Key string
Certificate string
AllowIDPInitiated bool
IDPMetadata *saml.Metadata
IDPMetadataURL string
}
// New creates a new Middleware
func New(opts Options) (*Middleware, error) {
m := &Middleware{
ServiceProvider: saml.ServiceProvider{
Key: opts.Key,
Certificate: opts.Certificate,
MetadataURL: opts.URL + "/saml/metadata",
AcsURL: opts.URL + "/saml/acs",
IDPMetadata: opts.IDPMetadata,
},
AllowIDPInitiated: opts.AllowIDPInitiated,
CookieName: defaultCookieName,
CookieMaxAge: defaultCookieMaxAge,
}
// fetch the IDP metadata if needed.
if opts.IDPMetadataURL == "" {
return m, nil
}
for i := 0; true; i++ {
resp, err := http.Get(opts.IDPMetadataURL)
if err == nil && resp.StatusCode != http.StatusOK {
err = fmt.Errorf("%d %s", resp.StatusCode, resp.Status)
}
var data []byte
if err == nil {
data, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
if err != nil {
if i > 10 {
return nil, err
}
log.Printf("ERROR: %s: %s (will retry)", opts.IDPMetadataURL, err)
time.Sleep(5 * time.Second)
continue
}
entity := &saml.Metadata{}
err = xml.Unmarshal(data, entity)
// this comparison is ugly, but it is how the error is generated in encoding/xml
if err != nil && err.Error() == "expected element type <EntityDescriptor> but have <EntitiesDescriptor>" {
entities := &saml.EntitiesDescriptor{}
if err := xml.Unmarshal(data, entities); err != nil {
return nil, err
}
err = fmt.Errorf("no entity found with IDPSSODescriptor")
for _, e := range entities.EntityDescriptor {
if e.IDPSSODescriptor != nil {
entity = e
err = nil
}
}
}
if err != nil {
return nil, err
}
m.ServiceProvider.IDPMetadata = entity
return m, nil
}
panic("unreachable")
}