-
Notifications
You must be signed in to change notification settings - Fork 13
/
authclient.go
188 lines (162 loc) · 4.5 KB
/
authclient.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package oauth
import (
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"sync"
"time"
"github.com/Axway/agent-sdk/pkg/api"
"github.com/Axway/agent-sdk/pkg/util/log"
)
// AuthClient - Interface representing the auth Client
type AuthClient interface {
GetToken() (string, error)
}
// AuthClientOption - configures auth client.
type AuthClientOption func(*authClientOptions)
type authClientOptions struct {
serverName string
authenticator authenticator
}
// authClient -
type authClient struct {
tokenURL string
apiClient api.Client
cachedToken *tokenResponse
cachedTokenExpiry *time.Timer
getTokenMutex *sync.Mutex
options *authClientOptions
logger log.FieldLogger
}
type authenticator interface {
prepareRequest() (url.Values, error)
}
type tokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
}
// NewAuthClient - create a new auth client with client options
func NewAuthClient(tokenURL string, apiClient api.Client, opts ...AuthClientOption) (AuthClient, error) {
logger := log.NewFieldLogger().
WithComponent("authclient").
WithPackage("sdk.agent.authz.oauth")
client := &authClient{
tokenURL: tokenURL,
apiClient: apiClient,
getTokenMutex: &sync.Mutex{},
options: &authClientOptions{},
logger: logger,
}
for _, o := range opts {
o(client.options)
}
if client.options.serverName == "" {
client.options.serverName = defaultServerName
}
if client.options.authenticator == nil {
return nil, errors.New("unable to create client, no authenticator configured")
}
return client, nil
}
// WithServerName - sets up the server name in auth client
func WithServerName(serverName string) AuthClientOption {
return func(opt *authClientOptions) {
opt.serverName = serverName
}
}
// WithClientSecretAuth - sets up to use client secret authenticator
func WithClientSecretAuth(clientID, clientSecret, scope string) AuthClientOption {
return func(opt *authClientOptions) {
opt.authenticator = &clientSecretAuthenticator{
clientID,
clientSecret,
scope,
}
}
}
// WithKeyPairAuth - sets up to use public/private key pair authenticator
func WithKeyPairAuth(clientID, audience string, privKey *rsa.PrivateKey, publicKey []byte) AuthClientOption {
return func(opt *authClientOptions) {
opt.authenticator = &keyPairAuthenticator{
clientID,
audience,
privKey,
publicKey,
}
}
}
func (c *authClient) getCachedToken() string {
if c.cachedToken != nil {
select {
case <-c.cachedTokenExpiry.C:
// cleanup the token on expiry
c.cachedToken = nil
return ""
default:
return c.cachedToken.AccessToken
}
}
return ""
}
// GetToken returns a token from cache if not expired or fetches a new token
func (c *authClient) GetToken() (string, error) {
// only one GetToken should execute at a time
c.getTokenMutex.Lock()
defer c.getTokenMutex.Unlock()
if token := c.getCachedToken(); token != "" {
return token, nil
}
// try fetching a new token
return c.fetchNewToken()
}
// fetchNewToken fetches a new token from the platform and updates the token cache.
func (c *authClient) fetchNewToken() (string, error) {
tokenResponse, err := c.getOAuthTokens()
if err != nil {
return "", err
}
almostExpires := (tokenResponse.ExpiresIn * 4) / 5
c.cachedToken = tokenResponse
c.cachedTokenExpiry = time.NewTimer(time.Duration(almostExpires) * time.Second)
return c.cachedToken.AccessToken, nil
}
func (c *authClient) getOAuthTokens() (*tokenResponse, error) {
req, err := c.options.authenticator.prepareRequest()
if err != nil {
return nil, err
}
resp, err := c.postAuthForm(req)
if err != nil {
return nil, err
}
if resp.Code != 200 {
err := fmt.Errorf("bad response from %s: %d %s", c.options.serverName, resp.Code, http.StatusText(resp.Code))
c.logger.
WithField("server", c.options.serverName).
WithField("url", c.tokenURL).
WithField("status", resp.Code).
WithField("body", string(resp.Body)).
WithError(err).
Debug(err.Error())
return nil, err
}
tokens := tokenResponse{}
if err := json.Unmarshal(resp.Body, &tokens); err != nil {
return nil, fmt.Errorf("unable to unmarshal token: %v", err)
}
return &tokens, nil
}
func (c *authClient) postAuthForm(data url.Values) (resp *api.Response, err error) {
req := api.Request{
Method: api.POST,
URL: c.tokenURL,
Body: []byte(data.Encode()),
Headers: map[string]string{
hdrContentType: mimeApplicationFormURLEncoded,
},
}
return c.apiClient.Send(req)
}