-
Notifications
You must be signed in to change notification settings - Fork 0
/
authn.go
425 lines (343 loc) · 17.2 KB
/
authn.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package gokeycloak
import (
"context"
"io"
"net/http"
"github.com/golang-jwt/jwt/v4"
"github.com/segmentio/ksuid"
"github.com/zblocks/gokeycloak/pkg/jwx"
)
// LoginAdmin performs a login with Admin client
func (g *GoKeycloak) LoginAdmin(ctx context.Context, username, password, realm string) (int, *JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: StringP(adminClientID),
GrantType: StringP("password"),
Username: &username,
Password: &password,
})
}
// LoginClient performs a login with client credentials
func (g *GoKeycloak) LoginClient(ctx context.Context, clientID, clientSecret, realm string) (int, *JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("client_credentials"),
})
}
// LoginClientTokenExchange will exchange the presented token for a user's token
// Requires Token-Exchange is enabled: https://www.keycloak.org/docs/latest/securing_apps/index.html#_token-exchange
func (g *GoKeycloak) LoginClientTokenExchange(ctx context.Context, clientID, token, clientSecret, realm, targetClient, userID string) (int, *JWT, error) {
tokenOptions := TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("urn:ietf:params:oauth:grant-type:token-exchange"),
SubjectToken: &token,
RequestedTokenType: StringP("urn:ietf:params:oauth:token-type:refresh_token"),
Audience: &targetClient,
}
if userID != "" {
tokenOptions.RequestedSubject = &userID
}
return g.GetToken(ctx, realm, tokenOptions)
}
// LoginClientSignedJWT performs a login with client credentials and signed jwt claims
func (g *GoKeycloak) LoginClientSignedJWT(
ctx context.Context,
clientID,
realm string,
key interface{},
signedMethod jwt.SigningMethod,
expiresAt *jwt.NumericDate,
) (int, *JWT, error) {
claims := jwt.RegisteredClaims{
ExpiresAt: expiresAt,
Issuer: clientID,
Subject: clientID,
ID: ksuid.New().String(),
Audience: jwt.ClaimStrings{
g.getRealmURL(realm),
},
}
assertion, err := jwx.SignClaims(claims, key, signedMethod)
if err != nil {
return http.StatusInternalServerError, nil, err
}
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
GrantType: StringP("client_credentials"),
ClientAssertionType: StringP("urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),
ClientAssertion: &assertion,
})
}
// Login performs a login with user credentials and a client
func (g *GoKeycloak) Login(ctx context.Context, clientID, clientSecret, realm, username, password string) (int, *JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("password"),
Username: &username,
Password: &password,
Scope: StringP("openid"),
})
}
// LoginOtp performs a login with user credentials and otp token
func (g *GoKeycloak) LoginOtp(ctx context.Context, clientID, clientSecret, realm, username, password, totp string) (int, *JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("password"),
Username: &username,
Password: &password,
Totp: &totp,
})
}
// GetAuthenticationFlows get all authentication flows from a realm
func (g *GoKeycloak) GetAuthenticationFlows(ctx context.Context, token, realm string) (int, []*AuthenticationFlowRepresentation, error) {
const errMessage = "could not retrieve authentication flows"
var result []*AuthenticationFlowRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "authentication", "flows"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// GetAuthenticationFlow get an authentication flow with the given ID
func (g *GoKeycloak) GetAuthenticationFlow(ctx context.Context, token, realm string, authenticationFlowID string) (int, *AuthenticationFlowRepresentation, error) {
const errMessage = "could not retrieve authentication flows"
var result *AuthenticationFlowRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "authentication", "flows", authenticationFlowID))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// CreateAuthenticationFlow creates a new Authentication flow in a realm
func (g *GoKeycloak) CreateAuthenticationFlow(ctx context.Context, token, realm string, flow AuthenticationFlowRepresentation) (int, error) {
const errMessage = "could not create authentication flows"
var result []*AuthenticationFlowRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).SetBody(flow).
Post(g.getAdminRealmURL(realm, "authentication", "flows"))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// UpdateAuthenticationFlow a given Authentication Flow
func (g *GoKeycloak) UpdateAuthenticationFlow(ctx context.Context, token, realm string, flow AuthenticationFlowRepresentation, authenticationFlowID string) (int, *AuthenticationFlowRepresentation, error) {
const errMessage = "could not create authentication flows"
var result *AuthenticationFlowRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).SetBody(flow).
Put(g.getAdminRealmURL(realm, "authentication", "flows", authenticationFlowID))
if err = checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// DeleteAuthenticationFlow deletes a flow in a realm with the given ID
func (g *GoKeycloak) DeleteAuthenticationFlow(ctx context.Context, token, realm, flowID string) (int, error) {
const errMessage = "could not delete authentication flows"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
Delete(g.getAdminRealmURL(realm, "authentication", "flows", flowID))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// GetAuthenticationExecutions retrieves all executions of a given flow
func (g *GoKeycloak) GetAuthenticationExecutions(ctx context.Context, token, realm, flow string) (int, []*ModifyAuthenticationExecutionRepresentation, error) {
const errMessage = "could not retrieve authentication flows"
var result []*ModifyAuthenticationExecutionRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "authentication", "flows", flow, "executions"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// CreateAuthenticationExecution creates a new execution for the given flow name in the given realm
func (g *GoKeycloak) CreateAuthenticationExecution(ctx context.Context, token, realm, flow string, execution CreateAuthenticationExecutionRepresentation) (int, error) {
const errMessage = "could not create authentication execution"
resp, err := g.GetRequestWithBearerAuth(ctx, token).SetBody(execution).
Post(g.getAdminRealmURL(realm, "authentication", "flows", flow, "executions", "execution"))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// UpdateAuthenticationExecution updates an authentication execution for the given flow in the given realm
func (g *GoKeycloak) UpdateAuthenticationExecution(ctx context.Context, token, realm, flow string, execution ModifyAuthenticationExecutionRepresentation) (int, error) {
const errMessage = "could not update authentication execution"
resp, err := g.GetRequestWithBearerAuth(ctx, token).SetBody(execution).
Put(g.getAdminRealmURL(realm, "authentication", "flows", flow, "executions"))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// DeleteAuthenticationExecution delete a single execution with the given ID
func (g *GoKeycloak) DeleteAuthenticationExecution(ctx context.Context, token, realm, executionID string) (int, error) {
const errMessage = "could not delete authentication execution"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
Delete(g.getAdminRealmURL(realm, "authentication", "executions", executionID))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// CreateAuthenticationExecutionFlow creates a new execution for the given flow name in the given realm
func (g *GoKeycloak) CreateAuthenticationExecutionFlow(ctx context.Context, token, realm, flow string, executionFlow CreateAuthenticationExecutionFlowRepresentation) (int, error) {
const errMessage = "could not create authentication execution flow"
resp, err := g.GetRequestWithBearerAuth(ctx, token).SetBody(executionFlow).
Post(g.getAdminRealmURL(realm, "authentication", "flows", flow, "executions", "flow"))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// ------------------
// Identity Providers
// ------------------
// CreateIdentityProvider creates an identity provider in a realm
func (g *GoKeycloak) CreateIdentityProvider(ctx context.Context, token string, realm string, providerRep IdentityProviderRepresentation) (int, string, error) {
const errMessage = "could not create identity provider"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(providerRep).
Post(g.getAdminRealmURL(realm, "identity-provider", "instances"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), "", err
}
return resp.StatusCode(), getID(resp), nil
}
// GetIdentityProviders returns list of identity providers in a realm
func (g *GoKeycloak) GetIdentityProviders(ctx context.Context, token, realm string) (int, []*IdentityProviderRepresentation, error) {
const errMessage = "could not get identity providers"
var result []*IdentityProviderRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// GetIdentityProvider gets the identity provider in a realm
func (g *GoKeycloak) GetIdentityProvider(ctx context.Context, token, realm, alias string) (int, *IdentityProviderRepresentation, error) {
const errMessage = "could not get identity provider"
var result IdentityProviderRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances", alias))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), &result, nil
}
// UpdateIdentityProvider updates the identity provider in a realm
func (g *GoKeycloak) UpdateIdentityProvider(ctx context.Context, token, realm, alias string, providerRep IdentityProviderRepresentation) (int, error) {
const errMessage = "could not update identity provider"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(providerRep).
Put(g.getAdminRealmURL(realm, "identity-provider", "instances", alias))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// DeleteIdentityProvider deletes the identity provider in a realm
func (g *GoKeycloak) DeleteIdentityProvider(ctx context.Context, token, realm, alias string) (int, error) {
const errMessage = "could not delete identity provider"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
Delete(g.getAdminRealmURL(realm, "identity-provider", "instances", alias))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// ExportIDPPublicBrokerConfig exports the broker config for a given alias
func (g *GoKeycloak) ExportIDPPublicBrokerConfig(ctx context.Context, token, realm, alias string) (int, *string, error) {
const errMessage = "could not get public identity provider configuration"
resp, err := g.GetRequestWithBearerAuthXMLHeader(ctx, token).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "export"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
result := resp.String()
return resp.StatusCode(), &result, nil
}
// ImportIdentityProviderConfig parses and returns the identity provider config at a given URL
func (g *GoKeycloak) ImportIdentityProviderConfig(ctx context.Context, token, realm, fromURL, providerID string) (int, map[string]string, error) {
const errMessage = "could not import config"
result := make(map[string]string)
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
SetBody(map[string]string{
"fromUrl": fromURL,
"providerId": providerID,
}).
Post(g.getAdminRealmURL(realm, "identity-provider", "import-config"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// ImportIdentityProviderConfigFromFile parses and returns the identity provider config from a given file
func (g *GoKeycloak) ImportIdentityProviderConfigFromFile(ctx context.Context, token, realm, providerID, fileName string, fileBody io.Reader) (int, map[string]string, error) {
const errMessage = "could not import config"
result := make(map[string]string)
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
SetFileReader("file", fileName, fileBody).
SetFormData(map[string]string{
"providerId": providerID,
}).
Post(g.getAdminRealmURL(realm, "identity-provider", "import-config"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// CreateIdentityProviderMapper creates an instance of an identity provider mapper associated with the given alias
func (g *GoKeycloak) CreateIdentityProviderMapper(ctx context.Context, token, realm, alias string, mapper IdentityProviderMapper) (int, string, error) {
const errMessage = "could not create mapper for identity provider"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(mapper).
Post(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), "", err
}
return resp.StatusCode(), getID(resp), nil
}
// GetIdentityProviderMapper gets the mapper by id for the given identity provider alias in a realm
func (g *GoKeycloak) GetIdentityProviderMapper(ctx context.Context, token string, realm string, alias string, mapperID string) (int, *IdentityProviderMapper, error) {
const errMessage = "could not get identity provider mapper"
result := IdentityProviderMapper{}
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers", mapperID))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), &result, nil
}
// DeleteIdentityProviderMapper deletes an instance of an identity provider mapper associated with the given alias and mapper ID
func (g *GoKeycloak) DeleteIdentityProviderMapper(ctx context.Context, token, realm, alias, mapperID string) (int, error) {
const errMessage = "could not delete mapper for identity provider"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
Delete(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers", mapperID))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}
// GetIdentityProviderMappers returns list of mappers associated with an identity provider
func (g *GoKeycloak) GetIdentityProviderMappers(ctx context.Context, token, realm, alias string) (int, []*IdentityProviderMapper, error) {
const errMessage = "could not get identity provider mappers"
var result []*IdentityProviderMapper
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers"))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), result, nil
}
// GetIdentityProviderMapperByID gets the mapper of an identity provider
func (g *GoKeycloak) GetIdentityProviderMapperByID(ctx context.Context, token, realm, alias, mapperID string) (int, *IdentityProviderMapper, error) {
const errMessage = "could not get identity provider mappers"
var result IdentityProviderMapper
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers", mapperID))
if err := checkForError(resp, err, errMessage); err != nil {
return resp.StatusCode(), nil, err
}
return resp.StatusCode(), &result, nil
}
// UpdateIdentityProviderMapper updates mapper of an identity provider
func (g *GoKeycloak) UpdateIdentityProviderMapper(ctx context.Context, token, realm, alias string, mapper IdentityProviderMapper) (int, error) {
const errMessage = "could not update identity provider mapper"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(mapper).
Put(g.getAdminRealmURL(realm, "identity-provider", "instances", alias, "mappers", PString(mapper.ID)))
return resp.StatusCode(), checkForError(resp, err, errMessage)
}