Java Code Examples for org.keycloak.admin.client.Keycloak#getInstance()

The following examples show how to use org.keycloak.admin.client.Keycloak#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GroupTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that the role assigned to a user is correctly handled by Keycloak Admin endpoint.
 * @link https://issues.jboss.org/browse/KEYCLOAK-2964
 */
@Test
public void adminEndpointAccessibleWhenAdminRoleAssignedToUser() {
    String userName = "user-" + UUID.randomUUID();

    final String realmName = AuthRealm.MASTER;
    RealmResource realm = adminClient.realms().realm(realmName);
    RoleRepresentation adminRole = realm.roles().get(AdminRoles.ADMIN).toRepresentation();
    assertThat(adminRole, notNullValue());
    assertThat(adminRole.getId(), notNullValue());

    String userId = createUser(realmName, userName, "pwd");
    assertThat(userId, notNullValue());

    RoleMappingResource mappings = realm.users().get(userId).roles();
    mappings.realmLevel().add(Collections.singletonList(adminRole));

    try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
      realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {

        assertThat(userClient.realms().findAll(),  // Any admin operation will do
                not(empty()));
    }
}
 
Example 2
Source File: TestsHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static boolean importTestRealm(String username, String password, String realmJsonPath) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        ClassLoader classLoader = TestsHelper.class.getClassLoader();
        InputStream stream = TestsHelper.class.getResourceAsStream(realmJsonPath);
        RealmRepresentation realmRepresentation = mapper.readValue(stream, RealmRepresentation.class);

        Keycloak keycloak = Keycloak.getInstance(
                keycloakBaseUrl,
                "master",
                username,
                password,
                "admin-cli");
        keycloak.realms().create(realmRepresentation);
        testRealm = realmRepresentation.getRealm();
        generateInitialAccessToken(keycloak);
        return true;

    }
 
Example 3
Source File: KeycloakProvider.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private Keycloak createKeycloak(
        KeycloakConfigProperties properties
) {
    return Keycloak.getInstance(
            buildUri(properties.getUrl()),
            properties.getLoginRealm(),
            properties.getUser(),
            properties.getPassword(),
            properties.getClientId(),
            null,
            null,
            null,
            !properties.isSslVerify(),
            null
    );
}
 
Example 4
Source File: CrossRealmPermissionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmBuilder builder = RealmBuilder.create().name(REALM_NAME).testMail();
    builder.client(ClientBuilder.create().clientId("test-client").publicClient().directAccessGrants());

    builder.user(UserBuilder.create()
            .username(AdminRoles.REALM_ADMIN)
            .role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN)
            .addPassword("password"));
    testRealms.add(builder.build());

    adminClient1 = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", REALM_NAME, AdminRoles.REALM_ADMIN, "password", "test-client", "secret", TLSUtils.initializeTLS());
    realm1 = adminClient1.realm(REALM_NAME);

    builder = RealmBuilder.create().name(REALM2_NAME).testMail();
    builder.client(ClientBuilder.create().clientId("test-client").publicClient().directAccessGrants());

    builder.user(UserBuilder.create()
            .username(AdminRoles.REALM_ADMIN)
            .role(Constants.REALM_MANAGEMENT_CLIENT_ID, AdminRoles.REALM_ADMIN)
            .addPassword("password"));

    testRealms.add(builder.build());

    adminClient2 = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", REALM2_NAME, AdminRoles.REALM_ADMIN, "password", "test-client", "secret", TLSUtils.initializeTLS());
    realm2 = adminClient2.realm(REALM2_NAME);
}
 
