Tests: Determine IDs from Keycloak

Instead of assuming that the ID of created objects is honored,
the tests are rewritten in the way which obtains the ID from
the created objects. This is to account for storages where
ID is not necessarily an UUID and cannot be thus prescribed.

Closes: #19814
This commit is contained in:
Hynek Mlnarik 2023-03-15 08:44:21 +01:00 committed by Hynek Mlnařík
parent b22801c8dd
commit 80ba42a0b4
22 changed files with 183 additions and 89 deletions

View file

@ -43,6 +43,7 @@ import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.ClientScopeBuilder;
import org.keycloak.testsuite.util.RealmBuilder;
import org.keycloak.testsuite.util.UserBuilder;
import java.util.Objects;
/**
* Test for the various "Advanced" scenarios of java admin-client
@ -78,11 +79,9 @@ public class AdminClientTest extends AbstractKeycloakTest {
RealmBuilder realm = RealmBuilder.create().name(realmName)
.testEventListener();
clientUUID = KeycloakModelUtils.generateId();
clientId = "service-account-cl";
clientSecret = "secret1";
ClientRepresentation enabledAppWithSkipRefreshToken = ClientBuilder.create()
.id(clientUUID)
.clientId(clientId)
.secret(clientSecret)
.serviceAccountsEnabled(true)
@ -92,7 +91,6 @@ public class AdminClientTest extends AbstractKeycloakTest {
userId = KeycloakModelUtils.generateId();
userName = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + enabledAppWithSkipRefreshToken.getClientId();
UserBuilder serviceAccountUser = UserBuilder.create()
.id(userId)
.username(userName)
.serviceAccountId(enabledAppWithSkipRefreshToken.getClientId())
.role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN);
@ -108,6 +106,15 @@ public class AdminClientTest extends AbstractKeycloakTest {
testRealms.add(realm.build());
}
@Override
public void importRealm(RealmRepresentation realm) {
super.importRealm(realm);
if (Objects.equals(realm.getRealm(), realmName)) {
clientUUID = adminClient.realm(realmName).clients().findByClientId(clientId).get(0).getId();
userId = adminClient.realm(realmName).users().searchByUsername(userName, true).get(0).getId();
}
}
@Test
public void clientCredentialsAuthSuccess() throws Exception {
try (Keycloak adminClient = AdminClientUtil.createAdminClientWithClientCredentials(realmName, clientId, clientSecret, null)) {
@ -173,8 +180,7 @@ public class AdminClientTest extends AbstractKeycloakTest {
// we need to create custom scope after import, otherwise the default scopes are missing.
final String scopeName = "myScope";
final String scopeId = KeycloakModelUtils.generateId();
createScope(testRealm, scopeName, scopeId);
String scopeId = createScope(testRealm, scopeName, KeycloakModelUtils.generateId());
testRealm.clients().get(clientUUID).addOptionalClientScope(scopeId);
// with scope
@ -198,11 +204,13 @@ public class AdminClientTest extends AbstractKeycloakTest {
client.update(clientRep);
}
private void createScope(RealmResource testRealm, String scopeName, String scopeId) {
private String createScope(RealmResource testRealm, String scopeName, String scopeId) {
final ClientScopeRepresentation testScope =
ClientScopeBuilder.create().name(scopeName).protocol("openid-connect").build();
testScope.setId(scopeId);
final Response scope = testRealm.clientScopes().create(testScope);
Assert.assertEquals(201, scope.getStatus());
try (Response response = testRealm.clientScopes().create(testScope)) {
Assert.assertEquals(201, response.getStatus());
return ApiUtil.getCreatedId(response);
}
}
}

View file

@ -88,6 +88,15 @@ public class AdminEventAuthDetailsTest extends AbstractAuthTest {
testRealms.add(realm.build());
}
@Override
public void importTestRealms() {
super.importTestRealms();
client1Uuid = adminClient.realm("test").clients().findByClientId("client1").get(0).getId();
admin1Id = adminClient.realm("test").users().search("admin1", true).get(0).getId();
admin2Id = adminClient.realm("test").users().search("admin2", true).get(0).getId();
appUserId = adminClient.realm("test").users().search("app-user", true).get(0).getId();
}
@Before
public void initConfig() {
RealmResource masterRealm = adminClient.realm(MASTER);

View file

@ -80,6 +80,7 @@ import static org.junit.Assert.assertTrue;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.models.AdminRoles;
import org.keycloak.models.GroupModel;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -278,18 +279,19 @@ public class GroupTest extends AbstractGroupTest {
@Test
@UncaughtServerErrorExpected
public void doNotAllowSameGroupNameAtTopLevelInDatabase() throws Exception {
final String id = KeycloakModelUtils.generateId();
testingClient.server().run(session -> {
final String id = testingClient.server().fetch(session -> {
RealmModel realm = session.realms().getRealmByName("test");
realm.createGroup(id, "test-group");
});
GroupModel g = realm.createGroup("test-group");
return g.getId();
}, String.class);
getCleanup().addGroupId(id);
// unique key should work even in top groups
expectedException.expect(RunOnServerException.class);
expectedException.expectMessage(ModelDuplicateException.class.getName());
testingClient.server().run(session -> {
RealmModel realm = session.realms().getRealmByName("test");
realm.createGroup("test-group");
GroupModel g = realm.createGroup("test-group");
realm.removeGroup(g);
});
}

View file

@ -52,6 +52,8 @@ import org.keycloak.testsuite.util.UserBuilder;
public abstract class AbstractResourceServerTest extends AbstractAuthzTest {
protected static final String REALM_NAME = "authz-test";
protected String martaId;
protected String koloId;
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
@ -81,6 +83,13 @@ public abstract class AbstractResourceServerTest extends AbstractAuthzTest {
.build());
}
@Override
public void importTestRealms() {
super.importTestRealms();
koloId = adminClient.realm(REALM_NAME).users().search("kolo", true).get(0).getId();
martaId = adminClient.realm(REALM_NAME).users().search("marta", true).get(0).getId();
}
protected AuthorizationResponse authorize(String resourceName, String[] scopeNames, String claimToken) {
return authorize(null, null, resourceName, scopeNames, null, null, claimToken);
}

View file

@ -586,6 +586,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
request.addPermission("Sensortest", "sensors:view");
getTestContext().getTestingClient().testing().clearEventQueue();
AccessToken at = toAccessToken(accessToken);
try {
authzClient.authorization(accessToken).authorize(request);
@ -595,11 +596,12 @@ public class EntitlementAPITest extends AbstractAuthzTest {
assertTrue(HttpResponseException.class.cast(expected.getCause()).toString().contains("invalid_resource"));
}
events.expect(EventType.PERMISSION_TOKEN_ERROR).realm(getRealm().toRepresentation().getId()).client(RESOURCE_SERVER_TEST)
.session((String) null)
.error("invalid_request")
.detail("reason", "Resource with id [Sensortest] does not exist.")
.user(isUUID())
.user(at.getSubject())
.assertEvent();
}

View file

@ -319,14 +319,14 @@ public class UserManagedAccessTest extends AbstractResourceServerTest {
String realmId = getRealm().toRepresentation().getId();
String clientId = client.toRepresentation().getClientId();
events.expectLogin().realm(realmId).client(clientId)
.user(isUUID())
.user(koloId)
.clearDetails()
.assertEvent();
events.expectLogin().realm(realmId).client(clientId)
.user(isUUID())
.user(koloId)
.clearDetails()
.assertEvent();
events.expect(EventType.PERMISSION_TOKEN_ERROR).realm(realmId).client(clientId).user(isUUID())
events.expect(EventType.PERMISSION_TOKEN_ERROR).realm(realmId).client(clientId).user(koloId)
.session((String) null)
.error("access_denied")
.detail("reason", "request_submitted")
@ -375,14 +375,14 @@ public class UserManagedAccessTest extends AbstractResourceServerTest {
assertTrue(permissions.isEmpty());
events.expectLogin().realm(realmId).client(clientId)
.user(isUUID())
.user(koloId)
.clearDetails()
.assertEvent();
events.expectLogin().realm(realmId).client(clientId)
.user(isUUID())
.user(koloId)
.clearDetails()
.assertEvent();
events.expect(EventType.PERMISSION_TOKEN).realm(realmId).client(clientId).user(isUUID())
events.expect(EventType.PERMISSION_TOKEN).realm(realmId).client(clientId).user(koloId)
.session((String) null)
.clearDetails()
.assertEvent();

View file

@ -2704,11 +2704,12 @@ public class CIBATest extends AbstractClientPoliciesTest {
private void verifyBackchannelAuthenticationTokenRequest(OAuthClient.AccessTokenResponse tokenRes, String clientId, String username) {
assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
EventRepresentation event = events.expectAuthReqIdToToken(null, null).clearDetails().user(AssertEvents.isUUID()).client(clientId).assertEvent();
AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
assertThat(accessToken.getIssuedFor(), is(equalTo(clientId)));
EventRepresentation event = events.expectAuthReqIdToToken(null, null).clearDetails().user(accessToken.getSubject()).client(clientId).assertEvent();
RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
assertThat(refreshToken.getIssuedFor(), is(equalTo(clientId)));
assertThat(refreshToken.getAudience()[0], is(equalTo(refreshToken.getIssuer())));
@ -2778,7 +2779,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
assertThat(idToken.getAudience()[0], is(equalTo(idToken.getIssuedFor())));
checkTokenExpiration(idToken, tokenRes.getExpiresIn());
events.expectRefresh(tokenRes.getRefreshToken(), sessionId).session(CoreMatchers.notNullValue(String.class)).user(AssertEvents.isUUID()).clearDetails().assertEvent();
events.expectRefresh(tokenRes.getRefreshToken(), sessionId).session(CoreMatchers.notNullValue(String.class)).user(accessToken.getSubject()).clearDetails().assertEvent();
return tokenRes;
}
@ -2808,7 +2809,8 @@ public class CIBATest extends AbstractClientPoliciesTest {
if (isOfflineAccess) assertThat(tokenRes.getErrorDescription(), is(equalTo("Offline user session not found")));
else assertThat(tokenRes.getErrorDescription(), is(equalTo("Session not active")));
return events.expectLogout(sessionId).client(TEST_CLIENT_NAME).user(AssertEvents.isUUID()).session(AssertEvents.isUUID()).clearDetails().assertEvent();
RefreshToken rt = oauth.parseRefreshToken(refreshToken);
return events.expectLogout(sessionId).client(TEST_CLIENT_NAME).user(rt.getSubject()).session(AssertEvents.isUUID()).clearDetails().assertEvent();
}
private EventRepresentation doTokenRevokeByRefreshToken(String refreshToken, String sessionId, String userId, boolean isOfflineAccess) throws IOException {
@ -2823,7 +2825,8 @@ public class CIBATest extends AbstractClientPoliciesTest {
if (isOfflineAccess) assertThat(tokenRes.getErrorDescription(), is(equalTo("Offline user session not found")));
else assertThat(tokenRes.getErrorDescription(), is(equalTo("Session not active")));
return events.expect(EventType.REVOKE_GRANT).clearDetails().client(TEST_CLIENT_NAME).user(AssertEvents.isUUID()).assertEvent();
RefreshToken rt = oauth.parseRefreshToken(refreshToken);
return events.expect(EventType.REVOKE_GRANT).clearDetails().client(TEST_CLIENT_NAME).user(rt.getSubject()).assertEvent();
}
private void testBackchannelAuthenticationFlow(boolean isOfflineAccess) throws Exception {

View file

@ -622,12 +622,12 @@ public class FAPICIBATest extends AbstractClientPoliciesTest {
private void verifyBackchannelAuthenticationTokenRequest(OAuthClient.AccessTokenResponse tokenRes, String clientId, String username) {
assertThat(tokenRes.getStatusCode(), is(equalTo(200)));
events.expectAuthReqIdToToken(null, null).clearDetails().user(AssertEvents.isUUID()).client(clientId).assertEvent();
AccessToken accessToken = oauth.verifyToken(tokenRes.getAccessToken());
assertThat(accessToken.getIssuedFor(), is(equalTo(clientId)));
Assert.assertNotNull(accessToken.getCertConf().getCertThumbprint());
events.expectAuthReqIdToToken(null, null).clearDetails().user(accessToken.getSubject()).client(clientId).assertEvent();
RefreshToken refreshToken = oauth.parseRefreshToken(tokenRes.getRefreshToken());
assertThat(refreshToken.getIssuedFor(), is(equalTo(clientId)));

View file

@ -101,22 +101,18 @@ public class LoginTest extends AbstractTestRealmKeycloakTest {
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
UserRepresentation user = UserBuilder.create()
.id(UUID.randomUUID().toString())
.username("login-test")
.email("login@test.com")
.enabled(true)
.password("password")
.build();
userId = user.getId();
UserRepresentation user2 = UserBuilder.create()
.id(UUID.randomUUID().toString())
.username("login-test2")
.email("login2@test.com")
.enabled(true)
.password("password")
.build();
user2Id = user2.getId();
UserRepresentation admin = UserBuilder.create()
.username("admin")
@ -161,6 +157,13 @@ public class LoginTest extends AbstractTestRealmKeycloakTest {
private static String user2Id;
@Override
public void importTestRealms() {
super.importTestRealms();
userId = testRealm().users().search("login-test", Boolean.TRUE).get(0).getId();
user2Id = testRealm().users().search("login-test2", Boolean.TRUE).get(0).getId();
}
@Test
public void testBrowserSecurityHeaders() {
Client client = AdminClientUtil.createResteasyClient();

View file

@ -67,8 +67,8 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
public AssertEvents events = new AssertEvents(this);
private AuthenticationFlowRepresentation flow;
private final static String userId = UUID.randomUUID().toString();
private final static String failId = UUID.randomUUID().toString();
private static String userId;
private static String failId;
public static final String EXECUTION_ID = "scriptAuth";
@ -81,7 +81,7 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
public void configureTestRealm(RealmRepresentation testRealm) {
UserRepresentation failUser = UserBuilder.create()
.id(failId)
.id(UUID.randomUUID().toString())
.username("fail")
.email("fail@test.com")
.enabled(true)
@ -89,7 +89,7 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
.build();
UserRepresentation okayUser = UserBuilder.create()
.id(userId)
.id(UUID.randomUUID().toString())
.username("user")
.email("user@test.com")
.enabled(true)
@ -101,6 +101,13 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
.user(okayUser);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("user", true).get(0).getId();
failId = adminClient.realm("test").users().search("fail", true).get(0).getId();
}
@Before
public void configureFlows() throws Exception {
String scriptFlow = "scriptBrowser";

View file

@ -107,25 +107,12 @@ public class VerifyProfileTest extends AbstractTestRealmKeycloakTest {
enableDynamicUserProfile(testRealm);
UserRepresentation user = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test").email("login@test.com").enabled(true).password("password").build();
userId = user.getId();
UserRepresentation user2 = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test2").email("login2@test.com").enabled(true).password("password").build();
user2Id = user2.getId();
UserRepresentation user3 = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test3").email("login3@test.com").enabled(true).password("password").lastName("ExistingLast").build();
user3Id = user3.getId();
UserRepresentation user4 = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test4").email("login4@test.com").enabled(true).password("password").lastName("ExistingLast").build();
user4Id = user4.getId();
UserRepresentation user5 = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test5").email("login5@test.com").enabled(true).password("password").firstName("ExistingFirst").lastName("ExistingLast").build();
user5Id = user5.getId();
UserRepresentation user6 = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-test6").email("login6@test.com").enabled(true).password("password").firstName("ExistingFirst").lastName("ExistingLast").build();
user6Id = user6.getId();
UserRepresentation userWithoutEmail = UserBuilder.create().id(UUID.randomUUID().toString()).username("login-nomail").enabled(true).password("password").firstName("NoMailFirst").lastName("NoMailLast").build();
userWithoutEmailId = userWithoutEmail.getId();
RealmBuilder.edit(testRealm).user(user).user(user2).user(user3).user(user4).user(user5).user(user6).user(userWithoutEmail);
@ -151,6 +138,18 @@ public class VerifyProfileTest extends AbstractTestRealmKeycloakTest {
client_scope_optional.setRedirectUris(Collections.singletonList("*"));
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("login-test", true).get(0).getId();
user2Id = adminClient.realm("test").users().search("login-test2", true).get(0).getId();
user3Id = adminClient.realm("test").users().search("login-test3", true).get(0).getId();
user4Id = adminClient.realm("test").users().search("login-test4", true).get(0).getId();
user5Id = adminClient.realm("test").users().search("login-test5", true).get(0).getId();
user6Id = adminClient.realm("test").users().search("login-test6", true).get(0).getId();
userWithoutEmailId = adminClient.realm("test").users().search("login-nomail", true).get(0).getId();
}
@Rule
public AssertEvents events = new AssertEvents(this);

View file

@ -164,7 +164,6 @@ public class ClientAuthSignedJWTTest extends AbstractKeycloakTest {
.testEventListener();
app1 = ClientBuilder.create()
.id(KeycloakModelUtils.generateId())
.clientId("client1")
.attribute(JWTClientAuthenticator.CERTIFICATE_ATTR, generatedKeystoreClient1.getCertificateInfo().getCertificate())
.attribute(OIDCConfigAttributes.USE_REFRESH_TOKEN_FOR_CLIENT_CREDENTIALS_GRANT, "true")
@ -175,7 +174,6 @@ public class ClientAuthSignedJWTTest extends AbstractKeycloakTest {
realmBuilder.client(app1);
app2 = ClientBuilder.create()
.id(KeycloakModelUtils.generateId())
.clientId("client2")
.directAccessGrants()
.serviceAccountsEnabled(true)
@ -187,17 +185,13 @@ public class ClientAuthSignedJWTTest extends AbstractKeycloakTest {
realmBuilder.client(app2);
defaultUser = UserBuilder.create()
.id(KeycloakModelUtils.generateId())
//.serviceAccountId(app1.getClientId())
.username("test-user@localhost")
.password("password")
.build();
realmBuilder.user(defaultUser);
client1SAUserId = KeycloakModelUtils.generateId();
serviceAccountUser = UserBuilder.create()
.id(client1SAUserId)
.username(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + app1.getClientId())
.serviceAccountId(app1.getClientId())
.build();
@ -207,18 +201,29 @@ public class ClientAuthSignedJWTTest extends AbstractKeycloakTest {
testRealms.add(testRealm);
}
@Override
public void importTestRealms() {
super.importTestRealms();
app1 = adminClient.realm("test").clients().findByClientId("client1").get(0);
app2 = adminClient.realm("test").clients().findByClientId("client2").get(0);
defaultUser.setId(adminClient.realm("test").users().search("test-user@localhost", true).get(0).getId());
client1SAUserId = adminClient.realm("test").users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + app1.getClientId(), true).get(0).getId();
serviceAccountUser.setId(client1SAUserId);
}
@Before
public void recreateApp3() {
app3 = ClientBuilder.create()
.id(KeycloakModelUtils.generateId())
.clientId("client3")
.directAccessGrants()
.authenticatorType(JWTClientAuthenticator.PROVIDER_ID)
.build();
Response resp = adminClient.realm("test").clients().create(app3);
getCleanup().addClientUuid(ApiUtil.getCreatedId(resp));
resp.close();
try (Response resp = adminClient.realm("test").clients().create(app3)) {
final String id = ApiUtil.getCreatedId(resp);
getCleanup().addClientUuid(id);
app3.setId(id);
}
}
// TEST SUCCESS

View file

@ -143,7 +143,6 @@ public class OfflineTokenTest extends AbstractKeycloakTest {
realm.client(app);
serviceAccountUserId = KeycloakModelUtils.generateId();
UserRepresentation serviceAccountUser = UserBuilder.create()
.id(serviceAccountUserId)
.addRoles("user", "offline_access")
@ -157,6 +156,12 @@ public class OfflineTokenTest extends AbstractKeycloakTest {
}
@Override
public void importTestRealms() {
super.importTestRealms();
serviceAccountUserId = adminClient.realm("test").users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "offline-client", true).get(0).getId();
}
@Test
public void offlineTokenDisabledForClient() throws Exception {
// Remove offline-access scope from client

View file

@ -133,25 +133,20 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
.password("password");
realm.user(defaultUser);
userId = KeycloakModelUtils.generateId();
UserRepresentation user = UserBuilder.create()
.id(userId)
.username("direct-login")
.email("direct-login@localhost")
.password("password")
.build();
realm.user(user);
userId2 = KeycloakModelUtils.generateId();
UserRepresentation user2 = UserBuilder.create()
.id(userId2)
.username("direct-login-otp")
.password("password")
.totpSecret("totpSecret")
.build();
realm.user(user2);
userIdMultipleOTPs = KeycloakModelUtils.generateId();
UserBuilder userBuilderMultipleOTPs = UserBuilder.create()
.id(userIdMultipleOTPs)
.username("direct-login-multiple-otps")
@ -163,6 +158,14 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
testRealms.add(realm.build());
}
@Override
public void importTestRealms() {
super.importTestRealms();
userIdMultipleOTPs = adminClient.realm("test").users().search("direct-login-multiple-otps", true).get(0).getId();
userId = adminClient.realm("test").users().search("direct-login", true).get(0).getId();
userId2 = adminClient.realm("test").users().search("direct-login-otp", true).get(0).getId();
}
@Test
public void grantAccessTokenUsername() throws Exception {
int authSessionsBefore = getAuthenticationSessionsCount();

View file

@ -75,7 +75,8 @@ import static org.junit.Assert.assertThat;
*/
public class ServiceAccountTest extends AbstractKeycloakTest {
private static String userId;
private static String userIdClRefreshOn;
private static String userIdCl;
private static String userName;
@Rule
@ -137,11 +138,10 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
.username("test-user@localhost");
realm.user(defaultUser);
userId = KeycloakModelUtils.generateId();
userName = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + enabledApp.getClientId();
UserBuilder serviceAccountUser = UserBuilder.create()
.id(userId)
.id(KeycloakModelUtils.generateId())
.username(userName)
.serviceAccountId(enabledApp.getClientId());
realm.user(serviceAccountUser);
@ -149,6 +149,13 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
testRealms.add(realm.build());
}
@Override
public void importTestRealms() {
super.importTestRealms();
userIdClRefreshOn = adminClient.realm("test").users().search(userName, true).get(0).getId();
userIdCl = adminClient.realm("test").users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl", true).get(0).getId();
}
@Test
public void clientCredentialsAuthSuccess() throws Exception {
oauth.clientId("service-account-cl-refresh-on");
@ -169,7 +176,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expectClientLogin()
.client("service-account-cl-refresh-on")
.user(userId)
.user(userIdClRefreshOn)
.session(accessToken.getSessionState())
.detail(Details.TOKEN_ID, accessToken.getId())
.detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
@ -190,7 +197,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
assertEquals(accessToken.getSessionState(), refreshedAccessToken.getSessionState());
assertEquals(accessToken.getSessionState(), refreshedRefreshToken.getSessionState());
events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState()).user(userId).client("service-account-cl-refresh-on").assertEvent();
events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState()).user(userIdClRefreshOn).client("service-account-cl-refresh-on").assertEvent();
}
// This is for the backwards compatibility only. By default, there won't be refresh token and hence there won't be availability for the logout
@ -208,7 +215,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expectClientLogin()
.client("service-account-cl-refresh-on")
.user(userId)
.user(userIdClRefreshOn)
.session(accessToken.getSessionState())
.detail(Details.TOKEN_ID, accessToken.getId())
.detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
@ -220,7 +227,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
assertEquals(204, logoutResponse.getStatusLine().getStatusCode());
events.expectLogout(accessToken.getSessionState())
.client("service-account-cl-refresh-on")
.user(userId)
.user(userIdClRefreshOn)
.removeDetail(Details.REDIRECT_URI)
.assertEvent();
@ -230,7 +237,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState())
.client("service-account-cl-refresh-on")
.user(userId)
.user(userIdClRefreshOn)
.removeDetail(Details.TOKEN_ID)
.removeDetail(Details.UPDATED_REFRESH_TOKEN_ID)
.error(Errors.INVALID_TOKEN).assertEvent();
@ -293,7 +300,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
// Username updated after client ID changed
events.expectClientLogin()
.client("updated-client")
.user(userId)
.user(userIdClRefreshOn)
.session(accessToken.getSessionState())
.detail(Details.TOKEN_ID, accessToken.getId())
.detail(Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "updated-client")
@ -319,6 +326,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
finally {
ClientManager.realm(adminClient.realm("test")).clientId("service-account-cl").setServiceAccountsEnabled(true);
UserRepresentation user = ClientManager.realm(adminClient.realm("test")).clientId("service-account-cl").getServiceAccountUser();
userIdCl = user.getId();
}
}
@ -329,7 +337,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
@Test
public void failManagePassword() {
UserResource serviceAccount = adminClient.realm("test").users().get(userId);
UserResource serviceAccount = adminClient.realm("test").users().get(userIdClRefreshOn);
UserRepresentation representation = serviceAccount.toRepresentation();
CredentialRepresentation password = new CredentialRepresentation();
@ -361,7 +369,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expect(EventType.REVOKE_GRANT)
.client("service-account-cl")
.user(AssertEvents.isUUID())
.user(userIdCl)
.session(Matchers.isEmptyOrNullString())
.detail(Details.TOKEN_ID, accessToken.getId())
.assertEvent();
@ -404,7 +412,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expectClientLogin()
.client("service-account-cl")
.user(AssertEvents.isUUID())
.user(userIdCl)
.session(AssertEvents.isUUID())
.detail(Details.TOKEN_ID, accessToken.getId())
.detail(Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl")
@ -418,7 +426,6 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
Assert.assertTrue(getIntrospectionResponse("service-account-cl", "secret1", tokenString));
events.expect(EventType.INTROSPECT_TOKEN)
.client("service-account-cl")
.user(AssertEvents.isUUID())
.user(Matchers.isEmptyOrNullString())
.session(Matchers.isEmptyOrNullString())
.assertEvent();
@ -469,7 +476,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
events.expectClientLogin()
.client("service-account-cl-refresh-on")
.user(userId)
.user(userIdClRefreshOn)
.session(accessToken.getSessionState())
.detail(Details.TOKEN_ID, accessToken.getId())
.detail(Details.REFRESH_TOKEN_ID, refreshToken.getId())
@ -490,7 +497,7 @@ public class ServiceAccountTest extends AbstractKeycloakTest {
assertEquals(accessToken.getSessionState(), refreshedAccessToken.getSessionState());
assertEquals(accessToken.getSessionState(), refreshedRefreshToken.getSessionState());
events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState()).user(userId).client("service-account-cl-refresh-on").assertEvent();
events.expectRefresh(refreshToken.getId(), refreshToken.getSessionState()).user(userIdClRefreshOn).client("service-account-cl-refresh-on").assertEvent();
}
@Test

View file

@ -107,11 +107,10 @@ public class ServiceAccountUserProfileTest extends AbstractKeycloakTest {
.username("test-user@localhost");
realm.user(defaultUser);
userId = KeycloakModelUtils.generateId();
userName = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + enabledApp.getClientId();
UserBuilder serviceAccountUser = UserBuilder.create()
.id(userId)
.id(KeycloakModelUtils.generateId())
.username(userName)
.serviceAccountId(enabledApp.getClientId());
realm.user(serviceAccountUser);
@ -121,6 +120,12 @@ public class ServiceAccountUserProfileTest extends AbstractKeycloakTest {
testRealms.add(realmRep);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search(userName, true).get(0).getId();
}
@Test
public void testDoNotUpdateUsername() {
RealmResource test = adminClient.realm("test");

View file

@ -428,7 +428,7 @@ public class HoKTest extends AbstractTestRealmKeycloakTest {
assertEquals(1, refreshedToken.getResourceAccess(oauth.getClientId()).getRoles().size());
Assert.assertTrue(refreshedToken.getResourceAccess(oauth.getClientId()).isUserInRole("customer-user"));
EventRepresentation refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).user(AssertEvents.isUUID()).assertEvent();
EventRepresentation refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).user(refreshToken.getSubject()).assertEvent();
Assert.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
Assert.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));

