-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthenticator_enterprise.go
90 lines (74 loc) · 2.06 KB
/
authenticator_enterprise.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
package main
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/prometheus/common/log"
)
type enterpriseStrategy struct {
Target *url.URL
Verbose bool
client *http.Client
creds *authContext
hash crypto.Hash
// authZ string
}
func (e *enterpriseStrategy) authenticate() (string, error) {
var body string
var bodyLog string
if e.creds.PrivateKey != nil {
token, _ := e.getSelfSignedToken()
body = fmt.Sprintf(`{"uid":"%s","token":"%s"}`, e.creds.UID, token)
bodyLog = body
} else {
body = fmt.Sprintf(`{"uid":"%s","password":"%s"}`, e.creds.UID, e.creds.Password)
bodyLog = fmt.Sprintf(`{"uid":"%s","password":"%s"}`, e.creds.UID, "****")
}
if e.Verbose {
log.Infof("Authenticating: POST %s %s", e.creds.AuthEndpoint, bodyLog)
}
r, _ := http.NewRequest("POST", e.creds.AuthEndpoint, bytes.NewBufferString(body))
r.Header.Add("Content-Type", "application/json")
resp, err := e.client.Do(r)
checkError(err)
if e.Verbose {
log.Infof("Authentication result: %d", resp.StatusCode)
}
rbody := []byte{}
if resp.Body != nil {
rbodyString, err := ioutil.ReadAll(resp.Body)
checkError(err)
rbody = rbodyString
defer resp.Body.Close()
}
if resp.StatusCode == 200 {
data := make(map[string]interface{})
if err := json.Unmarshal(rbody, &data); err != nil {
return "", err
}
return data["token"].(string), nil
}
log.Error(fmt.Sprintf("POST %s : %d\n%s",
e.creds.AuthEndpoint, resp.StatusCode, resp.Body))
return "", errors.New("Failed to authenticate")
}
func (e *enterpriseStrategy) getSelfSignedToken() (string, error) {
head := base64URLEncode([]byte(`{"alg":"RS256","typ":"JWT"}`))
body := base64URLEncode([]byte(fmt.Sprintf(`{"uid": "%s"}`, e.creds.UID)))
rawToken := head + "." + body
hashed := sha256.Sum256([]byte(rawToken))
sig, err := rsa.SignPKCS1v15(rand.Reader, e.creds.PrivateKey, e.hash, hashed[:])
if err != nil {
return "", err
}
signature := base64URLEncode(sig)
return rawToken + "." + signature, nil
}