Example 5
Source File: Main.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String serverUrl = "http://127.0.0.1:8081/auth";
        String realm = "session-propagation";
        String username = "tester";
        String password = "test";
        String clientId = "app-backend";
        String clientSecret = "0b69f10f-ba95-4674-a2d0-62a7d6ae60f7";

        Keycloak keycloak = Keycloak.getInstance(serverUrl, realm, username, password, clientId, clientSecret);
        AccessTokenResponse accessToken = keycloak.tokenManager().getAccessToken();
        String sessionState = accessToken.getSessionState();
        System.out.println(sessionState);

        while (true) {
            Thread.sleep(2500);
            Map<Object, Object> data = new HashMap<>();
            data.put(OAuth2Constants.CLIENT_ID, clientId);
            data.put(OAuth2Constants.CLIENT_SECRET, clientSecret);
            data.put("token", keycloak.tokenManager().getAccessTokenString());

            HttpRequest postRequest = HttpRequest.newBuilder()
                    .uri(URI.create(String.format("%s/realms/%s/protocol/openid-connect/token/introspect", serverUrl, realm)))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .POST(ofFormData(data))
                    .build();

            HttpClient client = HttpClient.newHttpClient();

            HttpResponse.BodyHandler<String> asString = HttpResponse.BodyHandlers.ofString();
            HttpResponse<String> response = client.send(postRequest, asString);

            System.out.printf("%s: %s %n", Instant.now(), response.body());
        }
    }
 
Example 6
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-7406
 *
 * @throws Exception
 */
@Test
@UncaughtServerErrorExpected
@AuthServerContainerExclude(AuthServer.REMOTE)
@EnableFeature(value = Profile.Feature.TOKEN_EXCHANGE, skipRestart = true)
public void testWithTokenExchange() throws Exception {
    String exchanged = checkTokenExchange(true);
    Assert.assertNotNull(exchanged);
    try (Keycloak client = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
            AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, exchanged, TLSUtils.initializeTLS())) {
        Assert.assertNotNull(client.realm("master").roles().get("offline_access"));
    }
}
 
Example 7
Source File: OfflineTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-4201
 *
 * @throws Exception
 */
@Test
public void offlineTokenAdminRESTAccess() throws Exception {
    // Grant "view-realm" role to user
    RealmResource appRealm = adminClient.realm("test");
    ClientResource realmMgmt = ApiUtil.findClientByClientId(appRealm, Constants.REALM_MANAGEMENT_CLIENT_ID);
    String realmMgmtUuid = realmMgmt.toRepresentation().getId();
    RoleRepresentation roleRep = realmMgmt.roles().get(AdminRoles.VIEW_REALM).toRepresentation();

    UserResource testUser = findUserByUsernameId(appRealm, "test-user@localhost");
    testUser.roles().clientLevel(realmMgmtUuid).add(Collections.singletonList(roleRep));

    // Login with offline token now
    oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
    oauth.clientId("offline-client");
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("secret1", "test-user@localhost", "password");

    events.clear();

    // Set the time offset, so that "normal" userSession expires
    setTimeOffset(86400);

    // Remove expired sessions. This will remove "normal" userSession
    testingClient.testing().removeUserSessions(appRealm.toRepresentation().getId());

    // Refresh with the offline token
    tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "secret1");

    // Use accessToken to admin REST request
    try (Keycloak offlineTokenAdmin = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
            AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, tokenResponse.getAccessToken(), TLSUtils.initializeTLS())) {
        RealmRepresentation testRealm = offlineTokenAdmin.realm("test").toRepresentation();
        Assert.assertNotNull(testRealm);
    }
}
 
Example 8
Source File: RealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginAfterRemoveRealm() {
    realm.remove();

    try (Keycloak client = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth", "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        client.serverInfo().getInfo();
    }

    reCreateRealm();
}
 
Example 9
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the role assigned to a user's group is correctly handled by Keycloak Admin endpoint.
 * @link https://issues.jboss.org/browse/KEYCLOAK-2964
 */
