-
Notifications
You must be signed in to change notification settings - Fork 287
/
client.go
4509 lines (3425 loc) · 153 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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package gocloak is a golang keycloak adaptor.
package gocloak
import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
"github.com/golang-jwt/jwt/v5"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/segmentio/ksuid"
"golang.org/x/mod/semver"
"github.com/Nerzal/gocloak/v13/pkg/jwx"
)
// GoCloak provides functionalities to talk to Keycloak.
type GoCloak struct {
basePath string
certsCache sync.Map
certsLock sync.Mutex
restyClient *resty.Client
Config struct {
CertsInvalidateTime time.Duration
authAdminRealms string
authRealms string
tokenEndpoint string
revokeEndpoint string
logoutEndpoint string
openIDConnect string
attackDetection string
version string
}
}
// Verify struct implements interface
var _ GoCloakIface = &GoCloak{}
const (
adminClientID string = "admin-cli"
urlSeparator string = "/"
)
func makeURL(path ...string) string {
return strings.Join(path, urlSeparator)
}
// Compares the provided version against the current version of the Keycloak server.
// Current version is fetched from the serverinfo if not already set.
//
// Returns:
//
// -1 if the provided version is lower than the server version
//
// 0 if the provided version is equal to the server version
//
// 1 if the provided version is higher than the server version
func (g *GoCloak) compareVersions(v, token string, ctx context.Context) (int, error) {
curVersion := g.Config.version
if curVersion == "" {
curV, err := g.getServerVersion(ctx, token)
if err != nil {
return 0, err
}
curVersion = curV
}
curVersion = "v" + g.Config.version
if v[0] != 'v' {
v = "v" + v
}
return semver.Compare(curVersion, v), nil
}
// Get the server version from the serverinfo endpoint.
// If the version is already set, it will return the cached version.
// Otherwise, it will fetch the version from the serverinfo endpoint and cache it.
func (g *GoCloak) getServerVersion(ctx context.Context, token string) (string, error) {
if g.Config.version != "" {
return g.Config.version, nil
}
serverInfo, err := g.GetServerInfo(ctx, token)
if err != nil {
return "", err
}
g.Config.version = *(serverInfo.SystemInfo.Version)
return g.Config.version, nil
}
// GetRequest returns a request for calling endpoints.
func (g *GoCloak) GetRequest(ctx context.Context) *resty.Request {
var err HTTPErrorResponse
return injectTracingHeaders(
ctx, g.restyClient.R().
SetContext(ctx).
SetError(&err),
)
}
// GetRequestWithBearerAuthNoCache returns a JSON base request configured with an auth token and no-cache header.
func (g *GoCloak) GetRequestWithBearerAuthNoCache(ctx context.Context, token string) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json").
SetHeader("Cache-Control", "no-cache")
}
// GetRequestWithBearerAuth returns a JSON base request configured with an auth token.
func (g *GoCloak) GetRequestWithBearerAuth(ctx context.Context, token string) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json")
}
// GetRequestWithBearerAuthXMLHeader returns an XML base request configured with an auth token.
func (g *GoCloak) GetRequestWithBearerAuthXMLHeader(ctx context.Context, token string) *resty.Request {
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/xml;charset=UTF-8")
}
// GetRequestWithBasicAuth returns a form data base request configured with basic auth.
func (g *GoCloak) GetRequestWithBasicAuth(ctx context.Context, clientID, clientSecret string) *resty.Request {
req := g.GetRequest(ctx).
SetHeader("Content-Type", "application/x-www-form-urlencoded")
// Public client doesn't require Basic Auth
if len(clientID) > 0 && len(clientSecret) > 0 {
httpBasicAuth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
req.SetHeader("Authorization", "Basic "+httpBasicAuth)
}
return req
}
func (g *GoCloak) getRequestingParty(ctx context.Context, token string, realm string, options RequestingPartyTokenOptions, res interface{}) (*resty.Response, error) {
return g.GetRequestWithBearerAuth(ctx, token).
SetFormData(options.FormData()).
SetFormDataFromValues(url.Values{"permission": PStringSlice(options.Permissions)}).
SetResult(&res).
Post(g.getRealmURL(realm, g.Config.tokenEndpoint))
}
func checkForError(resp *resty.Response, err error, errMessage string) error {
if err != nil {
return &APIError{
Code: 0,
Message: errors.Wrap(err, errMessage).Error(),
Type: ParseAPIErrType(err),
}
}
if resp == nil {
return &APIError{
Message: "empty response",
Type: ParseAPIErrType(err),
}
}
if resp.IsError() {
var msg string
if e, ok := resp.Error().(*HTTPErrorResponse); ok && e.NotEmpty() {
msg = fmt.Sprintf("%s: %s", resp.Status(), e)
} else {
msg = resp.Status()
}
return &APIError{
Code: resp.StatusCode(),
Message: msg,
Type: ParseAPIErrType(err),
}
}
return nil
}
func getID(resp *resty.Response) string {
header := resp.Header().Get("Location")
splittedPath := strings.Split(header, urlSeparator)
return splittedPath[len(splittedPath)-1]
}
func findUsedKey(usedKeyID string, keys []CertResponseKey) *CertResponseKey {
for _, key := range keys {
if *(key.Kid) == usedKeyID {
return &key
}
}
return nil
}
func injectTracingHeaders(ctx context.Context, req *resty.Request) *resty.Request {
// look for span in context, do nothing if span is not found
span := opentracing.SpanFromContext(ctx)
if span == nil {
return req
}
// look for tracer in context, use global tracer if not found
tracer, ok := ctx.Value(tracerContextKey).(opentracing.Tracer)
if !ok || tracer == nil {
tracer = opentracing.GlobalTracer()
}
// inject tracing header into request
err := tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
if err != nil {
return req
}
return req
}
// ===============
// Keycloak client
// ===============
// NewClient creates a new Client
func NewClient(basePath string, options ...func(*GoCloak)) *GoCloak {
c := GoCloak{
basePath: strings.TrimRight(basePath, urlSeparator),
restyClient: resty.New(),
}
c.Config.CertsInvalidateTime = 10 * time.Minute
c.Config.authAdminRealms = makeURL("admin", "realms")
c.Config.authRealms = makeURL("realms")
c.Config.tokenEndpoint = makeURL("protocol", "openid-connect", "token")
c.Config.logoutEndpoint = makeURL("protocol", "openid-connect", "logout")
c.Config.revokeEndpoint = makeURL("protocol", "openid-connect", "revoke")
c.Config.openIDConnect = makeURL("protocol", "openid-connect")
c.Config.attackDetection = makeURL("attack-detection", "brute-force")
for _, option := range options {
option(&c)
}
return &c
}
// RestyClient returns the internal resty g.
// This can be used to configure the g.
func (g *GoCloak) RestyClient() *resty.Client {
return g.restyClient
}
// SetRestyClient overwrites the internal resty g.
func (g *GoCloak) SetRestyClient(restyClient *resty.Client) {
g.restyClient = restyClient
}
func (g *GoCloak) getRealmURL(realm string, path ...string) string {
path = append([]string{g.basePath, g.Config.authRealms, realm}, path...)
return makeURL(path...)
}
func (g *GoCloak) getAdminRealmURL(realm string, path ...string) string {
path = append([]string{g.basePath, g.Config.authAdminRealms, realm}, path...)
return makeURL(path...)
}
func (g *GoCloak) getAttackDetectionURL(realm string, user string, path ...string) string {
path = append([]string{g.basePath, g.Config.authAdminRealms, realm, g.Config.attackDetection, user}, path...)
return makeURL(path...)
}
// ==== Functional Options ===
// SetLegacyWildFlySupport maintain legacy WildFly support.
func SetLegacyWildFlySupport() func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.authAdminRealms = makeURL("auth", "admin", "realms")
g.Config.authRealms = makeURL("auth", "realms")
}
}
// SetAuthRealms sets the auth realm
func SetAuthRealms(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.authRealms = url
}
}
// SetAuthAdminRealms sets the auth admin realm
func SetAuthAdminRealms(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.authAdminRealms = url
}
}
// SetTokenEndpoint sets the token endpoint
func SetTokenEndpoint(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.tokenEndpoint = url
}
}
// SetRevokeEndpoint sets the revoke endpoint
func SetRevokeEndpoint(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.revokeEndpoint = url
}
}
// SetLogoutEndpoint sets the logout
func SetLogoutEndpoint(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.logoutEndpoint = url
}
}
// SetOpenIDConnectEndpoint sets the logout
func SetOpenIDConnectEndpoint(url string) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.openIDConnect = url
}
}
// SetCertCacheInvalidationTime sets the logout
func SetCertCacheInvalidationTime(duration time.Duration) func(g *GoCloak) {
return func(g *GoCloak) {
g.Config.CertsInvalidateTime = duration
}
}
// GetServerInfo fetches the server info.
func (g *GoCloak) GetServerInfo(ctx context.Context, accessToken string) (*ServerInfoRepresentation, error) {
errMessage := "could not get server info"
var result *ServerInfoRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(makeURL(g.basePath, "admin", "serverinfo"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return result, nil
}
// GetUserInfo calls the UserInfo endpoint
func (g *GoCloak) GetUserInfo(ctx context.Context, accessToken, realm string) (*UserInfo, error) {
const errMessage = "could not get user info"
var result UserInfo
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(g.getRealmURL(realm, g.Config.openIDConnect, "userinfo"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetRawUserInfo calls the UserInfo endpoint and returns a raw json object
func (g *GoCloak) GetRawUserInfo(ctx context.Context, accessToken, realm string) (map[string]interface{}, error) {
const errMessage = "could not get user info"
var result map[string]interface{}
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(g.getRealmURL(realm, g.Config.openIDConnect, "userinfo"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return result, nil
}
func (g *GoCloak) getNewCerts(ctx context.Context, realm string) (*CertResponse, error) {
const errMessage = "could not get newCerts"
var result CertResponse
resp, err := g.GetRequest(ctx).
SetResult(&result).
Get(g.getRealmURL(realm, g.Config.openIDConnect, "certs"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetCerts fetches certificates for the given realm from the public /open-id-connect/certs endpoint
func (g *GoCloak) GetCerts(ctx context.Context, realm string) (*CertResponse, error) {
const errMessage = "could not get certs"
if cert, ok := g.certsCache.Load(realm); ok {
return cert.(*CertResponse), nil
}
g.certsLock.Lock()
defer g.certsLock.Unlock()
if cert, ok := g.certsCache.Load(realm); ok {
return cert.(*CertResponse), nil
}
cert, err := g.getNewCerts(ctx, realm)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
g.certsCache.Store(realm, cert)
time.AfterFunc(g.Config.CertsInvalidateTime, func() {
g.certsCache.Delete(realm)
})
return cert, nil
}
// GetIssuer gets the issuer of the given realm
func (g *GoCloak) GetIssuer(ctx context.Context, realm string) (*IssuerResponse, error) {
const errMessage = "could not get issuer"
var result IssuerResponse
resp, err := g.GetRequest(ctx).
SetResult(&result).
Get(g.getRealmURL(realm))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// RetrospectToken calls the openid-connect introspect endpoint
func (g *GoCloak) RetrospectToken(ctx context.Context, accessToken, clientID, clientSecret, realm string) (*IntroSpectTokenResult, error) {
const errMessage = "could not introspect requesting party token"
var result IntroSpectTokenResult
resp, err := g.GetRequestWithBasicAuth(ctx, clientID, clientSecret).
SetFormData(map[string]string{
"token_type_hint": "requesting_party_token",
"token": accessToken,
}).
SetResult(&result).
Post(g.getRealmURL(realm, g.Config.tokenEndpoint, "introspect"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
func (g *GoCloak) decodeAccessTokenWithClaims(ctx context.Context, accessToken, realm string, claims jwt.Claims) (*jwt.Token, error) {
const errMessage = "could not decode access token"
accessToken = strings.Replace(accessToken, "Bearer ", "", 1)
decodedHeader, err := jwx.DecodeAccessTokenHeader(accessToken)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
certResult, err := g.GetCerts(ctx, realm)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
if certResult.Keys == nil {
return nil, errors.Wrap(errors.New("there is no keys to decode the token"), errMessage)
}
usedKey := findUsedKey(decodedHeader.Kid, *certResult.Keys)
if usedKey == nil {
return nil, errors.Wrap(errors.New("cannot find a key to decode the token"), errMessage)
}
if strings.HasPrefix(decodedHeader.Alg, "ES") {
return jwx.DecodeAccessTokenECDSACustomClaims(accessToken, usedKey.X, usedKey.Y, usedKey.Crv, claims)
} else if strings.HasPrefix(decodedHeader.Alg, "RS") {
return jwx.DecodeAccessTokenRSACustomClaims(accessToken, usedKey.E, usedKey.N, claims)
}
return nil, fmt.Errorf("unsupported algorithm")
}
// DecodeAccessToken decodes the accessToken
func (g *GoCloak) DecodeAccessToken(ctx context.Context, accessToken, realm string) (*jwt.Token, *jwt.MapClaims, error) {
claims := jwt.MapClaims{}
token, err := g.decodeAccessTokenWithClaims(ctx, accessToken, realm, claims)
if err != nil {
return nil, nil, err
}
return token, &claims, nil
}
// DecodeAccessTokenCustomClaims decodes the accessToken and writes claims into the given claims
func (g *GoCloak) DecodeAccessTokenCustomClaims(ctx context.Context, accessToken, realm string, claims jwt.Claims) (*jwt.Token, error) {
return g.decodeAccessTokenWithClaims(ctx, accessToken, realm, claims)
}
// GetToken uses TokenOptions to fetch a token.
func (g *GoCloak) GetToken(ctx context.Context, realm string, options TokenOptions) (*JWT, error) {
const errMessage = "could not get token"
var token JWT
var req *resty.Request
if !NilOrEmpty(options.ClientSecret) {
req = g.GetRequestWithBasicAuth(ctx, *options.ClientID, *options.ClientSecret)
} else {
req = g.GetRequest(ctx)
}
resp, err := req.SetFormData(options.FormData()).
SetResult(&token).
Post(g.getRealmURL(realm, g.Config.tokenEndpoint))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &token, nil
}
// GetRequestingPartyToken returns a requesting party token with permissions granted by the server
func (g *GoCloak) GetRequestingPartyToken(ctx context.Context, token, realm string, options RequestingPartyTokenOptions) (*JWT, error) {
const errMessage = "could not get requesting party token"
var res JWT
resp, err := g.getRequestingParty(ctx, token, realm, options, &res)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &res, nil
}
// GetRequestingPartyPermissions returns a requesting party permissions granted by the server
func (g *GoCloak) GetRequestingPartyPermissions(ctx context.Context, token, realm string, options RequestingPartyTokenOptions) (*[]RequestingPartyPermission, error) {
const errMessage = "could not get requesting party token"
var res []RequestingPartyPermission
options.ResponseMode = StringP("permissions")
resp, err := g.getRequestingParty(ctx, token, realm, options, &res)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &res, nil
}
// GetRequestingPartyPermissionDecision returns a requesting party permission decision granted by the server
func (g *GoCloak) GetRequestingPartyPermissionDecision(ctx context.Context, token, realm string, options RequestingPartyTokenOptions) (*RequestingPartyPermissionDecision, error) {
const errMessage = "could not get requesting party token"
var res RequestingPartyPermissionDecision
options.ResponseMode = StringP("decision")
resp, err := g.getRequestingParty(ctx, token, realm, options, &res)
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &res, nil
}
// RefreshToken refreshes the given token.
// May return a *APIError with further details about the issue.
func (g *GoCloak) RefreshToken(ctx context.Context, refreshToken, clientID, clientSecret, realm string) (*JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("refresh_token"),
RefreshToken: &refreshToken,
})
}
// LoginAdmin performs a login with Admin client
func (g *GoCloak) LoginAdmin(ctx context.Context, username, password, realm string) (*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 *GoCloak) LoginClient(ctx context.Context, clientID, clientSecret, realm string, scopes ...string) (*JWT, error) {
opts := TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("client_credentials"),
}
if len(scopes) > 0 {
opts.Scope = &scopes[0]
}
return g.GetToken(ctx, realm, opts)
}
// 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 *GoCloak) LoginClientTokenExchange(ctx context.Context, clientID, token, clientSecret, realm, targetClient, userID string) (*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)
}
// DirectNakedImpersonationTokenExchange performs "Direct Naked Impersonation"
// See: https://www.keycloak.org/docs/latest/securing_apps/index.html#direct-naked-impersonation
func (g *GoCloak) DirectNakedImpersonationTokenExchange(ctx context.Context, clientID, clientSecret, realm, userID string) (*JWT, error) {
tokenOptions := TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("urn:ietf:params:oauth:grant-type:token-exchange"),
RequestedTokenType: StringP("urn:ietf:params:oauth:token-type:refresh_token"),
RequestedSubject: StringP(userID),
}
return g.GetToken(ctx, realm, tokenOptions)
}
// LoginClientSignedJWT performs a login with client credentials and signed jwt claims
func (g *GoCloak) LoginClientSignedJWT(
ctx context.Context,
clientID,
realm string,
key interface{},
signedMethod jwt.SigningMethod,
expiresAt *jwt.NumericDate,
) (*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 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 *GoCloak) Login(ctx context.Context, clientID, clientSecret, realm, username, password string) (*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 *GoCloak) LoginOtp(ctx context.Context, clientID, clientSecret, realm, username, password, totp string) (*JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("password"),
Username: &username,
Password: &password,
Totp: &totp,
})
}
// Logout logs out users with refresh token
func (g *GoCloak) Logout(ctx context.Context, clientID, clientSecret, realm, refreshToken string) error {
const errMessage = "could not logout"
resp, err := g.GetRequestWithBasicAuth(ctx, clientID, clientSecret).
SetFormData(map[string]string{
"client_id": clientID,
"refresh_token": refreshToken,
}).
Post(g.getRealmURL(realm, g.Config.logoutEndpoint))
return checkForError(resp, err, errMessage)
}
// LogoutPublicClient performs a logout using a public client and the accessToken.
func (g *GoCloak) LogoutPublicClient(ctx context.Context, clientID, realm, accessToken, refreshToken string) error {
const errMessage = "could not logout public client"
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetFormData(map[string]string{
"client_id": clientID,
"refresh_token": refreshToken,
}).
Post(g.getRealmURL(realm, g.Config.logoutEndpoint))
return checkForError(resp, err, errMessage)
}
// LogoutAllSessions logs out all sessions of a user given an id.
func (g *GoCloak) LogoutAllSessions(ctx context.Context, accessToken, realm, userID string) error {
const errMessage = "could not logout"
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
Post(g.getAdminRealmURL(realm, "users", userID, "logout"))
return checkForError(resp, err, errMessage)
}
// RevokeUserConsents revokes the given user consent.
func (g *GoCloak) RevokeUserConsents(ctx context.Context, accessToken, realm, userID, clientID string) error {
const errMessage = "could not revoke consents"
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
Delete(g.getAdminRealmURL(realm, "users", userID, "consents", clientID))
return checkForError(resp, err, errMessage)
}
// LogoutUserSession logs out a single sessions of a user given a session id
func (g *GoCloak) LogoutUserSession(ctx context.Context, accessToken, realm, session string) error {
const errMessage = "could not logout"
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
Delete(g.getAdminRealmURL(realm, "sessions", session))
return checkForError(resp, err, errMessage)
}
// ExecuteActionsEmail executes an actions email
func (g *GoCloak) ExecuteActionsEmail(ctx context.Context, token, realm string, params ExecuteActionsEmail) error {
const errMessage = "could not execute actions email"
queryParams, err := GetQueryParams(params)
if err != nil {
return errors.Wrap(err, errMessage)
}
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(params.Actions).
SetQueryParams(queryParams).
Put(g.getAdminRealmURL(realm, "users", *(params.UserID), "execute-actions-email"))
return checkForError(resp, err, errMessage)
}
// SendVerifyEmail sends a verification e-mail to a user.
func (g *GoCloak) SendVerifyEmail(ctx context.Context, token, userID, realm string, params ...SendVerificationMailParams) error {
const errMessage = "failed to send verify email"
queryParams := map[string]string{}
if params != nil {
if params[0].ClientID != nil {
queryParams["client_id"] = *params[0].ClientID
}
if params[0].RedirectURI != nil {
queryParams["redirect_uri"] = *params[0].RedirectURI
}
}
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetQueryParams(queryParams).
Put(g.getAdminRealmURL(realm, "users", userID, "send-verify-email"))
return checkForError(resp, err, errMessage)
}
// CreateGroup creates a new group.
func (g *GoCloak) CreateGroup(ctx context.Context, token, realm string, group Group) (string, error) {
const errMessage = "could not create group"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(group).
Post(g.getAdminRealmURL(realm, "groups"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateChildGroup creates a new child group
func (g *GoCloak) CreateChildGroup(ctx context.Context, token, realm, groupID string, group Group) (string, error) {
const errMessage = "could not create child group"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(group).
Post(g.getAdminRealmURL(realm, "groups", groupID, "children"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateComponent creates the given component.
func (g *GoCloak) CreateComponent(ctx context.Context, token, realm string, component Component) (string, error) {
const errMessage = "could not create component"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(component).
Post(g.getAdminRealmURL(realm, "components"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateClient creates the given g.
func (g *GoCloak) CreateClient(ctx context.Context, accessToken, realm string, newClient Client) (string, error) {
const errMessage = "could not create client"
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetBody(newClient).
Post(g.getAdminRealmURL(realm, "clients"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateClientRepresentation creates a new client representation
func (g *GoCloak) CreateClientRepresentation(ctx context.Context, token, realm string, newClient Client) (*Client, error) {
const errMessage = "could not create client representation"
var result Client
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetResult(&result).
SetBody(newClient).
Post(g.getRealmURL(realm, "clients-registrations", "default"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// CreateClientRole creates a new role for a client
func (g *GoCloak) CreateClientRole(ctx context.Context, token, realm, idOfClient string, role Role) (string, error) {
const errMessage = "could not create client role"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(role).
Post(g.getAdminRealmURL(realm, "clients", idOfClient, "roles"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateClientScope creates a new client scope
func (g *GoCloak) CreateClientScope(ctx context.Context, token, realm string, scope ClientScope) (string, error) {
const errMessage = "could not create client scope"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(scope).
Post(g.getAdminRealmURL(realm, "client-scopes"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateClientScopeProtocolMapper creates a new protocolMapper under the given client scope
func (g *GoCloak) CreateClientScopeProtocolMapper(ctx context.Context, token, realm, scopeID string, protocolMapper ProtocolMappers) (string, error) {
const errMessage = "could not create client scope protocol mapper"
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(protocolMapper).
Post(g.getAdminRealmURL(realm, "client-scopes", scopeID, "protocol-mappers", "models"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// UpdateGroup updates the given group.
func (g *GoCloak) UpdateGroup(ctx context.Context, token, realm string, updatedGroup Group) error {
const errMessage = "could not update group"
if NilOrEmpty(updatedGroup.ID) {
return errors.Wrap(errors.New("ID of a group required"), errMessage)
}
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(updatedGroup).
Put(g.getAdminRealmURL(realm, "groups", PString(updatedGroup.ID)))
return checkForError(resp, err, errMessage)
}
// UpdateGroupManagementPermissions updates the given group management permissions
func (g *GoCloak) UpdateGroupManagementPermissions(ctx context.Context, accessToken, realm string, idOfGroup string, managementPermissions ManagementPermissionRepresentation) (*ManagementPermissionRepresentation, error) {
const errMessage = "could not update group management permissions"
var result ManagementPermissionRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
SetBody(managementPermissions).
Put(g.getAdminRealmURL(realm, "groups", idOfGroup, "management", "permissions"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// UpdateClient updates the given Client
func (g *GoCloak) UpdateClient(ctx context.Context, token, realm string, updatedClient Client) error {
const errMessage = "could not update client"
if NilOrEmpty(updatedClient.ID) {
return errors.Wrap(errors.New("ID of a client required"), errMessage)
}
resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetBody(updatedClient).
Put(g.getAdminRealmURL(realm, "clients", PString(updatedClient.ID)))
return checkForError(resp, err, errMessage)
}
// UpdateClientRepresentation updates the given client representation
func (g *GoCloak) UpdateClientRepresentation(ctx context.Context, accessToken, realm string, updatedClient Client) (*Client, error) {
const errMessage = "could not update client representation"
if NilOrEmpty(updatedClient.ID) {
return nil, errors.Wrap(errors.New("ID of a client required"), errMessage)
}
var result Client
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
SetBody(updatedClient).
Put(g.getRealmURL(realm, "clients-registrations", "default", PString(updatedClient.ClientID)))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// UpdateClientManagementPermissions updates the given client management permissions
func (g *GoCloak) UpdateClientManagementPermissions(ctx context.Context, accessToken, realm string, idOfClient string, managementPermissions ManagementPermissionRepresentation) (*ManagementPermissionRepresentation, error) {
const errMessage = "could not update client management permissions"
var result ManagementPermissionRepresentation
resp, err := g.GetRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
SetBody(managementPermissions).
Put(g.getAdminRealmURL(realm, "clients", idOfClient, "management", "permissions"))