Java Code Examples for org.keycloak.representations.idm.ClientRepresentation#getId()

The following examples show how to use org.keycloak.representations.idm.ClientRepresentation#getId() . 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: ClientImportService.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
private void updateClient(String realm, ClientRepresentation patchedClient) {
    try {
        clientRepository.update(realm, patchedClient);
    } catch (WebApplicationException error) {
        String errorMessage = ResponseUtil.getErrorMessage(error);
        throw new ImportProcessingException("Cannot update client '" + patchedClient.getClientId() + "' for realm '" + realm + "': " + errorMessage, error);
    }

    List<ProtocolMapperRepresentation> protocolMappers = patchedClient.getProtocolMappers();
    if (protocolMappers != null) {
        String clientId = patchedClient.getId();
        updateProtocolMappers(realm, clientId, protocolMappers);
    }
}
 
Example 2
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void assignClientRoles(RealmResource realm, String userId, String clientName, String... roles) {
    String realmName = realm.toRepresentation().getRealm();
    String clientId = "";
    for (ClientRepresentation clientRepresentation : realm.clients().findAll()) {
        if (clientRepresentation.getClientId().equals(clientName)) {
            clientId = clientRepresentation.getId();
        }
    }

    if (!clientId.isEmpty()) {
        ClientResource clientResource = realm.clients().get(clientId);

        List<RoleRepresentation> roleRepresentations = new ArrayList<>();
        for (String roleName : roles) {
            RoleRepresentation role = clientResource.roles().get(roleName).toRepresentation();
            roleRepresentations.add(role);
        }

        UserResource userResource = realm.users().get(userId);
        log.info("assigning role: " + Arrays.toString(roles) + " to user: \""
                + userResource.toRepresentation().getUsername() + "\" of client: \""
                + clientName + "\" in realm: \"" + realmName + "\"");
        userResource.roles().clientLevel(clientId).add(roleRepresentations);
    } else {
        log.warn("client with name " + clientName + " doesn't exist in realm " + realmName);
    }
}
 
Example 3
Source File: ClientTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void pushRevocation() {
    testingClient.testApp().clearAdminActions();

    ClientRepresentation client = createAppClient();
    String id = client.getId();

    realm.clients().get(id).pushRevocation();

    PushNotBeforeAction pushNotBefore = testingClient.testApp().getAdminPushNotBefore();
    assertEquals(client.getNotBefore().intValue(), pushNotBefore.getNotBefore());

    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientPushRevocationPath(id), ResourceType.CLIENT);
}
 
Example 4
Source File: ClientTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test (expected = BadRequestException.class)
public void testAddNodeWithReservedCharacter() {
    testingClient.testApp().clearAdminActions();

    ClientRepresentation client = createAppClient();
    String id = client.getId();

    realm.clients().get(id).registerNode(Collections.singletonMap("node", "foo#"));
}
 
Example 5
Source File: UsersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private RealmResource setupTestEnvironmentWithPermissions(boolean grp1ViewPermissions) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    String testUserId = createUser(realmId, "test-user", "password", "", "", "");
    //assign 'query-users' role to test user
    ClientRepresentation clientRepresentation = realm.clients().findByClientId("realm-management").get(0);
    String realmManagementId = clientRepresentation.getId();
    RoleRepresentation roleRepresentation = realm.clients().get(realmManagementId).roles().get("query-users").toRepresentation();
    realm.users().get(testUserId).roles().clientLevel(realmManagementId).add(Collections.singletonList(roleRepresentation));

    //create test users and groups
    List<GroupRepresentation> groups = setupUsersInGroupsWithPermissions();

    if (grp1ViewPermissions) {
        AuthorizationResource authorizationResource = realm.clients().get(realmManagementId).authorization();
        //create a user policy for the test user
        UserPolicyRepresentation policy = new UserPolicyRepresentation();
        String policyName = "test-policy";
        policy.setName(policyName);
        policy.setUsers(Collections.singleton(testUserId));
        authorizationResource.policies().user().create(policy);
        PolicyRepresentation policyRepresentation = authorizationResource.policies().findByName(policyName);
        //add the policy to grp1
        Optional<GroupRepresentation> optional = groups.stream().filter(g -> g.getName().equals("grp1")).findFirst();
        assertThat(optional.isPresent(), is(true));
        GroupRepresentation grp1 = optional.get();
        ScopePermissionRepresentation scopePermissionRepresentation = authorizationResource.permissions().scope().findByName("view.members.permission.group." + grp1.getId());
        scopePermissionRepresentation.setPolicies(Collections.singleton(policyRepresentation.getId()));
        scopePermissionRepresentation.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
        authorizationResource.permissions().scope().findById(scopePermissionRepresentation.getId()).update(scopePermissionRepresentation);
    }

    Keycloak testUserClient = AdminClientUtil.createAdminClient(true, realm.toRepresentation().getRealm(), "test-user", "password", "admin-cli", "");

    return testUserClient.realm(realm.toRepresentation().getRealm());
}
 
