Create TestRealmKeycloakTest as common base class for tests that need

testrealm.json.  Rename admin packaget to endpoint.  Rename legacy package
to match old testsuite.
test suite.
This commit is contained in:
Stan Silvert 2016-04-14 15:16:58 -04:00
parent ca72a3bd70
commit e25a0d3cf1
36 changed files with 156 additions and 789 deletions

View file

@ -21,7 +21,7 @@ import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.DeleteMeOAuthClient;
import java.lang.annotation.Annotation;
@ -31,11 +31,11 @@ import java.lang.annotation.Annotation;
public class OAuthClientProvider implements ResourceProvider {
@Inject
Instance<OAuthClient> oauthClient;
Instance<DeleteMeOAuthClient> oauthClient;
@Override
public boolean canProvide(Class<?> type) {
return OAuthClient.class.isAssignableFrom(type);
return DeleteMeOAuthClient.class.isAssignableFrom(type);
}
@Override

View file

@ -40,11 +40,11 @@ import java.util.List;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class OAuthClient {
public class DeleteMeOAuthClient {
private String baseUrl;
public OAuthClient(String baseUrl) {
public DeleteMeOAuthClient(String baseUrl) {
this.baseUrl = baseUrl;
}

View file

@ -60,19 +60,23 @@ import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.testsuite.arquillian.SuiteContext;
import org.keycloak.testsuite.auth.page.WelcomePage;
import org.keycloak.testsuite.util.OAuthClient;
import org.keycloak.testsuite.util.DeleteMeOAuthClient;
import org.keycloak.util.JsonSerialization;
import org.openqa.selenium.WebDriver;
import org.keycloak.testsuite.auth.page.AuthServer;
import org.keycloak.testsuite.auth.page.AuthServerContextRoot;
import org.keycloak.testsuite.auth.page.AuthRealm;
import static org.keycloak.testsuite.auth.page.AuthRealm.ADMIN;
import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER;
import org.keycloak.testsuite.auth.page.account.Account;
import org.keycloak.testsuite.auth.page.login.OIDCLogin;
import org.keycloak.testsuite.auth.page.login.UpdatePassword;
import org.keycloak.testsuite.util.WaitUtils;
import static org.keycloak.testsuite.admin.Users.setPasswordFor;
import org.keycloak.testsuite.util.TestEventsLogger;
/**
@ -93,7 +97,7 @@ public abstract class AbstractKeycloakTest {
protected Keycloak adminClient;
protected OAuthClient oauthClient;
protected DeleteMeOAuthClient oauthClient;
protected List<RealmRepresentation> testRealmReps;
@ -128,7 +132,7 @@ public abstract class AbstractKeycloakTest {
public void beforeAbstractKeycloakTest() {
adminClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID);
oauthClient = new OAuthClient(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth");
oauthClient = new DeleteMeOAuthClient(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth");
adminUser = createAdminUserRepresentation();
@ -155,7 +159,7 @@ public abstract class AbstractKeycloakTest {
}
// removeTestRealms(); // keeping test realms after test to be able to inspect failures, instead deleting existing realms before import
// keycloak.close(); // keeping admin connection open
// adminClient.close(); // keeping admin connection open
}
private void updateMasterAdminPassword() {

View file

@ -0,0 +1,66 @@
/*
* Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.testsuite;
import org.keycloak.testsuite.util.OAuthClient;
import java.util.List;
import org.junit.Before;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson;
/**
* This class provides loading of the testRealm called "test". It also
* provides an OAuthClient for the testRealm.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public abstract class TestRealmKeycloakTest extends AbstractKeycloakTest {
protected OAuthClient oauth;
protected ClientRepresentation findTestApp(RealmRepresentation testRealm) {
for (ClientRepresentation client : testRealm.getClients()) {
if (client.getClientId().equals("test-app")) return client;
}
return null;
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation testRealm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
oauth = new OAuthClient(driver, testRealm.getPublicKey());
testRealms.add(testRealm);
configureTestRealm(testRealm);
}
/**
* This allows a subclass to change the configuration of the testRealm before
* it is imported. This method will be called prior to any @Before methods
* in the subclass.
*
* @param testRealm The realm read from /testrealm.json.
*/
public abstract void configureTestRealm(RealmRepresentation testRealm);
}

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.legacy.admin;
package org.keycloak.testsuite.admin;
import java.io.IOException;
import java.io.InputStream;
@ -31,7 +31,7 @@ import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.legacy.LegacyAdapter;
import org.keycloak.testsuite.TestRealmKeycloakTest;
import org.keycloak.util.JsonSerialization;
import static org.junit.Assert.assertArrayEquals;
@ -42,11 +42,16 @@ import static org.junit.Assert.assertArrayEquals;
*
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public abstract class LegacyAbstractClientTest extends LegacyAdapter {
public abstract class AbstractAdminTest extends TestRealmKeycloakTest {
protected static final String REALM_NAME = "admin-client-test";
protected RealmResource realm;
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
findTestApp(testRealm).setDirectAccessGrantsEnabled(true);
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
super.addTestRealms(testRealms);
@ -71,7 +76,7 @@ public abstract class LegacyAbstractClientTest extends LegacyAdapter {
// not sure if it really matters
@After
public void after() {
for (RealmRepresentation r : keycloak.realms().findAll()) {
for (RealmRepresentation r : adminClient.realms().findAll()) {
if (r.getRealm().equals(REALM_NAME)) {
removeRealm(r);
}

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.legacy.admin;
package org.keycloak.testsuite.admin;
import org.jboss.logging.Logger;
import org.keycloak.admin.client.resource.ClientResource;

View file

@ -18,17 +18,12 @@
package org.keycloak.testsuite.admin;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ProtocolMappersResource;
import org.keycloak.models.Constants;
import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;
import org.keycloak.representations.idm.*;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.openqa.selenium.WebDriver;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
@ -36,6 +31,7 @@ import javax.ws.rs.core.Response;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.keycloak.testsuite.util.OAuthClient;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@ -47,16 +43,7 @@ import static org.junit.Assert.fail;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class ClientTest extends AbstractClientTest {
@Rule
public WebRule webRule = new WebRule(this);
@WebResource
protected WebDriver driver;
@WebResource
protected OAuthClient oauth;
public class ClientTest extends AbstractAdminTest {
@Test
public void getClients() {
@ -122,7 +109,7 @@ public class ClientTest extends AbstractClientTest {
OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password");
assertEquals(200, response2.getStatusCode());
ClientResource app = ApiUtil.findClientByClientId(keycloak.realm("test"), "test-app");
ClientResource app = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
assertEquals(2, (long) app.getApplicationSessionCount().get("count"));

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Before;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.authentication;
package org.keycloak.testsuite.endpoint.authentication;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import java.util.List;
import javax.ws.rs.core.Response;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import java.util.ArrayList;
import java.util.HashMap;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import org.junit.After;
import org.junit.Before;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import java.util.List;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import org.junit.Before;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import org.junit.After;
import org.junit.Before;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.client;
package org.keycloak.testsuite.endpoint.client;
import java.util.List;
import org.jboss.arquillian.graphene.page.Page;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.event;
package org.keycloak.testsuite.endpoint.event;
import java.util.Collections;
import org.junit.Before;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.event;
package org.keycloak.testsuite.endpoint.event;
import java.util.Arrays;
import java.util.Collections;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.event;
package org.keycloak.testsuite.endpoint.event;
import java.util.Arrays;
import java.util.Collections;

View file

@ -15,7 +15,7 @@
* the License.
*/
package org.keycloak.testsuite.admin.event;
package org.keycloak.testsuite.endpoint.event;
import java.util.Arrays;
import java.util.List;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.group;
package org.keycloak.testsuite.endpoint.group;
import org.junit.Before;
import org.keycloak.OAuth2Constants;
@ -45,6 +45,7 @@ public abstract class AbstractGroupTest extends AbstractKeycloakTest {
@Before
public void initAssertEvents() throws Exception {
events = new AssertEvents(this);
events.clear();
}
AccessToken login(String login, String clientId, String clientSecret, String userId) throws Exception {

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.group;
package org.keycloak.testsuite.endpoint.group;
import org.junit.Assert;
import org.junit.Test;

View file

@ -15,7 +15,7 @@
* limitations under the License.
*/
package org.keycloak.testsuite.admin.group;
package org.keycloak.testsuite.endpoint.group;
import org.junit.Assert;
import org.junit.Test;

View file

@ -14,7 +14,7 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.testsuite.admin.partialimport;
package org.keycloak.testsuite.endpoint.partialimport;
import java.util.ArrayList;
import java.util.Arrays;

View file

@ -41,7 +41,7 @@ import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
/**
* Test importing JSON files exported from previous keycloak versions
* Test importing JSON files exported from previous adminClient versions
*
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/

View file

@ -1,83 +0,0 @@
/*
* Copyright 2016 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.keycloak.testsuite.legacy;
import java.util.List;
import org.junit.Before;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.AbstractKeycloakTest;
import static org.keycloak.testsuite.legacy.admin.LegacyAbstractClientTest.loadJson;
/**
* Allows migration of legacy tests with a minimum of changes to the tests themselves.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class LegacyAdapter extends AbstractKeycloakTest {
protected Keycloak keycloak;
protected LegacyOAuthClient oauth;
private String testRealmPublicKey;
private ClientRepresentation findTestApp(List<ClientRepresentation> clients) {
for (ClientRepresentation client : clients) {
if (client.getClientId().equals("test-app")) return client;
}
return null;
}
public static RealmRepresentation findRealm(String realmName, List<RealmRepresentation> testRealms) {
for (RealmRepresentation realm : testRealms) {
if (realm.getRealm().equals(realmName)) return realm;
}
return null;
}
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
RealmRepresentation rep = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class);
this.testRealmPublicKey = rep.getPublicKey();
/* Implement this old behavior by changing the representation before the realm gets loaded
keycloakRule.configure(new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
}
});*/
findTestApp(rep.getClients()).setDirectAccessGrantsEnabled(true);
testRealms.add(rep);
}
@Before
public void setUpKeycloakAlias() {
keycloak = adminClient;
}
@Before
public void setUpOAuthClient() {
oauth = new LegacyOAuthClient(driver, testRealmPublicKey);
}
}

View file

@ -1,31 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.legacy;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class LegacyConstants {
public static String SERVER_ROOT = AuthServerTestEnricher.getAuthServerContextRoot();
public static String AUTH_SERVER_ROOT = SERVER_ROOT + "/auth";
public static String APP_ROOT = AUTH_SERVER_ROOT + "/realms/master/app";
}

View file

@ -1,285 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.legacy.admin;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.admin.client.resource.ClientResource;
import org.keycloak.admin.client.resource.ProtocolMappersResource;
import org.keycloak.models.Constants;
import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory;
import org.keycloak.representations.idm.*;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.keycloak.testsuite.legacy.LegacyOAuthClient;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class ClientTest extends LegacyAbstractClientTest {
@Test
public void getClients() {
assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", Constants.ADMIN_CLI_CLIENT_ID);
}
private ClientRepresentation createClient() {
ClientRepresentation rep = new ClientRepresentation();
rep.setClientId("my-app");
rep.setDescription("my-app description");
rep.setEnabled(true);
Response response = realm.clients().create(rep);
response.close();
String id = ApiUtil.getCreatedId(response);
rep.setId(id);
return rep;
}
@Test
public void createClientVerify() {
String id = createClient().getId();
assertNotNull(realm.clients().get(id));
assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", "my-app", Constants.ADMIN_CLI_CLIENT_ID);
}
@Test
public void removeClient() {
String id = createClient().getId();
realm.clients().get(id).remove();
}
@Test
public void getClientRepresentation() {
String id = createClient().getId();
ClientRepresentation rep = realm.clients().get(id).toRepresentation();
assertEquals(id, rep.getId());
assertEquals("my-app", rep.getClientId());
assertTrue(rep.isEnabled());
}
/**
* See <a href="https://issues.jboss.org/browse/KEYCLOAK-1918">KEYCLOAK-1918</a>
*/
@Test
public void getClientDescription() {
String id = createClient().getId();
ClientRepresentation rep = realm.clients().get(id).toRepresentation();
assertEquals(id, rep.getId());
assertEquals("my-app description", rep.getDescription());
}
@Test
public void getClientSessions() throws Exception {
LegacyOAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
assertEquals(200, response.getStatusCode());
LegacyOAuthClient.AuthorizationCodeResponse codeResponse = oauth.doLogin("test-user@localhost", "password");
LegacyOAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password");
assertEquals(200, response2.getStatusCode());
ClientResource app = ApiUtil.findClientByClientId(keycloak.realm("test"), "test-app");
assertEquals(2, (long) app.getApplicationSessionCount().get("count"));
List<UserSessionRepresentation> userSessions = app.getUserSessions(0, 100);
assertEquals(2, userSessions.size());
assertEquals(1, userSessions.get(0).getClients().size());
}
@Test
// KEYCLOAK-1110
public void deleteDefaultRole() {
ClientRepresentation rep = new ClientRepresentation();
rep.setClientId("my-app");
rep.setEnabled(true);
Response response = realm.clients().create(rep);
response.close();
String id = ApiUtil.getCreatedId(response);
RoleRepresentation role = new RoleRepresentation("test", "test", false);
realm.clients().get(id).roles().create(role);
rep = realm.clients().get(id).toRepresentation();
rep.setDefaultRoles(new String[] { "test" });
realm.clients().get(id).update(rep);
assertArrayEquals(new String[] { "test" }, realm.clients().get(id).toRepresentation().getDefaultRoles());
realm.clients().get(id).roles().deleteRole("test");
assertNull(realm.clients().get(id).toRepresentation().getDefaultRoles());
}
@Test
public void testProtocolMappers() {
createClient();
ProtocolMappersResource mappersResource = ApiUtil.findClientByClientId(realm, "my-app").getProtocolMappers();
protocolMappersTest(mappersResource);
}
@Test
public void updateClient() {
ClientRepresentation client = createClient();
ClientRepresentation newClient = new ClientRepresentation();
newClient.setId(client.getId());
newClient.setClientId(client.getClientId());
newClient.setBaseUrl("http://baseurl");
realm.clients().get(client.getId()).update(newClient);
ClientRepresentation storedClient = realm.clients().get(client.getId()).toRepresentation();
assertClient(client, storedClient);
newClient.setSecret("new-secret");
realm.clients().get(client.getId()).update(newClient);
storedClient = realm.clients().get(client.getId()).toRepresentation();
assertClient(client, storedClient);
}
public static void protocolMappersTest(ProtocolMappersResource mappersResource) {
// assert default mappers found
List<ProtocolMapperRepresentation> protocolMappers = mappersResource.getMappers();
String emailMapperId = null;
String usernameMapperId = null;
String fooMapperId = null;
for (ProtocolMapperRepresentation mapper : protocolMappers) {
if (mapper.getName().equals(OIDCLoginProtocolFactory.EMAIL)) {
emailMapperId = mapper.getId();
} else if (mapper.getName().equals(OIDCLoginProtocolFactory.USERNAME)) {
usernameMapperId = mapper.getId();
} else if (mapper.getName().equals("foo")) {
fooMapperId = mapper.getId();
}
}
assertNotNull(emailMapperId);
assertNotNull(usernameMapperId);
assertNull(fooMapperId);
// Create foo mapper
ProtocolMapperRepresentation fooMapper = new ProtocolMapperRepresentation();
fooMapper.setName("foo");
fooMapper.setProtocol("fooProtocol");
fooMapper.setProtocolMapper("fooMapper");
fooMapper.setConsentRequired(true);
Response response = mappersResource.createMapper(fooMapper);
String location = response.getLocation().toString();
fooMapperId = location.substring(location.lastIndexOf("/") + 1);
response.close();
fooMapper = mappersResource.getMapperById(fooMapperId);
assertEquals(fooMapper.getName(), "foo");
// Update foo mapper
fooMapper.setProtocolMapper("foo-mapper-updated");
mappersResource.update(fooMapperId, fooMapper);
fooMapper = mappersResource.getMapperById(fooMapperId);
assertEquals(fooMapper.getProtocolMapper(), "foo-mapper-updated");
// Remove foo mapper
mappersResource.delete(fooMapperId);
try {
mappersResource.getMapperById(fooMapperId);
fail("Not expected to find deleted mapper");
} catch (NotFoundException nfe) {
}
}
public static void assertClient(ClientRepresentation client, ClientRepresentation storedClient) {
if (client.getClientId() != null) Assert.assertEquals(client.getClientId(), storedClient.getClientId());
if (client.getName() != null) Assert.assertEquals(client.getName(), storedClient.getName());
if (client.isEnabled() != null) Assert.assertEquals(client.isEnabled(), storedClient.isEnabled());
if (client.isBearerOnly() != null) Assert.assertEquals(client.isBearerOnly(), storedClient.isBearerOnly());
if (client.isPublicClient() != null) Assert.assertEquals(client.isPublicClient(), storedClient.isPublicClient());
if (client.isFullScopeAllowed() != null) Assert.assertEquals(client.isFullScopeAllowed(), storedClient.isFullScopeAllowed());
if (client.getRootUrl() != null) Assert.assertEquals(client.getRootUrl(), storedClient.getRootUrl());
if (client.getAdminUrl() != null) Assert.assertEquals(client.getAdminUrl(), storedClient.getAdminUrl());
if (client.getBaseUrl() != null) Assert.assertEquals(client.getBaseUrl(), storedClient.getBaseUrl());
if (client.isSurrogateAuthRequired() != null) Assert.assertEquals(client.isSurrogateAuthRequired(), storedClient.isSurrogateAuthRequired());
if (client.getClientAuthenticatorType() != null) Assert.assertEquals(client.getClientAuthenticatorType(), storedClient.getClientAuthenticatorType());
if (client.getNotBefore() != null) {
Assert.assertEquals(client.getNotBefore(), storedClient.getNotBefore());
}
if (client.getDefaultRoles() != null) {
Set<String> set = new HashSet<String>();
for (String val : client.getDefaultRoles()) {
set.add(val);
}
Set<String> storedSet = new HashSet<String>();
for (String val : storedClient.getDefaultRoles()) {
storedSet.add(val);
}
Assert.assertEquals(set, storedSet);
}
List<String> redirectUris = client.getRedirectUris();
if (redirectUris != null) {
Set<String> set = new HashSet<String>();
for (String val : client.getRedirectUris()) {
set.add(val);
}
Set<String> storedSet = new HashSet<String>();
for (String val : storedClient.getRedirectUris()) {
storedSet.add(val);
}
Assert.assertEquals(set, storedSet);
}
List<String> webOrigins = client.getWebOrigins();
if (webOrigins != null) {
Set<String> set = new HashSet<String>();
for (String val : client.getWebOrigins()) {
set.add(val);
}
Set<String> storedSet = new HashSet<String>();
for (String val : storedClient.getWebOrigins()) {
storedSet.add(val);
}
Assert.assertEquals(set, storedSet);
}
}
}

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.legacy.oauth;
package org.keycloak.testsuite.oauth;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -32,12 +32,12 @@ import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.oidc.TokenMetadataRepresentation;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.legacy.LegacyAdapter;
import org.keycloak.testsuite.legacy.LegacyOAuthClient.AccessTokenResponse;
//import org.keycloak.testsuite.pages.LoginPage;
//import org.keycloak.testsuite.rule.KeycloakRule;
//import org.keycloak.testsuite.rule.WebResource;
//import org.keycloak.testsuite.rule.WebRule;
import org.keycloak.testsuite.TestRealmKeycloakTest;
import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse;
//import org.adminClient.testsuite.pages.LoginPage;
//import org.adminClient.testsuite.rule.KeycloakRule;
//import org.adminClient.testsuite.rule.WebResource;
//import org.adminClient.testsuite.rule.WebRule;
import org.keycloak.util.JsonSerialization;
import static org.junit.Assert.*;
@ -46,15 +46,17 @@ import static org.junit.Assert.*;
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class TokenIntrospectionTest extends LegacyAdapter {
public class TokenIntrospectionTest extends TestRealmKeycloakTest {
/* @ClassRule >>> now implemented in addTestRealms()
private AssertEvents events;
/* @ClassRule >>> now implemented in configureTestRealm()
public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
@Override
vvv "test" realm
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
vvv Done in LegacyAdapter vvv
vvv Done in TestRealmKeycloakTest vvv
appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
ClientModel confApp = KeycloakModelUtils.createClient(appRealm, "confidential-cli");
@ -70,20 +72,18 @@ public class TokenIntrospectionTest extends LegacyAdapter {
user.grantRole(role);
}
keycloak = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
adminClient = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
}
}); */
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
super.addTestRealms(testRealms);
RealmRepresentation appRealm = findRealm("test", testRealms);
ClientRepresentation confApp = KeycloakModelUtils.createClient(appRealm, "confidential-cli");
public void configureTestRealm(RealmRepresentation testRealm) {
ClientRepresentation confApp = KeycloakModelUtils.createClient(testRealm, "confidential-cli");
confApp.setSecret("secret1");
confApp.setServiceAccountsEnabled(Boolean.TRUE);
ClientRepresentation pubApp = KeycloakModelUtils.createClient(appRealm, "public-cli");
ClientRepresentation pubApp = KeycloakModelUtils.createClient(testRealm, "public-cli");
pubApp.setPublicClient(Boolean.TRUE);
UserRepresentation user = new UserRepresentation();
@ -98,11 +98,9 @@ public class TokenIntrospectionTest extends LegacyAdapter {
List<String> realmRoles = new ArrayList<>();
realmRoles.add("user");
user.setRealmRoles(realmRoles);
appRealm.getUsers().add(user);
testRealm.getUsers().add(user);
}
private AssertEvents events;
@Before
public void setUpAssertEvents() throws Exception {
events = new AssertEvents(this);
@ -271,7 +269,7 @@ public class TokenIntrospectionTest extends LegacyAdapter {
UserRepresentation userRep = new UserRepresentation();
try {
userRep.setEnabled(false);
keycloak.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
@ -284,7 +282,7 @@ public class TokenIntrospectionTest extends LegacyAdapter {
events.clear();
} finally {
userRep.setEnabled(true);
keycloak.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
adminClient.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
}
}
@ -295,7 +293,7 @@ public class TokenIntrospectionTest extends LegacyAdapter {
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
try {
Time.setOffset(keycloak.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan() + 1);
Time.setOffset(adminClient.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan() + 1);
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);

View file

@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.legacy;
package org.keycloak.testsuite.util;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
@ -37,6 +37,7 @@ import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.protocol.oidc.OIDCLoginProtocolService;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.RefreshToken;
import org.keycloak.testsuite.arquillian.AuthServerTestEnricher;
import org.keycloak.util.BasicAuthHelper;
import org.keycloak.util.JsonSerialization;
@ -58,17 +59,20 @@ import java.util.Map;
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
* @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc.
*/
public class LegacyOAuthClient {
public class OAuthClient {
public static final String SERVER_ROOT = AuthServerTestEnricher.getAuthServerContextRoot();
public static final String AUTH_SERVER_ROOT = SERVER_ROOT + "/auth";
public static final String APP_ROOT = AUTH_SERVER_ROOT + "/realms/master/app";
private WebDriver driver;
private String baseUrl = LegacyConstants.AUTH_SERVER_ROOT;
private String baseUrl = AUTH_SERVER_ROOT;
private String realm = "test";
private String clientId = "test-app";
private String redirectUri = LegacyConstants.APP_ROOT + "/auth";
private String redirectUri = APP_ROOT + "/auth";
private String state = "mystate";
@ -82,7 +86,7 @@ public class LegacyOAuthClient {
private String clientSessionHost;
public LegacyOAuthClient(WebDriver driver, String publicKey) {
public OAuthClient(WebDriver driver, String publicKey) {
this.driver = driver;
try {
@ -429,7 +433,7 @@ public class LegacyOAuthClient {
}
public String getLoginFormUrl() {
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(LegacyConstants.SERVER_ROOT + "/auth"));
UriBuilder b = OIDCLoginProtocolService.authUrl(UriBuilder.fromUri(SERVER_ROOT + "/auth"));
b.queryParam(OAuth2Constants.RESPONSE_TYPE, OAuth2Constants.CODE);
if (clientId != null) {
b.queryParam(OAuth2Constants.CLIENT_ID, clientId);
@ -489,46 +493,46 @@ public class LegacyOAuthClient {
return b.build(realm).toString();
}
public LegacyOAuthClient realm(String realm) {
public OAuthClient realm(String realm) {
this.realm = realm;
return this;
}
public LegacyOAuthClient realmPublicKey(PublicKey key) {
public OAuthClient realmPublicKey(PublicKey key) {
this.realmPublicKey = key;
return this;
}
public LegacyOAuthClient clientId(String clientId) {
public OAuthClient clientId(String clientId) {
this.clientId = clientId;
return this;
}
public LegacyOAuthClient redirectUri(String redirectUri) {
public OAuthClient redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
public LegacyOAuthClient state(String state) {
public OAuthClient state(String state) {
this.state = state;
return this;
}
public LegacyOAuthClient scope(String scope) {
public OAuthClient scope(String scope) {
this.scope = scope;
return this;
}
public LegacyOAuthClient uiLocales(String uiLocales){
public OAuthClient uiLocales(String uiLocales){
this.uiLocales = uiLocales;
return this;
}
public LegacyOAuthClient clientSessionState(String client_session_state) {
public OAuthClient clientSessionState(String client_session_state) {
this.clientSessionState = client_session_state;
return this;
}
public LegacyOAuthClient clientSessionHost(String client_session_host) {
public OAuthClient clientSessionHost(String client_session_host) {
this.clientSessionHost = client_session_host;
return this;
}
@ -544,7 +548,7 @@ public class LegacyOAuthClient {
private String state;
private String error;
public AuthorizationCodeResponse(LegacyOAuthClient client) {
public AuthorizationCodeResponse(OAuthClient client) {
isRedirected = client.getCurrentRequest().equals(client.getRedirectUri());
code = client.getCurrentQuery().get(OAuth2Constants.CODE);
state = client.getCurrentQuery().get(OAuth2Constants.STATE);

View file

@ -1,299 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.oauth;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.OAuth2Constants;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.common.util.Time;
import org.keycloak.events.Event;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.oidc.TokenMetadataRepresentation;
import org.keycloak.services.managers.ClientManager;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.AssertEvents;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.OAuthClient.AccessTokenResponse;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.rule.KeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.keycloak.util.JsonSerialization;
import org.openqa.selenium.WebDriver;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class TokenIntrospectionTest {
protected static Keycloak keycloak;
@ClassRule
public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
@Override
public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
ClientModel confApp = KeycloakModelUtils.createClient(appRealm, "confidential-cli");
confApp.setSecret("secret1");
new ClientManager(manager).enableServiceAccount(confApp);
ClientModel pubApp = KeycloakModelUtils.createClient(appRealm, "public-cli");
pubApp.setPublicClient(true);
{
UserModel user = manager.getSession().users().addUser(appRealm, KeycloakModelUtils.generateId(), "no-permissions", false, false);
user.updateCredential(UserCredentialModel.password("password"));
user.setEnabled(true);
RoleModel role = appRealm.getRole("user");
user.grantRole(role);
}
keycloak = Keycloak.getInstance("http://localhost:8081/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
}
});
@Rule
public WebRule webRule = new WebRule(this);
@WebResource
protected WebDriver driver;
@WebResource
protected OAuthClient oauth;
@WebResource
protected LoginPage loginPage;
@Rule
public AssertEvents events = new AssertEvents(keycloakRule);
@Test
public void testConfidentialClientCredentialsBasicAuthentication() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(tokenResponse);
assertTrue(jsonNode.get("active").asBoolean());
assertEquals("test-user@localhost", jsonNode.get("username").asText());
assertEquals("test-app", jsonNode.get("client_id").asText());
assertTrue(jsonNode.has("exp"));
assertTrue(jsonNode.has("iat"));
assertTrue(jsonNode.has("nbf"));
assertTrue(jsonNode.has("sub"));
assertTrue(jsonNode.has("aud"));
assertTrue(jsonNode.has("iss"));
assertTrue(jsonNode.has("jti"));
TokenMetadataRepresentation rep = objectMapper.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertTrue(rep.isActive());
assertEquals("test-user@localhost", rep.getUserName());
assertEquals("test-app", rep.getClientId());
assertEquals(jsonNode.get("exp").asInt(), rep.getExpiration());
assertEquals(jsonNode.get("iat").asInt(), rep.getIssuedAt());
assertEquals(jsonNode.get("nbf").asInt(), rep.getNotBefore());
assertEquals(jsonNode.get("sub").asText(), rep.getSubject());
assertEquals(jsonNode.get("aud").asText(), rep.getAudience()[0]);
assertEquals(jsonNode.get("iss").asText(), rep.getIssuer());
assertEquals(jsonNode.get("jti").asText(), rep.getId());
events.clear();
}
@Test
public void testInvalidClientCredentials() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "bad_credential", accessTokenResponse.getAccessToken());
assertEquals("{\"error_description\":\"Authentication failed.\",\"error\":\"invalid_request\"}", tokenResponse);
events.clear();
}
@Test
public void testIntrospectRefreshToken() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
Event loginEvent = events.expectLogin().assertEvent();
String sessionId = loginEvent.getSessionId();
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(tokenResponse);
assertTrue(jsonNode.get("active").asBoolean());
assertEquals(sessionId, jsonNode.get("session_state").asText());
assertEquals("test-app", jsonNode.get("client_id").asText());
assertTrue(jsonNode.has("exp"));
assertTrue(jsonNode.has("iat"));
assertTrue(jsonNode.has("nbf"));
assertTrue(jsonNode.has("sub"));
assertTrue(jsonNode.has("aud"));
assertTrue(jsonNode.has("iss"));
assertTrue(jsonNode.has("jti"));
TokenMetadataRepresentation rep = objectMapper.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertTrue(rep.isActive());
assertEquals("test-app", rep.getClientId());
assertEquals(jsonNode.get("session_state").asText(), rep.getSessionState());
assertEquals(jsonNode.get("exp").asInt(), rep.getExpiration());
assertEquals(jsonNode.get("iat").asInt(), rep.getIssuedAt());
assertEquals(jsonNode.get("nbf").asInt(), rep.getNotBefore());
assertEquals(jsonNode.get("iss").asText(), rep.getIssuer());
assertEquals(jsonNode.get("jti").asText(), rep.getId());
events.clear();
}
@Test
public void testPublicClientCredentialsNotAllowed() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("public-cli", "it_doesnt_matter", accessTokenResponse.getAccessToken());
assertEquals("{\"error_description\":\"Client not allowed.\",\"error\":\"invalid_request\"}", tokenResponse);
events.clear();
}
@Test
public void testInactiveAccessToken() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String inactiveAccessToken = "eyJhbGciOiJSUzI1NiJ9.eyJub25jZSI6IjczMGZjNjQ1LTBlMDQtNDE3Yi04MDY0LTkyYWIyY2RjM2QwZSIsImp0aSI6ImU5ZGU1NjU2LWUzMjctNDkxNC1hNjBmLTI1MzJlYjBiNDk4OCIsImV4cCI6MTQ1MjI4MTAwMCwibmJmIjowLCJpYXQiOjE0NTIyODA3MDAsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9hdXRoL3JlYWxtcy9leGFtcGxlIiwiYXVkIjoianMtY29uc29sZSIsInN1YiI6IjFkNzQ0MDY5LWYyOTgtNGU3Yy1hNzNiLTU1YzlhZjgzYTY4NyIsInR5cCI6IkJlYXJlciIsImF6cCI6ImpzLWNvbnNvbGUiLCJzZXNzaW9uX3N0YXRlIjoiNzc2YTA0OTktODNjNC00MDhkLWE5YjctYTZiYzQ5YmQ3MThjIiwiY2xpZW50X3Nlc3Npb24iOiJjN2Y5ODczOC05MDhlLTQxOWYtYTdkNC1kODYxYjRhYTI3NjkiLCJhbGxvd2VkLW9yaWdpbnMiOltdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsidXNlciJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJ2aWV3LXByb2ZpbGUiXX19LCJuYW1lIjoiU2FtcGxlIFVzZXIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ1c2VyIiwiZ2l2ZW5fbmFtZSI6IlNhbXBsZSIsImZhbWlseV9uYW1lIjoiVXNlciIsImVtYWlsIjoic2FtcGxlLXVzZXJAZXhhbXBsZSJ9.YyPV74j9CqOG2Jmq692ZZpqycjNpUgtYVRfQJccS_FU84tGVXoKKsXKYeY2UJ1Y_bPiYG1I1J6JSXC8XqgQijCG7Nh7oK0yN74JbRN58HG75fvg6K9BjR6hgJ8mHT8qPrCux2svFucIMIZ180eoBoRvRstkidOhl_mtjT_i31fU";
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", inactiveAccessToken);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(tokenResponse);
assertFalse(jsonNode.get("active").asBoolean());
TokenMetadataRepresentation rep = objectMapper.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertFalse(rep.isActive());
assertNull(rep.getUserName());
assertNull(rep.getClientId());
assertNull(rep.getSubject());
events.clear();
}
@Test
public void testIntrospectAccessToken() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
Event loginEvent = events.expectLogin().assertEvent();
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertTrue(rep.isActive());
assertEquals("test-user@localhost", rep.getUserName());
assertEquals("test-app", rep.getClientId());
assertEquals(loginEvent.getUserId(), rep.getSubject());
events.clear();
}
@Test
public void testIntrospectAccessTokenSessionInvalid() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
oauth.doLogout(accessTokenResponse.getRefreshToken(), "password");
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertFalse(rep.isActive());
assertNull(rep.getUserName());
assertNull(rep.getClientId());
assertNull(rep.getSubject());
events.clear();
}
@Test
public void testIntrospectAccessTokenUserDisabled() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
Event loginEvent = events.expectLogin().assertEvent();
UserRepresentation userRep = new UserRepresentation();
try {
userRep.setEnabled(false);
keycloak.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertFalse(rep.isActive());
assertNull(rep.getUserName());
assertNull(rep.getClientId());
assertNull(rep.getSubject());
events.clear();
} finally {
userRep.setEnabled(true);
keycloak.realm(oauth.getRealm()).users().get(loginEvent.getUserId()).update(userRep);
}
}
@Test
public void testIntrospectAccessTokenExpired() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
try {
Time.setOffset(keycloak.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan() + 1);
String tokenResponse = oauth.introspectAccessTokenWithClientCredential("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
TokenMetadataRepresentation rep = JsonSerialization.readValue(tokenResponse, TokenMetadataRepresentation.class);
assertFalse(rep.isActive());
assertNull(rep.getUserName());
assertNull(rep.getClientId());
assertNull(rep.getSubject());
events.clear();
} finally {
Time.setOffset(0);
}
}
}