-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
338 lines (297 loc) · 9.29 KB
/
client.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package keycloak
import (
// Error Handling
"errors"
// REST
"gopkg.in/resty.v1"
// Encoding
b64 "encoding/base64"
"encoding/json"
)
/**
* The OIDCToken holds all info about the token
*/
type OIDCToken struct {
AccessToken string
ExpiresIn float64
RefreshExpiresIn float64
RefreshToken string
TokenType string
}
/**
* The keycloak client kind-of class
*/
type KeycloakClient struct {
Server string
}
/**
* The Keycloak User Structure
*/
type KeycloakUser struct {
Id string `json:"id"`
CreatedTimestamp int64 `json:"createdTimestamp"`
Username string `json:"username"`
Enabled bool `json:"enabled"`
Totp bool `json:"totp"`
EmailVerified bool `json:"emailVerified"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email"`
FederationLink string `json:"federationLink"`
Attributes struct {
LDAPENTRYDN []string `json:"LDAP_ENTRY_DN"`
LDAPID []string `json:"LDAP_ID"`
} `json:"attributes"`
DisableableCredentialTypes []interface{} `json:"disableableCredentialTypes"`
RequiredActions []interface{} `json:"requiredActions"`
Access struct {
ManageGroupMembership bool `json:"manageGroupMembership"`
View bool `json:"view"`
MapRoles bool `json:"mapRoles"`
Impersonate bool `json:"impersonate"`
Manage bool `json:"manage"`
} `json:"access"`
}
/**
* Keycloak User Groups
*/
type KeycloakUserGroup struct {
Id string `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
}
/**
* The Keycloak Group Structure
*/
type KeycloakGroup struct {
Id string `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
SubGroups []interface{} `json:"subGroups"`
}
/**
* The Keycloak Role Structure
*/
type KeycloakRole struct {
Id string `json:"id"`
Name string `json:"name"`
ScopeParamRequired bool `json:"scopeParamRequired"`
Composite bool `json:"composite"`
ClientRole bool `json:"clientRole"`
ContainerID string `json:"containerId"`
Description string `json:"description,omitempty"`
}
/**
* Role Mapping for Clients
*/
type ClientRoleMapping struct {
ID string `json:"id"`
Client string `json:"client"`
Mappings []ClientRoleMappingRole `json:"mappings"`
}
type ClientRoleMappingRole struct {
Id string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
ScopeParamRequired bool `json:"scopeParamRequired"`
Composite bool `json:"composite"`
ClientRole bool `json:"clientRole"`
ContainerID string `json:"containerId"`
}
/**
* Keycloak Client
*/
type KeycloakRealmClient struct {
Id string `json:"id"`
ClientID string `json:"clientId"`
}
/**
* Direct Grant Authentication
* -
* This method directly gets you the OIDC Token from keycloak to use in your next requests
*/
func (keycloakClient KeycloakClient) DirectGrantAuthentication(clientId string, clientSecret string, realm string, username string, password string) (*OIDCToken, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/x-www-form-urlencoded").
SetHeader("Authorization", getBasicAuthForClient(clientId, clientSecret)).
SetFormData(map[string]string{
"grant_type": "password",
"username": username,
"password": password,
}).Post(keycloakClient.Server + "/auth/realms/" + realm + "/protocol/openid-connect/token")
if err != nil {
return nil, err
}
// Here’s the actual decoding, and a check for associated errors.
var result map[string]interface{}
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
// Check for Result
if val, ok := result["access_token"]; ok {
_ = val
return &OIDCToken{
AccessToken: result["access_token"].(string),
ExpiresIn: result["expires_in"].(float64),
RefreshExpiresIn: result["refresh_expires_in"].(float64),
RefreshToken: result["refresh_token"].(string),
TokenType: result["token_type"].(string),
}, nil
}
return nil, errors.New("Authentication failed")
}
/**
* User List
*/
func (keycloakClient KeycloakClient) GetUserListInRealm(token *OIDCToken, realm string) (*[]KeycloakUser, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/users")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakUser
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Get Groups of UserId
*/
func (keycloakClient KeycloakClient) GetUserGroupsInRealm(token *OIDCToken, realm string, userId string) (*[]KeycloakUserGroup, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/users/" + userId + "/groups")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakUserGroup
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Get Group Role Mapping
*/
func (keycloakClient KeycloakClient) GetRoleMappingByGroupId(token *OIDCToken, realm string, groupId string) (*[]ClientRoleMapping, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/groups/" + groupId + "/role-mappings")
if err != nil {
return nil, err
}
var result []ClientRoleMapping
// Decode into struct
var f map[string]interface{}
if err := json.Unmarshal(resp.Body(), &f); err != nil {
return nil, err
}
// JSON object parses into a map with string keys
itemsMap := f["clientMappings"].(map[string]interface{})
// Loop through the Items; we're not interested in the key, just the values
for _, v := range itemsMap {
// Use type assertions to ensure that the value's a JSON object
switch jsonObj := v.(type) {
// The value is an Item, represented as a generic interface
case interface{}:
jsonClientMapping, _ := json.Marshal(jsonObj)
var client ClientRoleMapping
if err := json.Unmarshal(jsonClientMapping, &client); err != nil {
return nil, err
}
result = append(result, client)
default:
return nil, errors.New("Expecting a JSON object; got something else")
}
}
return &result, nil
}
/**
* Group List
*/
func (keycloakClient KeycloakClient) GetGroupListByRealm(token *OIDCToken, realm string) (*[]KeycloakGroup, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/groups")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakGroup
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Get Roles by Realm
*/
func (keycloakClient KeycloakClient) GetRolesByRealm(token *OIDCToken, realm string) (*[]KeycloakRole, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/roles")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakRole
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Get Roles by Client and Realm
*/
func (keycloakClient KeycloakClient) GetRolesByClientId(token *OIDCToken, realm string, clientId string) (*[]KeycloakRole, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/clients/" + clientId + "/roles")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakRole
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Get Clients by Realm
*/
func (keycloakClient KeycloakClient) GetClientsInRealm(token *OIDCToken, realm string) (*[]KeycloakRealmClient, error) {
resp, err := resty.R().
SetHeader("Content-Type", "application/json").
SetHeader("Authorization", "Bearer " + token.AccessToken).
Get(keycloakClient.Server + "/auth/admin/realms/" + realm + "/clients")
if err != nil {
return nil, err
}
// Decode into struct
var result []KeycloakRealmClient
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return nil, err
}
return &result, nil
}
/**
* Function to build the HttpBasicAuth Base64 String
*/
func getBasicAuthForClient(clientId string, clientSecret string) string {
var httpBasicAuth string
if len(clientId) > 0 && len(clientSecret) > 0 {
httpBasicAuth = b64.URLEncoding.EncodeToString([]byte(clientId + ":" + clientSecret))
}
return "Basic " + httpBasicAuth
}