@Test
public void adminEndpointAccessibleWhenAdminRoleAssignedToGroupAfterUserJoinedIt() {
    String userName = "user-" + UUID.randomUUID();
    String groupName = "group-" + UUID.randomUUID();

    final String realmName = AuthRealm.MASTER;
    RealmResource realm = adminClient.realms().realm(realmName);
    RoleRepresentation adminRole = realm.roles().get(AdminRoles.ADMIN).toRepresentation();
    assertThat(adminRole, notNullValue());
    assertThat(adminRole.getId(), notNullValue());

    String userId = createUser(realmName, userName, "pwd");
    GroupRepresentation group = GroupBuilder.create().name(groupName).build();
    try (Response response = realm.groups().add(group)) {
        String groupId = ApiUtil.getCreatedId(response);

        realm.users().get(userId).joinGroup(groupId);

        RoleMappingResource mappings = realm.groups().group(groupId).roles();

        mappings.realmLevel().add(Collections.singletonList(adminRole));
    }
    try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
      realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {

        assertThat(userClient.realms().findAll(),  // Any admin operation will do
            not(empty()));
    }
}
 
Example 10
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the role assigned to a user's group is correctly handled by Keycloak Admin endpoint.
 * @link https://issues.jboss.org/browse/KEYCLOAK-2964
 */
@Test
public void adminEndpointAccessibleWhenAdminRoleAssignedToGroup() {
    String userName = "user-" + UUID.randomUUID();
    String groupName = "group-" + UUID.randomUUID();

    final String realmName = AuthRealm.MASTER;
    RealmResource realm = adminClient.realms().realm(realmName);
    RoleRepresentation adminRole = realm.roles().get(AdminRoles.ADMIN).toRepresentation();
    assertThat(adminRole, notNullValue());
    assertThat(adminRole.getId(), notNullValue());

    String userId = createUser(realmName, userName, "pwd");
    GroupRepresentation group = GroupBuilder.create().name(groupName).build();
    try (Response response = realm.groups().add(group)) {
        String groupId = ApiUtil.getCreatedId(response);
    
        RoleMappingResource mappings = realm.groups().group(groupId).roles();
        mappings.realmLevel().add(Collections.singletonList(adminRole));

        realm.users().get(userId).joinGroup(groupId);
    }
    try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
      realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {

        assertThat(userClient.realms().findAll(),  // Any admin operation will do
            not(empty()));
    }
}
 
Example 11
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void createTestUser(String username, String password, String realmName, String newUsername, String newPassword, String... roles) {
    Keycloak keycloak = Keycloak.getInstance(
            KEYCLOAK_URL,
            "master",
            username,
            password,
            CLIENT);

    //add roles
    for (String role : roles) {
        RoleRepresentation representation = new RoleRepresentation();
        representation.setName(role);
        RolesResource realmsRoles = keycloak.realms().realm(realmName).roles();
        if (realmsRoles.list().stream().map(RoleRepresentation::getName).noneMatch(role::equals)) {
            realmsRoles.create(representation);
        }
    }

    UserRepresentation userRepresentation = new UserRepresentation();
    userRepresentation.setUsername(newUsername);
    userRepresentation.setEnabled(Boolean.TRUE);
    userRepresentation.setRealmRoles(Arrays.asList(roles));
    Response response = keycloak.realms().realm(realmName).users().create(userRepresentation);
    String userId = TestsHelper.getCreatedId(response);
    response.close();
    CredentialRepresentation rep = new CredentialRepresentation();
    rep.setType(CredentialRepresentation.PASSWORD);
    rep.setValue(newPassword);
    rep.setTemporary(false);
    keycloak.realms().realm(realmName).users().get(userId).resetPassword(rep);
}
 
Example 12
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void nonMasterAdminCantExportTestRealm() throws IOException {
    try {
        final String testAdminUser = "test.admin";
        TestsHelper.importTestRealm("admin", "admin", "/" + TEST_REALM_NAME + "-realm.json");
        createTestUser("admin", "admin", TEST_REALM_NAME, testAdminUser, "password", "user", "admin");
        Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, TEST_REALM_NAME, testAdminUser, "password", CLIENT);
        String token = keycloak.tokenManager().getAccessTokenString();
        expectedEx.expect(HttpResponseException.class);
        expectedEx.expect(hasProperty("statusCode", is(403)));
        exportRealm(token, TEST_REALM_NAME);
    } finally {
        TestsHelper.deleteRealm("admin", "admin", TEST_REALM_NAME);
    }
}
 