Example 6
Source File: ClientTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
// KEYCLOAK-1110
public void deleteDefaultRole() {
    ClientRepresentation rep = createClient();
    String id = rep.getId();

    RoleRepresentation role = new RoleRepresentation("test", "test", false);
    realm.clients().get(id).roles().create(role);

    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(id, "test"), role, ResourceType.CLIENT_ROLE);

    ClientRepresentation foundClientRep = realm.clients().get(id).toRepresentation();
    foundClientRep.setDefaultRoles(new String[]{"test"});
    realm.clients().get(id).update(foundClientRep);

    assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT);

    assertArrayEquals(new String[]{"test"}, realm.clients().get(id).toRepresentation().getDefaultRoles());

    realm.clients().get(id).roles().deleteRole("test");

    assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientRoleResourcePath(id, "test"), ResourceType.CLIENT_ROLE);

    assertNull(realm.clients().get(id).toRepresentation().getDefaultRoles());
}
 
Example 7
Source File: ClientTest.java    From keycloak with Apache License 2.0 3 votes vote down vote up
@Test
public void nodes() {
    testingClient.testApp().clearAdminActions();

    ClientRepresentation client = createAppClient();
    String id = client.getId();

    String myhost = suiteContext.getAuthServerInfo().getContextRoot().getHost();
    realm.clients().get(id).registerNode(Collections.singletonMap("node", myhost));
    realm.clients().get(id).registerNode(Collections.singletonMap("node", "invalid"));

    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, myhost), ResourceType.CLUSTER_NODE);
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE);

    GlobalRequestResult result = realm.clients().get(id).testNodesAvailable();
    assertEquals(1, result.getSuccessRequests().size());
    assertEquals(1, result.getFailedRequests().size());

    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientTestNodesAvailablePath(id), result, ResourceType.CLUSTER_NODE);

    TestAvailabilityAction testAvailable = testingClient.testApp().getTestAvailable();
    assertEquals("test-app", testAvailable.getResource());

    assertEquals(2, realm.clients().get(id).toRepresentation().getRegisteredNodes().size());

    realm.clients().get(id).unregisterNode("invalid");

    assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE);

    assertEquals(1, realm.clients().get(id).toRepresentation().getRegisteredNodes().size());
}
 
Example 8
Source File: AbstractAdmCliTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
void testCRUDWithOnTheFlyAuth(String serverUrl, String credentials, String extraOptions, String loginMessage) throws IOException {

        File configFile = getDefaultConfigFilePath();
        long lastModified = configFile.exists() ? configFile.lastModified() : 0;

        // This test assumes it is the only user of any instance of on the system
        KcAdmExec exe = execute("create clients --no-config --server " + serverUrl +
                " --realm test " + credentials + " " + extraOptions + " -s clientId=test-client -o");

        Assert.assertEquals("exitCode == 0", 0, exe.exitCode());
        Assert.assertEquals("login message", loginMessage, exe.stderrLines().get(0));

        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client.getClientId());

        long lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("get clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        assertExitCodeAndStdErrSize(exe, 0, 1);

        ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client2.getClientId());

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("update clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " +
                credentials + " " + extraOptions + " -s enabled=false -o");

        assertExitCodeAndStdErrSize(exe, 0, 1);

        ClientRepresentation client4 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("clientId", "test-client", client4.getClientId());
        Assert.assertFalse("enabled", client4.isEnabled());

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        exe = execute("delete clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        int linecountOffset = "".equals(loginMessage) ? 1 : 0; // if there is no login, then there is one less stdErrLinecount
        assertExitCodeAndStreamSizes(exe, 0, 0, 1 - linecountOffset);

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);




        // subsequent delete should fail
        exe = execute("delete clients/" + client.getId() + " --no-config --server " + serverUrl + " --realm test " + credentials + " " + extraOptions);

        assertExitCodeAndStreamSizes(exe, 1, 0, 2 - linecountOffset);
        String resourceUri = serverUrl + "/admin/realms/test/clients/" + client.getId();
        Assert.assertEquals("error message", "Resource not found for url: " + resourceUri, exe.stderrLines().get(1 - linecountOffset));

        lastModified2 = configFile.exists() ? configFile.lastModified() : 0;
        Assert.assertEquals("config file not modified", lastModified, lastModified2);
    }