forked from Nerzal/gocloak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
3685 lines (2779 loc) · 127 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
import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/go-resty/resty/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/segmentio/ksuid"
"github.com/sirockin/gocloak/pkg/jwx"
)
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
logoutEndpoint string
openIDConnect string
}
}
const (
adminClientID string = "admin-cli"
urlSeparator string = "/"
)
func makeURL(path ...string) string {
return strings.Join(path, urlSeparator)
}
func (client *gocloak) getRequest(ctx context.Context) *resty.Request {
var err HTTPErrorResponse
return injectTracingHeaders(
ctx, client.restyClient.R().
SetContext(ctx).
SetError(&err),
)
}
func (client *gocloak) getRequestWithBearerAuthNoCache(ctx context.Context, token string) *resty.Request {
return client.getRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json").
SetHeader("Cache-Control", "no-cache")
}
func (client *gocloak) getRequestWithBearerAuth(ctx context.Context, token string) *resty.Request {
return client.getRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json")
}
func (client *gocloak) getRequestWithBearerAuthXMLHeader(ctx context.Context, token string) *resty.Request {
return client.getRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/xml;charset=UTF-8")
}
func (client *gocloak) getRequestWithBasicAuth(ctx context.Context, clientID, clientSecret string) *resty.Request {
req := client.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 (client *gocloak) getRequestingParty(ctx context.Context, token string, realm string, options RequestingPartyTokenOptions, res interface{}) (*resty.Response, error) {
return client.getRequestWithBearerAuth(ctx, token).
SetFormData(options.FormData()).
SetFormDataFromValues(url.Values{"permission": PStringSlice(options.Permissions)}).
SetResult(&res).
Post(client.getRealmURL(realm, client.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("auth", "admin", "realms")
c.Config.authRealms = makeURL("auth", "realms")
c.Config.tokenEndpoint = makeURL("protocol", "openid-connect", "token")
c.Config.logoutEndpoint = makeURL("protocol", "openid-connect", "logout")
c.Config.openIDConnect = makeURL("protocol", "openid-connect")
for _, option := range options {
option(&c)
}
return &c
}
func (client *gocloak) RestyClient() *resty.Client {
return client.restyClient
}
func (client *gocloak) SetRestyClient(restyClient *resty.Client) {
client.restyClient = restyClient
}
func (client *gocloak) getRealmURL(realm string, path ...string) string {
path = append([]string{client.basePath, client.Config.authRealms, realm}, path...)
return makeURL(path...)
}
func (client *gocloak) getAdminRealmURL(realm string, path ...string) string {
path = append([]string{client.basePath, client.Config.authAdminRealms, realm}, path...)
return makeURL(path...)
}
// ==== Functional Options ===
// SetAuthRealms sets the auth realm
func SetAuthRealms(url string) func(client *gocloak) {
return func(client *gocloak) {
client.Config.authRealms = url
}
}
// SetAuthAdminRealms sets the auth admin realm
func SetAuthAdminRealms(url string) func(client *gocloak) {
return func(client *gocloak) {
client.Config.authAdminRealms = url
}
}
// SetTokenEndpoint sets the token endpoint
func SetTokenEndpoint(url string) func(client *gocloak) {
return func(client *gocloak) {
client.Config.tokenEndpoint = url
}
}
// SetLogoutEndpoint sets the logout
func SetLogoutEndpoint(url string) func(client *gocloak) {
return func(client *gocloak) {
client.Config.logoutEndpoint = url
}
}
// SetOpenIDConnectEndpoint sets the logout
func SetOpenIDConnectEndpoint(url string) func(client *gocloak) {
return func(client *gocloak) {
client.Config.openIDConnect = url
}
}
// SetCertCacheInvalidationTime sets the logout
func SetCertCacheInvalidationTime(duration time.Duration) func(client *gocloak) {
return func(client *gocloak) {
client.Config.CertsInvalidateTime = duration
}
}
func (client *gocloak) GetServerInfo(ctx context.Context, accessToken string) (*ServerInfoRepesentation, error) {
errMessage := "could not get server info"
var result ServerInfoRepesentation
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(makeURL(client.basePath, "auth", "admin", "serverinfo"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetUserInfo calls the UserInfo endpoint
func (client *gocloak) GetUserInfo(ctx context.Context, accessToken, realm string) (*UserInfo, error) {
const errMessage = "could not get user info"
var result UserInfo
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(client.getRealmURL(realm, client.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 (client *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 := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(client.getRealmURL(realm, client.Config.openIDConnect, "userinfo"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return result, nil
}
func (client *gocloak) getNewCerts(ctx context.Context, realm string) (*CertResponse, error) {
const errMessage = "could not get newCerts"
var result CertResponse
resp, err := client.getRequest(ctx).
SetResult(&result).
Get(client.getRealmURL(realm, client.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 (client *gocloak) GetCerts(ctx context.Context, realm string) (*CertResponse, error) {
const errMessage = "could not get certs"
if cert, ok := client.certsCache.Load(realm); ok {
return cert.(*CertResponse), nil
}
client.certsLock.Lock()
defer client.certsLock.Unlock()
if cert, ok := client.certsCache.Load(realm); ok {
return cert.(*CertResponse), nil
}
cert, err := client.getNewCerts(ctx, realm)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
client.certsCache.Store(realm, cert)
time.AfterFunc(client.Config.CertsInvalidateTime, func() {
client.certsCache.Delete(realm)
})
return cert, nil
}
// GetIssuer gets the issuer of the given realm
func (client *gocloak) GetIssuer(ctx context.Context, realm string) (*IssuerResponse, error) {
const errMessage = "could not get issuer"
var result IssuerResponse
resp, err := client.getRequest(ctx).
SetResult(&result).
Get(client.getRealmURL(realm))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// RetrospectToken calls the openid-connect introspect endpoint
func (client *gocloak) RetrospectToken(ctx context.Context, accessToken, clientID, clientSecret, realm string) (*RetrospecTokenResult, error) {
const errMessage = "could not introspect requesting party token"
var result RetrospecTokenResult
resp, err := client.getRequestWithBasicAuth(ctx, clientID, clientSecret).
SetFormData(map[string]string{
"token_type_hint": "requesting_party_token",
"token": accessToken,
}).
SetResult(&result).
Post(client.getRealmURL(realm, client.Config.tokenEndpoint, "introspect"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// DecodeAccessToken decodes the accessToken
func (client *gocloak) DecodeAccessToken(ctx context.Context, accessToken, realm string) (*jwt.Token, *jwt.MapClaims, error) {
const errMessage = "could not decode access token"
accessToken = strings.Replace(accessToken, "Bearer ", "", 1)
decodedHeader, err := jwx.DecodeAccessTokenHeader(accessToken)
if err != nil {
return nil, nil, errors.Wrap(err, errMessage)
}
certResult, err := client.GetCerts(ctx, realm)
if err != nil {
return nil, nil, errors.Wrap(err, errMessage)
}
if certResult.Keys == nil {
return nil, 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, nil, errors.Wrap(errors.New("cannot find a key to decode the token"), errMessage)
}
return jwx.DecodeAccessToken(accessToken, usedKey.E, usedKey.N)
}
// DecodeAccessTokenCustomClaims decodes the accessToken and writes claims into the given claims
func (client *gocloak) DecodeAccessTokenCustomClaims(ctx context.Context, accessToken, realm string, claims jwt.Claims) (*jwt.Token, error) {
const errMessage = "could not decode access token with custom claims"
accessToken = strings.Replace(accessToken, "Bearer ", "", 1)
decodedHeader, err := jwx.DecodeAccessTokenHeader(accessToken)
if err != nil {
return nil, errors.Wrap(err, errMessage)
}
certResult, err := client.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)
}
return jwx.DecodeAccessTokenCustomClaims(accessToken, usedKey.E, usedKey.N, claims)
}
func (client *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 = client.getRequestWithBasicAuth(ctx, *options.ClientID, *options.ClientSecret)
} else {
req = client.getRequest(ctx)
}
resp, err := req.SetFormData(options.FormData()).
SetResult(&token).
Post(client.getRealmURL(realm, client.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 (client *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 := client.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 (client *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 := client.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 (client *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 := client.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 (client *gocloak) RefreshToken(ctx context.Context, refreshToken, clientID, clientSecret, realm string) (*JWT, error) {
return client.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("refresh_token"),
RefreshToken: &refreshToken,
})
}
// LoginAdmin performs a login with Admin client
func (client *gocloak) LoginAdmin(ctx context.Context, username, password, realm string) (*JWT, error) {
return client.GetToken(ctx, realm, TokenOptions{
ClientID: StringP(adminClientID),
GrantType: StringP("password"),
Username: &username,
Password: &password,
})
}
// Login performs a login with client credentials
func (client *gocloak) LoginClient(ctx context.Context, clientID, clientSecret, realm string) (*JWT, error) {
return client.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 (client *gocloak) LoginClientTokenExchange(ctx context.Context, clientID, token, clientSecret, realm, targetClient, userID string) (*JWT, error) {
return client.GetToken(ctx, realm, 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,
RequestedSubject: &userID,
})
}
// LoginClientSignedJWT performs a login with client credentials and signed jwt claims
func (client *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{
client.getRealmURL(realm),
},
}
assertion, err := jwx.SignClaims(claims, key, signedMethod)
if err != nil {
return nil, err
}
return client.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 (client *gocloak) Login(ctx context.Context, clientID, clientSecret, realm, username, password string) (*JWT, error) {
return client.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("password"),
Username: &username,
Password: &password,
})
}
// LoginOtp performs a login with user credentials and otp token
func (client *gocloak) LoginOtp(ctx context.Context, clientID, clientSecret, realm, username, password, totp string) (*JWT, error) {
return client.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 (client *gocloak) Logout(ctx context.Context, clientID, clientSecret, realm, refreshToken string) error {
const errMessage = "could not logout"
resp, err := client.getRequestWithBasicAuth(ctx, clientID, clientSecret).
SetFormData(map[string]string{
"client_id": clientID,
"refresh_token": refreshToken,
}).
Post(client.getRealmURL(realm, client.Config.logoutEndpoint))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) LogoutPublicClient(ctx context.Context, clientID, realm, accessToken, refreshToken string) error {
const errMessage = "could not logout public client"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetFormData(map[string]string{
"client_id": clientID,
"refresh_token": refreshToken,
}).
Post(client.getRealmURL(realm, client.Config.logoutEndpoint))
return checkForError(resp, err, errMessage)
}
// LogoutAllSessions logs out all sessions of a user given an id
func (client *gocloak) LogoutAllSessions(ctx context.Context, accessToken, realm, userID string) error {
const errMessage = "could not logout"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
Post(client.getAdminRealmURL(realm, "users", userID, "logout"))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) RevokeUserConsents(ctx context.Context, accessToken, realm, userID, clientID string) error {
const errMessage = "could not revoke consents"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
Delete(client.getAdminRealmURL(realm, "users", userID, "consents", clientID))
return checkForError(resp, err, errMessage)
}
// LogoutUserSessions logs out a single sessions of a user given a session id
func (client *gocloak) LogoutUserSession(ctx context.Context, accessToken, realm, session string) error {
const errMessage = "could not logout"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
Delete(client.getAdminRealmURL(realm, "sessions", session))
return checkForError(resp, err, errMessage)
}
// ExecuteActionsEmail executes an actions email
func (client *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 := client.getRequestWithBearerAuth(ctx, token).
SetBody(params.Actions).
SetQueryParams(queryParams).
Put(client.getAdminRealmURL(realm, "users", *(params.UserID), "execute-actions-email"))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) CreateGroup(ctx context.Context, token, realm string, group Group) (string, error) {
const errMessage = "could not create group"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(group).
Post(client.getAdminRealmURL(realm, "groups"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateChildGroup creates a new child group
func (client *gocloak) CreateChildGroup(ctx context.Context, token, realm, groupID string, group Group) (string, error) {
const errMessage = "could not create child group"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(group).
Post(client.getAdminRealmURL(realm, "groups", groupID, "children"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
func (client *gocloak) CreateComponent(ctx context.Context, token, realm string, component Component) (string, error) {
const errMessage = "could not create component"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(component).
Post(client.getAdminRealmURL(realm, "components"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
func (client *gocloak) CreateClient(ctx context.Context, accessToken, realm string, newClient Client) (string, error) {
const errMessage = "could not create client"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetBody(newClient).
Post(client.getAdminRealmURL(realm, "clients"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
// CreateClientRepresentation creates a new client representation
func (client *gocloak) CreateClientRepresentation(ctx context.Context, realm string) (*Client, error) {
const errMessage = "could not create client representation"
var result Client
resp, err := client.getRequest(ctx).
SetResult(&result).
SetBody(Client{}).
Post(client.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 (client *gocloak) CreateClientRole(ctx context.Context, token, realm, idOfClient string, role Role) (string, error) {
const errMessage = "could not create client role"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(role).
Post(client.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 (client *gocloak) CreateClientScope(ctx context.Context, token, realm string, scope ClientScope) (string, error) {
const errMessage = "could not create client scope"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(scope).
Post(client.getAdminRealmURL(realm, "client-scopes"))
if err := checkForError(resp, err, errMessage); err != nil {
return "", err
}
return getID(resp), nil
}
func (client *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 := client.getRequestWithBearerAuth(ctx, token).
SetBody(updatedGroup).
Put(client.getAdminRealmURL(realm, "groups", PString(updatedGroup.ID)))
return checkForError(resp, err, errMessage)
}
// UpdateClient updates the given Client
func (client *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 := client.getRequestWithBearerAuth(ctx, token).
SetBody(updatedClient).
Put(client.getAdminRealmURL(realm, "clients", PString(updatedClient.ID)))
return checkForError(resp, err, errMessage)
}
// UpdateClientRepresentation updates the given client representation
func (client *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 := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
SetBody(updatedClient).
Put(client.getRealmURL(realm, "clients-registrations", "default", PString(updatedClient.ID)))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
func (client *gocloak) UpdateRole(ctx context.Context, token, realm, idOfClient string, role Role) error {
const errMessage = "could not update role"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(role).
Put(client.getAdminRealmURL(realm, "clients", idOfClient, "roles", PString(role.Name)))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) UpdateClientScope(ctx context.Context, token, realm string, scope ClientScope) error {
const errMessage = "could not update client scope"
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetBody(scope).
Put(client.getAdminRealmURL(realm, "client-scopes", PString(scope.ID)))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) DeleteGroup(ctx context.Context, token, realm, groupID string) error {
const errMessage = "could not delete group"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "groups", groupID))
return checkForError(resp, err, errMessage)
}
// DeleteClient deletes a given client
func (client *gocloak) DeleteClient(ctx context.Context, token, realm, idOfClient string) error {
const errMessage = "could not delete client"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "clients", idOfClient))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) DeleteComponent(ctx context.Context, token, realm, componentID string) error {
const errMessage = "could not delete component"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "components", componentID))
return checkForError(resp, err, errMessage)
}
// DeleteClientRepresentation deletes a given client representation
func (client *gocloak) DeleteClientRepresentation(ctx context.Context, accessToken, realm, clientID string) error {
const errMessage = "could not delete client representation"
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
Delete(client.getRealmURL(realm, "clients-registrations", "default", clientID))
return checkForError(resp, err, errMessage)
}
// DeleteClientRole deletes a given role
func (client *gocloak) DeleteClientRole(ctx context.Context, token, realm, idOfClient, roleName string) error {
const errMessage = "could not delete client role"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "clients", idOfClient, "roles", roleName))
return checkForError(resp, err, errMessage)
}
func (client *gocloak) DeleteClientScope(ctx context.Context, token, realm, scopeID string) error {
const errMessage = "could not delete client scope"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "client-scopes", scopeID))
return checkForError(resp, err, errMessage)
}
// GetClient returns a client
func (client *gocloak) GetClient(ctx context.Context, token, realm, idOfClient string) (*Client, error) {
const errMessage = "could not get client"
var result Client
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(client.getAdminRealmURL(realm, "clients", idOfClient))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetClientRepresentation returns a client representation
func (client *gocloak) GetClientRepresentation(ctx context.Context, accessToken, realm, clientID string) (*Client, error) {
const errMessage = "could not get client representation"
var result Client
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(client.getRealmURL(realm, "clients-registrations", "default", clientID))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetAdapterConfiguration returns a adapter configuration
func (client *gocloak) GetAdapterConfiguration(ctx context.Context, accessToken, realm, clientID string) (*AdapterConfiguration, error) {
const errMessage = "could not get adapter configuration"
var result AdapterConfiguration
resp, err := client.getRequestWithBearerAuth(ctx, accessToken).
SetResult(&result).
Get(client.getRealmURL(realm, "clients-registrations", "install", clientID))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return &result, nil
}
// GetClientsDefaultScopes returns a list of the client's default scopes
func (client *gocloak) GetClientsDefaultScopes(ctx context.Context, token, realm, idOfClient string) ([]*ClientScope, error) {
const errMessage = "could not get clients default scopes"
var result []*ClientScope
resp, err := client.getRequestWithBearerAuth(ctx, token).
SetResult(&result).
Get(client.getAdminRealmURL(realm, "clients", idOfClient, "default-client-scopes"))
if err := checkForError(resp, err, errMessage); err != nil {
return nil, err
}
return result, nil
}
// AddDefaultScopeToClient adds a client scope to the list of client's default scopes
func (client *gocloak) AddDefaultScopeToClient(ctx context.Context, token, realm, idOfClient, scopeID string) error {
const errMessage = "could not add default scope to client"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Put(client.getAdminRealmURL(realm, "clients", idOfClient, "default-client-scopes", scopeID))
return checkForError(resp, err, errMessage)
}
// RemoveDefaultScopeFromClient removes a client scope from the list of client's default scopes
func (client *gocloak) RemoveDefaultScopeFromClient(ctx context.Context, token, realm, idOfClient, scopeID string) error {
const errMessage = "could not remove default scope from client"
resp, err := client.getRequestWithBearerAuth(ctx, token).
Delete(client.getAdminRealmURL(realm, "clients", idOfClient, "default-client-scopes", scopeID))
return checkForError(resp, err, errMessage)
}
// GetClientsOptionalScopes returns a list of the client's optional scopes
func (client *gocloak) GetClientsOptionalScopes(ctx context.Context, token, realm, idOfClient string) ([]*ClientScope, error) {
const errMessage = "could not get clients optional scopes"
var result []*ClientScope
resp, err := client.getRequestWithBearerAuth(ctx, token).