Example 13
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void nonMasterAdminCantExportMaster() throws IOException {
    try {
        final String testAdminUser = "test.admin";
        TestsHelper.importTestRealm("admin", "admin", "/" + TEST_REALM_NAME + "-realm.json");
        createTestUser("admin", "admin", TEST_REALM_NAME, testAdminUser, "password", "user", "admin");
        Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, TEST_REALM_NAME, testAdminUser, "password", CLIENT);
        String token = keycloak.tokenManager().getAccessTokenString();
        expectedEx.expect(HttpResponseException.class);
        expectedEx.expect(hasProperty("statusCode", is(403)));
        exportRealm(token, "master");
    } finally {
        TestsHelper.deleteRealm("admin", "admin", TEST_REALM_NAME);
    }
}
 
Example 14
Source File: TestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean deleteRealm(String username, String password, String realmName) throws IOException {

        Keycloak keycloak = Keycloak.getInstance(
                keycloakBaseUrl,
                "master",
                username,
                password,
                "admin-cli");
        keycloak.realms().realm(realmName).remove();
        return true;

    }
 
Example 15
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@AfterClass
public static void resetRealm() {
    //idempotence
    Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
    UserRepresentation user = keycloak.realm("master").users().search(TEST_USER).get(0);
    keycloak.realm("master").users().delete(user.getId());
    keycloak.realm("master").roles().get("user").remove();
    if (clientBeforeChanges != null) {
        keycloak.realms().realm("master").clients().get(clientBeforeChanges.getId()).update(clientBeforeChanges);
    }
}
 
Example 16
Source File: CrossDCTestEnricher.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static Keycloak createAdminClientFor(ContainerInfo node) {
    log.info("--DC: Initializing admin client for " + node.getContextRoot() + "/auth");
    return Keycloak.getInstance(node.getContextRoot() + "/auth", AuthRealm.MASTER, AuthRealm.ADMIN, AuthRealm.ADMIN, Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS());
}
 
Example 17
Source File: GroupTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that the user does not have access to Keycloak Admin endpoint when role is not
 * assigned to that user.
 * @link https://issues.jboss.org/browse/KEYCLOAK-2964
 */
