Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: social login exchange token #332

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ test:
./run-tests.sh

start-keycloak: stop-keycloak
docker-compose up -d
docker compose up -d

stop-keycloak:
docker-compose down
docker compose down

start-keycloak-old: stop-keycloak
docker-compose up -d

stop-keycloak-old:
docker-compose down
29 changes: 25 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,27 +63,32 @@ func (g *GoCloak) GetRequestWithBearerAuthNoCache(ctx context.Context, token str
return g.GetRequest(ctx).
SetAuthToken(token).
SetHeader("Content-Type", "application/json").
SetHeader("Cache-Control", "no-cache")
SetHeader("Cache-Control", "no-cache").
SetHeader("Accept-Charset", "utf-8")
}

// 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")
SetHeader("Content-Type", "application/json").
SetHeader("Accept-Charset", "utf-8")
}

// 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")
SetHeader("Content-Type", "application/xml;charset=UTF-8").
SetHeader("Accept-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")
SetHeader("Content-Type", "application/x-www-form-urlencoded").
SetHeader("Accept-Charset", "utf-8")

// Public client doesn't require Basic Auth
if len(clientID) > 0 && len(clientSecret) > 0 {
httpBasicAuth := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
Expand Down Expand Up @@ -581,6 +586,21 @@ func (g *GoCloak) LoginClientTokenExchange(ctx context.Context, clientID, token,
return g.GetToken(ctx, realm, tokenOptions)
}

// LoginSocialTokenExchange 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#external-token-to-internal-token-exchange
func (g *GoCloak) LoginSocialTokenExchange(ctx context.Context, clientID, token, clientSecret, realm, issuer string) (*JWT, error) {
return g.GetToken(ctx, realm, TokenOptions{
ClientID: &clientID,
ClientSecret: &clientSecret,
GrantType: StringP("urn:ietf:params:oauth:grant-type:token-exchange"),
SubjectToken: &token,
SubjectIssuer: &issuer,
SubjectTokenType: StringP("urn:ietf:params:oauth:token-type:access_token"),
RequestedTokenType: StringP("urn:ietf:params:oauth:token-type:refresh_token"),
Scope: StringP("openid"),
})
}

// LoginClientSignedJWT performs a login with client credentials and signed jwt claims
func (g *GoCloak) LoginClientSignedJWT(
ctx context.Context,
Expand Down Expand Up @@ -4031,6 +4051,7 @@ func (g *GoCloak) UpdateCredentialUserLabel(ctx context.Context, token, realm, u

resp, err := g.GetRequestWithBearerAuth(ctx, token).
SetHeader("Content-Type", "text/plain").
SetHeader("Accept-Charset", "utf-8").
SetBody(userLabel).
Put(g.getAdminRealmURL(realm, "users", userID, "credentials", credentialID, "userLabel"))

Expand Down
69 changes: 68 additions & 1 deletion client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ type configGoCloak struct {
Password string `json:"password"`
Realm string `json:"realm"`
ClientID string `json:"client_id"`
Token string `json:"token"`
ClientSecret string `json:"client_secret"`
Issuer string `json:"issuer"`
TargetClient string `json:"audience"`
}

type Config struct {
Expand Down Expand Up @@ -1097,6 +1100,68 @@ func Test_LoginClient(t *testing.T) {
require.NoError(t, err, "LoginClient failed")
}

func Test_LoginSocialTokenExchange_UnknownRealm(t *testing.T) {
// t.Parallel()
cfg := GetConfig(t)
client := NewClientWithDebug(t)
_, err := client.LoginSocialTokenExchange(
context.Background(),
cfg.GoCloak.ClientID,
cfg.GoCloak.Token,
cfg.GoCloak.ClientSecret,
"ThisRealmDoesNotExists",
cfg.GoCloak.Issuer,
)

require.Error(t, err, "Login shouldn't be successful")
require.EqualError(t, err, "404 Not Found: Realm does not exist")
}

func Test_LoginSocialTokenExchange_UnknownIssuer(t *testing.T) {
// t.Parallel()
cfg := GetConfig(t)
client := NewClientWithDebug(t)
_, err := client.LoginSocialTokenExchange(
context.Background(),
cfg.GoCloak.ClientID,
cfg.GoCloak.Token,
cfg.GoCloak.ClientSecret,
cfg.GoCloak.Realm,
"ThisIssuerDoesNotExists",
)

require.Error(t, err, "Login shouldn't be successful")
require.EqualError(t, err, "400 Bad Request: invalid_issuer: Invalid subject_issuer parameter")
}

func Test_LoginSocialTokenExchange(t *testing.T) {
// t.Parallel()
cfg := GetConfig(t)
client := NewClientWithDebug(t)
token := GetAdminToken(t, client)

_, err := client.LoginSocialTokenExchange(
context.Background(),
cfg.GoCloak.ClientID,
cfg.GoCloak.Token,
cfg.GoCloak.ClientSecret,
cfg.GoCloak.Realm,
cfg.GoCloak.Issuer,
)

require.NoError(t, err, "LoginSocialTokenExchange failed")

t.Run("Delete google provider", func(t *testing.T) {
err := client.DeleteIdentityProvider(
context.Background(),
token.AccessToken,
cfg.GoCloak.Realm,
"google",
)
require.NoError(t, err)
})
}

func Test_LoginAdmin(t *testing.T) {
t.Parallel()
cfg := GetConfig(t)
Expand Down Expand Up @@ -2151,11 +2216,13 @@ func Test_CreateListGetUpdateDeleteClient(t *testing.T) {

func Test_CreateListGetUpdateDeleteClientRepresentation(t *testing.T) {
t.Parallel()

cfg := GetConfig(t)
client := NewClientWithDebug(t)
token := GetClientToken(t, client)
testClient := gocloak.Client{
ClientID: GetRandomNameP("gocloak-client-secret-client-id-"),
ClientID: GetRandomNameP("gocloak-client-secret-client-id-"),
DefaultClientScopes: &[]string{},
}

ctx := context.Background()
Expand Down
5 changes: 3 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ version: '3'
services:
keycloak:
build: .
command: -Dauto-build -Dfeatures=preview
command: -Dauto-build -Dfeatures=preview -Dkeycloak.profile.feature.upload_scripts=enabled
environment:
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: secret
KEYCLOAK_ADMIN: admin
JAVA_OPTS_APPEND: "-Dkeycloak.profile=preview -Dkeycloak.profile.feature.admin_fine_grained_authz=enabled -Dkeycloak.profile.feature.token_exchange=enabled -Dkeycloak.profile.feature.upload_scripts=enabled"
KEYCLOAK_ADMIN_PASSWORD: secret
KC_HEALTH_ENABLED: "true"
ports:
Expand All @@ -19,5 +20,5 @@ services:
retries: 5
volumes:
- ./testdata/gocloak-realm.json:/opt/keycloak/data/import/gocloak-realm.json
entrypoint: ["/opt/keycloak/bin/kc.sh", "start-dev --features=preview --import-realm"]
entrypoint: ["/opt/keycloak/bin/kc.sh", "start-dev --features=preview --features=scripts --features=client-policies --features=admin-fine-grained-authz --features=token-exchange --import-realm"]

4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ module github.com/Nerzal/gocloak/v13
go 1.18

require (
github.com/go-resty/resty/v2 v2.7.0
github.com/go-resty/resty/v2 v2.10.0
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/opentracing/opentracing-go v1.2.0
github.com/pkg/errors v0.9.1
github.com/segmentio/ksuid v1.0.4
github.com/stretchr/testify v1.8.2
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.14.0
)

Expand Down
52 changes: 40 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY=
github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I=
github.com/go-resty/resty/v2 v2.10.0 h1:Qla4W/+TMmv0fOeeRqzEpXPLfTUnR5HZ1+lGs+CkiCo=
github.com/go-resty/resty/v2 v2.10.0/go.mod h1:iiP/OpA0CkcL3IGt1O0+/SIItFUbkkyw5BGXiVdTu+A=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
Expand All @@ -14,25 +14,53 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/segmentio/ksuid v1.0.4 h1:sBo2BdShXjmcugAMwjugoGUdUV0pcxY5mW4xKRn3v4c=
github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 changes: 2 additions & 0 deletions models.go
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,8 @@ type TokenOptions struct {
ClientAssertionType *string `json:"client_assertion_type,omitempty"`
ClientAssertion *string `json:"client_assertion,omitempty"`
SubjectToken *string `json:"subject_token,omitempty"`
SubjectTokenType *string `json:"subject_token_type,omitempty"`
SubjectIssuer *string `json:"subject_issuer,omitempty"`
RequestedSubject *string `json:"requested_subject,omitempty"`
Audience *string `json:"audience,omitempty"`
RequestedTokenType *string `json:"requested_token_type,omitempty"`
Expand Down
6 changes: 3 additions & 3 deletions run-tests.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/sh

docker-compose down
docker-compose up -d
docker compose down
docker compose up -d

keycloakServer=http://localhost:8080
url="${keycloakServer}/health"
Expand All @@ -23,4 +23,4 @@ fi

go test -failfast -race -cover -coverprofile=coverage.out -covermode=atomic -p 10 -cpu 1,2 -bench . -benchmem ${ARGS[@]}

docker-compose down
docker compose down
4 changes: 3 additions & 1 deletion testdata/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"password": "test",
"realm": "gocloak",
"client_id": "gocloak",
"client_secret": "gocloak-secret"
"client_secret": "gocloak-secret",
"token": "ya29.A0ARrdaM-M-0Hzf_rLH7OaZRiLM7ab14qihA6Gf7BytLGt_R0uacRurnFmYolDSAqeZRECc044aM0MgJQsdMjoHd2mStbccZe_o8N--Wq3wQSIVRDMJC0tGZHC9P1Wb9VkLMF2b8cDcrmj7gpfxjwqjWXZFD_M2w",
"issuer": "google"
}
}