forked from Versent/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 1
/
adfs2.go
99 lines (85 loc) · 2.39 KB
/
adfs2.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 adfs2
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"golang.org/x/net/publicsuffix"
"github.com/Azure/go-ntlmssp"
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
"github.com/versent/saml2aws/pkg/cfg"
"github.com/versent/saml2aws/pkg/creds"
)
// Client client for adfs2
type Client struct {
idpAccount *cfg.IDPAccount
transport http.RoundTripper
jar http.CookieJar
}
// New new adfs2 client with ntlmssp configured
func New(idpAccount *cfg.IDPAccount) (*Client, error) {
transport := &ntlmssp.Negotiator{
RoundTripper: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: idpAccount.SkipVerify, Renegotiation: tls.RenegotiateFreelyAsClient},
},
}
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return nil, err
}
return &Client{
transport: transport,
idpAccount: idpAccount,
jar: jar,
}, nil
}
// Authenticate authenticate the user using the supplied login details
func (ac *Client) Authenticate(loginDetails *creds.LoginDetails) (string, error) {
var samlAssertion string
client := http.Client{
Transport: ac.transport,
Jar: ac.jar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
req.SetBasicAuth(loginDetails.Username, loginDetails.Password)
return nil
},
}
url := fmt.Sprintf("%s/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=%s", loginDetails.URL, ac.idpAccount.AmazonWebservicesURN)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return samlAssertion, err
}
req.SetBasicAuth(loginDetails.Username, loginDetails.Password)
res, err := client.Do(req)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retieving login form")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return samlAssertion, errors.Wrap(err, "error retieving body")
}
doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(data))
if err != nil {
return samlAssertion, errors.Wrap(err, "error parsing document")
}
doc.Find("input").Each(func(i int, s *goquery.Selection) {
name, ok := s.Attr("name")
if !ok {
log.Fatalf("unable to locate IDP authentication form submit URL")
}
if name == "SAMLResponse" {
val, ok := s.Attr("value")
if !ok {
log.Fatalf("unable to locate saml assertion value")
}
samlAssertion = val
}
})
return samlAssertion, nil
}