-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
172 lines (149 loc) · 3.89 KB
/
auth.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package auth
import (
"context"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
jwt "github.com/form3tech-oss/jwt-go"
"github.com/pkg/errors"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
authTokenPath = "/oauth2/v2.0/token"
clientAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
grantType = "client_credentials"
)
type customClaims struct {
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
Id string `json:"jti,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Subject string `json:"sub,omitempty"`
}
func (c customClaims) Valid() error {
return nil
}
type Client struct {
httpClient HttpClient
url string
certFingerprint string
privateKey string
appId string
clientId string
tenantId string
}
func NewClient(httpClient HttpClient, url, certFingerprint, privateKey, appId, clientId, tenantId string) *Client {
return &Client{
httpClient: httpClient,
url: url,
certFingerprint: certFingerprint,
privateKey: privateKey,
appId: appId,
clientId: clientId,
tenantId: tenantId,
}
}
func (a Client) Token(ctx context.Context) (string, time.Duration, error) {
form, err := a.buildParams()
if err != nil {
return "", 0, err
}
r, err := a.httpClient.Post(
a.url+"/"+a.tenantId+authTokenPath,
a.buildHeaders(),
ctx,
form,
)
if err != nil {
return "", 0, err
}
var content map[string]interface{}
err = r.ToJSON(&content)
if err != nil {
return "", 0, err
}
if errorDesc, valid := content["error_description"].(string); valid {
return "", 0, errors.New(errorDesc)
}
if _, valid := content["access_token"].(string); !valid {
return "", 0, errors.New("access token not set, error not understood")
}
return content["access_token"].(string), time.Duration(content["expires_in"].(float64)) * time.Second, nil
}
func (a Client) x5t(fingerprint string) string {
f := strings.Split(fingerprint, ":")
var z int64
var e = make([]byte, len(f))
for i, v := range f {
z, _ = strconv.ParseInt(v, 16, 32)
e[i] = byte(z)
}
s := base64.URLEncoding.EncodeToString(e)
return s
}
func (a Client) randomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func (a Client) buildParams() (url.Values, error) {
signed, err := a.buildClientAssertion()
if err != nil {
return nil, err
}
return url.Values{
"tenant": []string{a.tenantId},
"client_id": []string{a.clientId},
"scope": []string{a.appId + "/.default"},
"client_assertion_type": []string{clientAssertionType},
"client_assertion": []string{signed},
"grant_type": []string{grantType},
},
nil
}
func (a Client) buildHeaders() http.Header {
return http.Header{
"Accept": []string{"application/json"},
"Content-Type": []string{"application/x-www-form-urlencoded"},
}
}
func (a Client) buildClientAssertion() (string, error) {
block, _ := pem.Decode([]byte(a.privateKey))
if block == nil {
return "", errors.New("nothing to decode private key is invalid")
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return "", err
}
randID, err := a.randomHex(12)
if err != nil {
return "", err
}
now := time.Now().Unix()
claims := customClaims{
Subject: a.clientId,
Issuer: a.clientId,
Id: randID,
NotBefore: now,
Audience: a.url + "/" + a.tenantId + authTokenPath,
ExpiresAt: now + 3600,
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
token.Header["x5t"] = a.x5t(a.certFingerprint)
signed, err := token.SignedString(key)
if err != nil {
return "", err
}
return signed, nil
}