@Test
public void noAdminEndpointAccessWhenNoRoleAssigned() {
    String userName = "user-" + UUID.randomUUID();
    final String realmName = AuthRealm.MASTER;
    createUser(realmName, userName, "pwd");

    try (Keycloak userClient = Keycloak.getInstance(AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
      realmName, userName, "pwd", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {

        expectedException.expect(ClientErrorException.class);
        expectedException.expectMessage(String.valueOf(Response.Status.FORBIDDEN.getStatusCode()));
        userClient.realms().findAll();  // Any admin operation will do
    }
}
 
Example 18
Source File: AbstractClusterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Keycloak createAdminClientFor(ContainerInfo node) {
    log.info("Initializing admin client for " + node.getContextRoot() + "/auth");
    return Keycloak.getInstance(node.getContextRoot() + "/auth",
            MASTER, ADMIN, ADMIN, Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS());
}
 
Example 19
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void importEqualsExport() throws IOException {
    try {
        Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
        String token = keycloak.tokenManager().getAccessTokenString();
        new ObjectMapper().readTree(new File(TEST_REALM_PATH));
        RealmRepresentation fileRepresentation = new ObjectMapper().readValue(new File(TEST_REALM_PATH), RealmRepresentation.class);
        Assert.assertNotNull(fileRepresentation);
        TestsHelper.importTestRealm("admin", "admin", "/" + TEST_REALM_NAME + "-realm.json");
        RealmRepresentation exportedRealm = exportRealm(token, TEST_REALM_NAME);
        Assert.assertEquals(fileRepresentation.getUsers().size(), exportedRealm.getUsers().size());
        //making sure all users are imported
        IntStream.range(0, fileRepresentation.getUsers().size()).forEach(i -> {
            UserRepresentation fileUser = fileRepresentation.getUsers().get(i);
            UserRepresentation exportedUser = exportedRealm.getUsers().parallelStream().filter(c -> c.getId().equals(fileUser.getId())).findAny().get();
            Assert.assertEquals(fileUser.getUsername(), exportedUser.getUsername());
            Assert.assertEquals(fileUser.getCredentials(), exportedUser.getCredentials());
            //making sure credentials are imported
            if (fileUser.getCredentials() != null && !fileUser.getCredentials().isEmpty()) {
                Assert.assertEquals(fileUser.getCredentials().get(0).getSecretData(), exportedUser.getCredentials().get(0).getSecretData());
            }
        });
        //making sure client secrets are well imported and exported
        IntStream.range(0, fileRepresentation.getClients().size()).forEach(i -> {
            ClientRepresentation fileClient = fileRepresentation.getClients().get(i);
            ClientRepresentation exportedClient = exportedRealm.getClients().parallelStream().filter(c -> c.getId().equals(fileClient.getId())).findAny().get();
            Assert.assertEquals(fileClient.getId(), exportedClient.getId());
            Assert.assertEquals(fileClient.getName(), exportedClient.getName());
            Assert.assertEquals(fileClient.getSecret(), exportedClient.getSecret());
        });
        //groups...
        IntStream.range(0, fileRepresentation.getGroups().size()).forEach(i -> {
            GroupRepresentation fileGroup = fileRepresentation.getGroups().get(i);
            GroupRepresentation exportedGroup = exportedRealm.getGroups().parallelStream().filter(c -> c.getId().equals(fileGroup.getId())).findAny().get();
            Assert.assertEquals(fileGroup.getId(), exportedGroup.getId());
            Assert.assertEquals(fileGroup.getName(), exportedGroup.getName());
        });
        //realm roles (do not compare IDs, as they might be changed by the import mechanism)
        IntStream.range(0, fileRepresentation.getRoles().getRealm().size()).forEach(i -> {
            RoleRepresentation fileRealmRole = fileRepresentation.getRoles().getRealm().get(i);
            Optional<RoleRepresentation> exportRealmRoleOpt = exportedRealm.getRoles().getRealm().parallelStream().filter(c -> c.getName().equals(fileRealmRole.getName())).findAny();
            Assert.assertTrue(exportRealmRoleOpt.isPresent());
        });
        //clients roles
        fileRepresentation.getRoles().getClient().keySet().forEach(clientId -> {
            List<RoleRepresentation> fileClientRoles = fileRepresentation.getRoles().getClient().get(clientId);
            List<RoleRepresentation> exportedClientRoles = exportedRealm.getRoles().getClient().get(clientId);
            IntStream.range(0, fileClientRoles.size()).forEach(i -> {
                RoleRepresentation fileClientRole = fileClientRoles.get(i);
                RoleRepresentation exportedClientRole = exportedClientRoles.parallelStream().filter(c -> c.getId().equals(fileClientRole.getId())).findAny().get();
                Assert.assertEquals(fileClientRole.getId(), exportedClientRole.getId());
                Assert.assertEquals(fileClientRole.getName(), exportedClientRole.getName());
            });
        });
    } finally {
        //idempotence
        TestsHelper.deleteRealm("admin", "admin", TEST_REALM_NAME);
    }
}
 
Example 20
Source File: FluentTestsHelper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Keycloak getKeycloakInstance(String keycloakBaseUrl, String realm, String username, String password, String clientId) {
    return Keycloak.getInstance(keycloakBaseUrl, realm, username, password, clientId);
}