-
Notifications
You must be signed in to change notification settings - Fork 480
/
consumer.go
276 lines (248 loc) · 9.34 KB
/
consumer.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*******************************************************************************
* Copyright 2019 Dell Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* @author: Tingyu Zeng, Dell
*******************************************************************************/
package proxy
import (
"encoding/json"
"errors"
"fmt"
"github.com/edgexfoundry/edgex-go/internal/security/proxy/config"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/edgexfoundry/edgex-go/internal"
"github.com/edgexfoundry/go-mod-core-contracts/clients"
"github.com/edgexfoundry/go-mod-core-contracts/clients/logger"
"github.com/dgrijalva/jwt-go"
)
type Consumer struct {
name string
client internal.HttpCaller
loggingClient logger.LoggingClient
configuration *config.ConfigurationStruct
}
func NewConsumer(
name string,
r internal.HttpCaller,
lc logger.LoggingClient,
configuration *config.ConfigurationStruct) Consumer {
return Consumer{
name: name,
client: r,
loggingClient: lc,
configuration: configuration,
}
}
func (c *Consumer) Delete() error {
resource := NewResource(c.name, c.client, c.configuration.KongURL.GetProxyBaseURL(), c.loggingClient)
return resource.Remove(ConsumersPath)
}
func (c *Consumer) Create(service string) error {
tokens := []string{c.configuration.KongURL.GetProxyBaseURL(), ConsumersPath, c.name}
req, err := http.NewRequest(http.MethodPut, strings.Join(tokens, "/"), nil)
if err != nil {
e := fmt.Sprintf("failed to create consumer %s for %s service with error %s", c.name, service, err.Error())
c.loggingClient.Error(e)
return errors.New(e)
}
resp, err := c.client.Do(req)
if err != nil {
e := fmt.Sprintf("failed to create consumer %s for %s service with error %s", c.name, service, err.Error())
c.loggingClient.Error(e)
return errors.New(e)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusConflict:
c.loggingClient.Info(fmt.Sprintf("successful to create consumer %s for %s service", c.name, service))
break
default:
e := fmt.Sprintf("failed to create consumer %s for %s service", c.name, service)
c.loggingClient.Error(e)
return errors.New(e)
}
return nil
}
func (c *Consumer) AssociateWithGroup(g string) error {
tokens := []string{c.configuration.KongURL.GetProxyBaseURL(), ConsumersPath, c.name, "acls"}
formVals := url.Values{
"group": {g},
}
req, err := http.NewRequest(http.MethodPost, strings.Join(tokens, "/"), strings.NewReader(formVals.Encode()))
if err != nil {
e := fmt.Sprintf("failed to create group association request. consumer %s, group %s -- %s", c.name, g, err.Error())
c.loggingClient.Error(e)
return errors.New(e)
}
req.Header.Add(clients.ContentType, "application/x-www-form-urlencoded")
resp, err := c.client.Do(req)
if err != nil {
e := fmt.Sprintf("failed to associate consumer %s for with group %s with error %s", c.name, g, err.Error())
c.loggingClient.Error(e)
return errors.New(e)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusConflict:
c.loggingClient.Info(fmt.Sprintf("successful to associate consumer %s with group %s", c.name, g))
break
default:
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
e := fmt.Sprintf("failed to associate consumer %s with group %s with error %s,%s", c.name, g, resp.Status, string(b))
c.loggingClient.Error(e)
return errors.New(e)
}
return nil
}
func (c *Consumer) CreateToken() (string, error) {
switch c.configuration.KongAuth.Name {
case "jwt":
c.loggingClient.Info("autheticate the user with jwt authentication.")
return c.createJWTToken()
case "oauth2":
c.loggingClient.Info("authenticate the user with oauth2 authentication.")
return c.createOAuth2Token()
default:
e := fmt.Sprintf("unknown authentication method provided: %s", c.configuration.KongAuth.Name)
c.loggingClient.Error(e)
return "", errors.New(e)
}
}
func (c *Consumer) createJWTToken() (string, error) {
jwtCred := JWTCred{}
tokens := []string{c.configuration.KongURL.GetProxyBaseURL(), ConsumersPath, c.name, "jwt"}
req, err := http.NewRequest(http.MethodPost, strings.Join(tokens, "/"), nil)
if err != nil {
e := fmt.Sprintf("error creating JWT token request -- %s", err.Error())
c.loggingClient.Error(e)
return "", errors.New(e)
}
req.Header.Add(clients.ContentType, "application/x-www-form-urlencoded")
resp, err := c.client.Do(req)
if err != nil {
e := fmt.Sprintf("failed to create jwt token for consumer %s with error %s", c.name, err.Error())
return "", errors.New(e)
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusConflict:
if err = json.NewDecoder(resp.Body).Decode(&jwtCred); err != nil {
return "", err
}
c.loggingClient.Info(fmt.Sprintf("successful on retrieving JWT credential for consumer %s", c.name))
// Create the Claims
claims := KongJWTClaims{
jwtCred.Key,
c.name,
jwt.StandardClaims{
Issuer: EdgeXKong,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(jwtCred.Secret))
default:
e := fmt.Sprintf("failed to create JWT for consumer %s with errorCode %d", c.name, resp.StatusCode)
c.loggingClient.Error(e)
return "", errors.New(e)
}
}
//createOAuth2Token implements the two curl command below. Using these two curl commands below against KONG to request OAuth2 token.
//curl -X POST "http://localhost:8001/consumers/user123/oauth2" -d "name=www.edgexfoundry.org" --data "client_id=user123" -d "client_secret=user123" -d "redirect_uri=http://www.edgexfoundry.org/"
//curl -k -v https://localhost:8443/{service}/oauth2/token -d "client_id=user123" -d "grant_type=client_credentials" -d "client_secret=user123" -d "scope=email"
func (c *Consumer) createOAuth2Token() (string, error) {
ko := &KongConsumerOauth2{
Name: EdgeXKong,
ClientID: c.name,
ClientSecret: c.name,
RedirectURIS: "http://" + EdgeXKong,
}
formVals := url.Values{
"name": {ko.Name},
"client_id": {ko.ClientID},
"client_secret": {ko.ClientSecret},
"redirect_uris": {ko.RedirectURIS},
}
tokens := []string{c.configuration.KongURL.GetProxyBaseURL(), ConsumersPath, c.name, "oauth2"}
req, err := http.NewRequest(http.MethodPost, strings.Join(tokens, "/"), strings.NewReader(formVals.Encode()))
if err != nil {
e := fmt.Sprintf("failed to construct http POST form request: %s %s", c.name, err.Error())
c.loggingClient.Error(e)
return "", err
}
req.Header.Add(clients.ContentType, "application/x-www-form-urlencoded")
resp, err := c.client.Do(req)
if err != nil {
e := fmt.Sprintf("failed to enable oauth2 authentication for consumer %s with error %s", c.name, err.Error())
c.loggingClient.Error(e)
return "", err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK, http.StatusCreated, http.StatusConflict:
c.loggingClient.Info(fmt.Sprintf("successful on enabling oauth2 for consumer %s", c.name))
// obtain token
tokenreq := &KongOuath2TokenRequest{
ClientID: c.name,
ClientSecret: c.name,
GrantType: OAuth2GrantType,
Scope: OAuth2Scopes,
}
formVals := url.Values{
"client_id": {tokenreq.ClientID},
"client_secret": {tokenreq.ClientSecret},
"grant_type": {tokenreq.GrantType},
"scope": {tokenreq.Scope},
}
tokens := []string{c.configuration.KongURL.GetSecureURL(), c.configuration.KongAuth.Resource, "oauth2/token"}
c.loggingClient.Info(fmt.Sprintf("creating token on the endpoint of %s", strings.Join(tokens, "/")))
req, err := http.NewRequest(http.MethodPost, strings.Join(tokens, "/"), strings.NewReader(formVals.Encode()))
if err != nil {
c.loggingClient.Error(fmt.Sprintf("failed to create oauth2 token for client_id %s with error %s", c.name, err.Error()))
return "", err
}
req.Header.Add(clients.ContentType, "application/x-www-form-urlencoded")
tresp, err := c.client.Do(req)
if err != nil {
c.loggingClient.Error(fmt.Sprintf("failed to create oauth2 token for client_id %s with error %s", c.name, err.Error()))
return "", err
}
defer tresp.Body.Close()
token := KongOauth2Token{}
switch tresp.StatusCode {
case http.StatusOK, http.StatusCreated:
if err = json.NewDecoder(tresp.Body).Decode(&token); err != nil {
return "", err
}
c.loggingClient.Info(fmt.Sprintf("successful on retrieving bearer credential for consumer %s", c.name))
return token.AccessToken, nil
default:
b, err := ioutil.ReadAll(tresp.Body)
if err != nil {
return "", err
}
e := fmt.Sprintf("failed to create bearer token for oauth authentication at endpoint oauth2/token with error %s,%s", tresp.Status, string(b))
c.loggingClient.Error(e)
return "", errors.New(e)
}
default:
e := fmt.Sprintf("failed to enable oauth2 for consumer %s with error code %d", c.name, resp.StatusCode)
c.loggingClient.Error(e)
return "", errors.New(e)
}
}