View file

@ -65,12 +65,17 @@ public abstract class AbstractRARParserTest extends AbstractTestRealmKeycloakTes
.enabled(true)
.password("password")
.build();
userId = user.getId();
RealmBuilder.edit(testRealm)
.user(user);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("rar-test", true).get(0).getId();
}
@Before
public void clientConfiguration() {
ClientManager.realm(adminClient.realm("test")).clientId("test-app").directAccessGrant(true);

View file

@ -48,7 +48,7 @@ import java.util.Collections;
*/
public class AudienceTest extends AbstractOIDCScopeTest {
private static final String userId = KeycloakModelUtils.generateId();
private static String userId;
@Override
@ -74,7 +74,7 @@ public class AudienceTest extends AbstractOIDCScopeTest {
// Create sample user
UserRepresentation user = UserBuilder.create()
.id(userId)
.id(KeycloakModelUtils.generateId())
.username("john")
.enabled(true)
.email("john@email.cz")
@ -88,6 +88,12 @@ public class AudienceTest extends AbstractOIDCScopeTest {
testRealm.getUsers().add(user);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("john", true).get(0).getId();
}
@Before
public void beforeTest() {
// Check if already exists

View file

@ -55,13 +55,13 @@ import static org.keycloak.common.Profile.Feature.DYNAMIC_SCOPES;
@EnableFeature(value = Profile.Feature.DYNAMIC_SCOPES, skipRestart = true)
public class OIDCDynamicScopeTest extends OIDCScopeTest {
private static String userId = KeycloakModelUtils.generateId();
private static String userId;
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
super.configureTestRealm(testRealm);
UserRepresentation user = UserBuilder.create()
.id(userId)
.id(KeycloakModelUtils.generateId())
.username("johnDynamic")
.enabled(true)
.email("johnDynamic@scopes.xyz")
@ -86,6 +86,12 @@ public class OIDCDynamicScopeTest extends OIDCScopeTest {
testRealm.getRoles().getRealm().add(dynamicScopeRole);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("john", true).get(0).getId();
}
@Before
public void assertDynamicScopesFeatureEnabled() {
ProfileAssume.assumeFeatureEnabled(DYNAMIC_SCOPES);

View file

@ -66,12 +66,12 @@ import static org.keycloak.testsuite.auth.page.AuthRealm.TEST;
*/
public class OIDCScopeTest extends AbstractOIDCScopeTest {
private static String userId = KeycloakModelUtils.generateId();
private static String userId;
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
UserRepresentation user = UserBuilder.create()
.id(userId)
.id(KeycloakModelUtils.generateId())
.username("john")
.enabled(true)
.email("john@email.cz")
@ -148,6 +148,12 @@ public class OIDCScopeTest extends AbstractOIDCScopeTest {
testRealm.getUsers().add(user);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId = adminClient.realm("test").users().search("john", true).get(0).getId();
}
@Before
public void clientConfiguration() {
ClientManager.realm(adminClient.realm("test")).clientId("test-app").directAccessGrant(true);

View file

@ -297,8 +297,6 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
.addAttribute("x509_issuer_identity", "Keycloak Intermediate CA")
.build();
userId2 = user.getId();
ClientRepresentation client = findTestApp(testRealm);
URI baseUri = URI.create(client.getRedirectUris().get(0));
URI redir = URI.create("https://localhost:" + System.getProperty("auth.server.https.port", "8543") + baseUri.getRawPath());
@ -312,6 +310,12 @@ public abstract class AbstractX509AuthenticationTest extends AbstractTestRealmKe
.client(app);
}
@Override
public void importTestRealms() {
super.importTestRealms();
userId2 = adminClient.realm("test").users().search("keycloak", true).get(0).getId();
}
AuthenticationFlowRepresentation createFlow(AuthenticationFlowRepresentation flowRep) {
Response response = authMgmtResource.createFlow(flowRep);
try {