-
Notifications
You must be signed in to change notification settings - Fork 3
/
admin.go
170 lines (148 loc) · 6.33 KB
/
admin.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
package keycloak
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
const (
adminClientID = "admin-cli"
masterRealm = "master"
)
// Token represents a Keycloak token.
type Token struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
ExpiresIn int `json:"expires_in"`
RefreshExpiresIn int `json:"refresh_expires_in"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
NotBeforePolicy int `json:"not-before-policy"`
SessionState string `json:"session_state"`
Scope string `json:"scope"`
}
// Client represents a Keycloak client(https://www.keycloak.org/docs-api/19.0.3/javadocs/org/keycloak/representations/idm/ClientRepresentation.html).
type Client struct {
Access *map[string]interface{} `json:"access,omitempty"`
AdminURL *string `json:"adminUrl,omitempty"`
Attributes *map[string]string `json:"attributes,omitempty"`
AuthenticationFlowBindingOverrides *map[string]string `json:"authenticationFlowBindingOverrides,omitempty"`
AuthorizationServicesEnabled *bool `json:"authorizationServicesEnabled,omitempty"`
BaseURL *string `json:"baseUrl,omitempty"`
BearerOnly *bool `json:"bearerOnly,omitempty"`
ClientAuthenticatorType *string `json:"clientAuthenticatorType,omitempty"`
ClientID *string `json:"clientId,omitempty"`
ConsentRequired *bool `json:"consentRequired,omitempty"`
DefaultClientScopes *[]string `json:"defaultClientScopes,omitempty"`
DefaultRoles *[]string `json:"defaultRoles,omitempty"`
Description *string `json:"description,omitempty"`
DirectAccessGrantsEnabled *bool `json:"directAccessGrantsEnabled,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
FrontChannelLogout *bool `json:"frontchannelLogout,omitempty"`
FullScopeAllowed *bool `json:"fullScopeAllowed,omitempty"`
ID *string `json:"id,omitempty"`
ImplicitFlowEnabled *bool `json:"implicitFlowEnabled,omitempty"`
Name *string `json:"name,omitempty"`
NodeReRegistrationTimeout *int32 `json:"nodeReRegistrationTimeout,omitempty"`
NotBefore *int32 `json:"notBefore,omitempty"`
OptionalClientScopes *[]string `json:"optionalClientScopes,omitempty"`
Origin *string `json:"origin,omitempty"`
Protocol *string `json:"protocol,omitempty"`
PublicClient *bool `json:"publicClient,omitempty"`
RedirectURIs *[]string `json:"redirectUris,omitempty"`
RegisteredNodes *map[string]int `json:"registeredNodes,omitempty"`
RegistrationAccessToken *string `json:"registrationAccessToken,omitempty"`
RootURL *string `json:"rootUrl,omitempty"`
Secret *string `json:"secret,omitempty"`
ServiceAccountsEnabled *bool `json:"serviceAccountsEnabled,omitempty"`
StandardFlowEnabled *bool `json:"standardFlowEnabled,omitempty"`
SurrogateAuthRequired *bool `json:"surrogateAuthRequired,omitempty"`
WebOrigins *[]string `json:"webOrigins,omitempty"`
}
// AdminClient is a Keycloak admin client.
type AdminClient struct {
ServerURL string
Realm string
Username string
Password string
ClientID string
UseTLS bool
client *http.Client
}
// NewAdminClient creates a new Keycloak admin client.
func NewAdminClient(ctx *context.Context, serverURL, username, password string) (*AdminClient, error) {
adminClient := &AdminClient{
ServerURL: serverURL,
Realm: masterRealm,
Username: username,
Password: password,
ClientID: adminClientID,
}
if (*ctx).Value(http.Client{}) == nil {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
adminClient.client = &http.Client{Transport: tr}
} else {
adminClient.client = (*ctx).Value(http.Client{}).(*http.Client)
}
// test connection
if _, err := adminClient.getToken(); err != nil {
return nil, err
}
return adminClient, nil
}
// GetClient returns a Keycloak client.
func (a *AdminClient) GetClient(realm string, clientID string) (*Client, error) {
token, err := a.getToken()
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", a.ServerURL+"/admin/realms/"+realm+"/clients", nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+token.AccessToken)
resp, err := a.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var clients []Client
if err = json.NewDecoder(resp.Body).Decode(&clients); err != nil {
return nil, err
}
for _, c := range clients {
if *c.ClientID == clientID {
return &c, nil
}
}
return nil, fmt.Errorf("client not found")
}
func (a *AdminClient) getToken() (*Token, error) {
var token Token
resp, err := a.client.PostForm(
a.ServerURL+"/realms/"+a.Realm+"/protocol/openid-connect/token",
url.Values{
"grant_type": {"password"},
"client_id": {a.ClientID},
"username": {a.Username},
"password": {a.Password},
},
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&token); err != nil {
return nil, err
}
return &token, nil
}
// ClientContext returns a new context with the given HTTP client
// Used to pass a custom HTTP client to the AdminClient
func ClientContext(ctx context.Context, client *http.Client) context.Context {
return context.WithValue(ctx, http.Client{}, client)
}