org.keycloak.admin.client.resource.RealmResource Java Examples

The following examples show how to use org.keycloak.admin.client.resource.RealmResource. 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: KcOidcBrokerWithConsentTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeBrokerTest() {
    super.beforeBrokerTest();
    // Require broker to show consent screen
    RealmResource brokeredRealm = adminClient.realm(bc.providerRealmName());
    List<ClientRepresentation> clients = brokeredRealm.clients().findByClientId("brokerapp");
    org.junit.Assert.assertEquals(1, clients.size());
    ClientRepresentation brokerApp = clients.get(0);
    brokerApp.setConsentRequired(true);
    brokeredRealm.clients().get(brokerApp.getId()).update(brokerApp);


    // Change timeouts on realm-with-broker to lower values
    RealmResource realmWithBroker = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realmWithBroker.toRepresentation();
    realmRep.setAccessCodeLifespanLogin(30);;
    realmRep.setAccessCodeLifespan(30);
    realmRep.setAccessCodeLifespanUserAction(30);
    realmWithBroker.update(realmRep);
}
 
Example #2
Source File: UsersTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void countUsersBySearchWithGroupViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RealmResource testRealmResource = setupTestEnvironmentWithPermissions(true);
    //search all
    assertThat(testRealmResource.users().count("user"), is(3));
    //search first name
    assertThat(testRealmResource.users().count("FirstName"), is(3));
    assertThat(testRealmResource.users().count("user2FirstName"), is(1));
    //search last name
    assertThat(testRealmResource.users().count("LastName"), is(3));
    assertThat(testRealmResource.users().count("user2LastName"), is(1));
    //search in email
    assertThat(testRealmResource.users().count("@example.com"), is(3));
    assertThat(testRealmResource.users().count("[email protected]"), is(1));
    //search for something not existing
    assertThat(testRealmResource.users().count("notExisting"), is(0));
    //search for empty string
    assertThat(testRealmResource.users().count(""), is(3));
    //search not specified (defaults to simply /count)
    assertThat(testRealmResource.users().count(null), is(3));
}
 
Example #3
Source File: ExportImportTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleFileRealmWithoutBuiltinsImport() throws Throwable {
    // Remove test realm
    removeRealm("test-realm");

    // Set the realm, which doesn't have builtin clients/roles inside JSON
    testingClient.testing().exportImport().setProvider(SingleFileExportProviderFactory.PROVIDER_ID);
    URL url = ExportImportTest.class.getResource("/model/testrealm.json");
    String targetFilePath = new File(url.getFile()).getAbsolutePath();
    testingClient.testing().exportImport().setFile(targetFilePath);

    testingClient.testing().exportImport().setAction(ExportImportConfig.ACTION_IMPORT);

    testingClient.testing().exportImport().runImport();

    RealmResource testRealmRealm = adminClient.realm("test-realm");

    ExportImportUtil.assertDataImportedInRealm(adminClient, testingClient, testRealmRealm.toRepresentation());
}
 
Example #4
Source File: ComponentRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
public ComponentRepresentation get(String realm, String providerType, String name) {
    RealmResource realmResource = realmRepository.loadRealm(realm);

    List<ComponentRepresentation> realmComponents = realmResource.components().query();

    Optional<ComponentRepresentation> maybeComponent = realmComponents
            .stream()
            .filter(c -> Objects.equals(c.getName(), name))
            .filter(c -> Objects.equals(c.getProviderType(), providerType))
            .findFirst();

    if (maybeComponent.isPresent()) {
        return maybeComponent.get();
    }

    throw new KeycloakRepositoryException("Cannot find component by name '" + name + "' and subtype '" + providerType + "' in realm '" + realm + "' ");
}
 
Example #5
Source File: UsersTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void countUsersBySearchWithNoViewPermission() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RealmResource testRealmResource = setupTestEnvironmentWithPermissions(false);
    //search all
    assertThat(testRealmResource.users().count("user"), is(0));
    //search first name
    assertThat(testRealmResource.users().count("FirstName"), is(0));
    assertThat(testRealmResource.users().count("user2FirstName"), is(0));
    //search last name
    assertThat(testRealmResource.users().count("LastName"), is(0));
    assertThat(testRealmResource.users().count("user2LastName"), is(0));
    //search in email
    assertThat(testRealmResource.users().count("@example.com"), is(0));
    assertThat(testRealmResource.users().count("[email protected]"), is(0));
    //search for something not existing
    assertThat(testRealmResource.users().count("notExisting"), is(0));
    //search for empty string
    assertThat(testRealmResource.users().count(""), is(0));
    //search not specified (defaults to simply /count)
    assertThat(testRealmResource.users().count(null), is(0));
}
 
Example #6
Source File: OfflineTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void offlineTokenAllowedWithCompositeRole() throws Exception {
    RealmResource appRealm = adminClient.realm("test");
    UserResource testUser = findUserByUsernameId(appRealm, "test-user@localhost");
    RoleRepresentation offlineAccess = findRealmRoleByName(adminClient.realm("test"),
            Constants.OFFLINE_ACCESS_ROLE).toRepresentation();

    // Grant offline_access role indirectly through composite role
    appRealm.roles().create(RoleBuilder.create().name("composite").build());
    RoleResource roleResource = appRealm.roles().get("composite");
    roleResource.addComposites(Collections.singletonList(offlineAccess));

    testUser.roles().realmLevel().remove(Collections.singletonList(offlineAccess));
    testUser.roles().realmLevel().add(Collections.singletonList(roleResource.toRepresentation()));

    // Integration test
    offlineTokenDirectGrantFlow();

    // Revert changes
    testUser.roles().realmLevel().remove(Collections.singletonList(appRealm.roles().get("composite").toRepresentation()));
    appRealm.roles().get("composite").remove();
    testUser.roles().realmLevel().add(Collections.singletonList(offlineAccess));
    
}
 
Example #7
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void testIdentityProviderAuthenticator(RealmResource... realms) {
    log.info("testing identity provider authenticator");
    for (RealmResource realm : realms) {
        boolean success = false;
        for (AuthenticationFlowRepresentation flow : realm.flows().getFlows()) {
            if (flow.getAlias().equals(DefaultAuthenticationFlows.BROWSER_FLOW)) {
                for (AuthenticationExecutionExportRepresentation execution : flow.getAuthenticationExecutions()) {
                    if ("identity-provider-redirector".equals(execution.getAuthenticator())) {
                        assertEquals("Requirement should be ALTERNATIVE.", AuthenticationExecutionModel.Requirement.ALTERNATIVE.name(), execution.getRequirement());
                        assertTrue("Priority should be 25.", execution.getPriority() == 25);
                        success = true;
                    }
                }
            }
        }
        if (!success) {
            fail("BROWSER_FLOW should contain execution: 'identity-provider-redirector' authenticator.");
        }
    }
}
 
Example #8
Source File: AdminEventTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultMaxResults() {
    RealmResource realm = adminClient.realms().realm("test");
    AdminEventRepresentation event = new AdminEventRepresentation();
    event.setOperationType(OperationType.CREATE.toString());
    event.setAuthDetails(new AuthDetailsRepresentation());
    event.setRealmId(realm.toRepresentation().getId());

    for (int i = 0; i < 110; i++) {
        testingClient.testing("test").onAdminEvent(event, false);
    }

    assertThat(realm.getAdminEvents(null, null, null, null, null, null, null, null, null, null).size(), is(equalTo(100)));
    assertThat(realm.getAdminEvents(null, null, null, null, null, null, null, null, 0, 105).size(), is(equalTo(105)));
    assertThat(realm.getAdminEvents(null, null, null, null, null, null, null, null, 0, 1000).size(), is(greaterThanOrEqualTo(110)));
}
 
Example #9
Source File: RealmRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private Optional<RealmRepresentation> tryToLoadRealm(String realm) {
    Optional<RealmRepresentation> maybeRealm;

    try {
        RealmResource realmResource = loadRealm(realm);

        // check here if realm is present, otherwise this method throws an NotFoundException
        RealmRepresentation foundRealm = realmResource.toRepresentation();

        maybeRealm = Optional.of(foundRealm);
    } catch (javax.ws.rs.NotFoundException e) {
        maybeRealm = Optional.empty();
    }

    return maybeRealm;
}
 
Example #10
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void testExtractRealmKeysMigrationRealm(RealmResource migrationRealm) {
    log.info("testing extract realm keys");
    String expectedMigrationRealmKey = "MIIEpAIBAAKCAQEApt6gCllWkVTZ7fy/oRIx6Bxjt9x3eKKyKGFXvN4iaafrNqpYU9lcqPngWJ9DyXGqUf8RpjPaQWiLWLxjw3xGBqLk2E1/Frb9e/dy8rj//fHGq6bujN1iguzyFwxPGT5Asd7jflRI3qU04M8JE52PArqPhGL2Fn+FiSK5SWRIGm+hVL7Ck/E/tVxM25sFG1/UTQqvrROm4q76TmP8FsyZaTLVf7cCwW2QPIX0N5HTVb3QbBb5KIsk4kKmk/g7uUxS9r42tu533LISzRr5CTyWZAL2XFRuF2RrKdE8gwqkEubw6sDmB2mE0EoPdY1DUhBQgVP/5rwJrCtTsUBR2xdEYQIDAQABAoIBAFbbsNBSOlZBpYJUOmcb8nBQPrOYhXN8tGGCccn0klMOvcdhmcJjdPDbyCQ5Gm7DxJUTwNsTSHsdcNMKlJ9Pk5+msJnKlOl87KrXXbTsCQvlCrWUmb0nCzz9GvJWTOHl3oT3cND0DE4gDksqWR4luCgCdevCGzgQvrBoK6wBD+r578uEW3iw10hnJ0+wnGiw8IvPzE1a9xbY4HD8/QrYdaLxuLb/aC1PDuzrz0cOjnvPkrws5JrbUSnbFygJiOv1z4l2Q00uGIxlHtXdwQBnTZZjVi4vOec2BYSHffgwDYEZIglw1mnrV7y0N1nnPbtJK/cegIkXoBQHXm8Q99TrWMUCgYEA9au86qcwrXZZg5H4BpR5cpy0MSkcKDbA1aRL1cAyTCqJxsczlAtLhFADF+NhnlXj4y7gwDEYWrz064nF73I+ZGicvCiyOy+tCTugTyTGS+XR948ElDMS6PCUUXsotS3dKa0b3c9wd2mxeddTjq/ArfgEVZJ6fE1KtjLt9dtfA+8CgYEAreK3JsvjR5b/Xct28TghYUU7Qnasombb/shqqy8FOMjYUr5OUm/OjNIgoCqhOlE8oQDJ4dOZofNSa7tL+oM8Gmbal+E3fRzxnx/9/EC4QV6sVaPLTIyk7EPfKTcZuzH7+BNZtAziTxJw9d6YJQRbkpg92EZIEoR8iDj2Xs5xrK8CgYEAwMVWwwYX8zT3vn7ukTM2LRH7bsvkVUXJgJqgCwT6Mrv6SmkK9vL5+cPS+Y6pjdW1sRGauBSOGL1Grf/4ug/6F03jFt4UJM8fRyxreU7Q7sNSQ6AMpsGA6BnHODycz7ZCYa59PErG5FyiL4of/cm5Nolz1TXQOPNpWZiTEqVlZC8CgYA4YPbjVF4nuxSnU64H/hwMjsbtAM9uhI016cN0J3W4+J3zDhMU9X1x+Tts0wWdg/N1fGz4lIQOl3cUyRCUc/KL2OdtMS+tmDHbVyMho9ZaE5kq10W2Vy+uDz+O/HeSU12QDK4cC8Vgv+jyPy7zaZtLR6NduUPrBRvfiyCOkr8WrwKBgQCY0h4RCdNFhr0KKLLmJipAtV8wBCGcg1jY1KoWKQswbcykfBKwHbF6EooVqkRW0ITjWB7ZZCf8TnSUxe0NXCUAkVBrhzS4DScgtoSZYOOUaSHgOxpfwgnQ3oYotKi98Yg3IsaLs1j4RuPG5Sp1z6o+ELP1uvr8azyn9YlLa+523Q==";

    List<ComponentRepresentation> components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName());
    assertEquals(3, components.size());

    components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName(), "rsa");
    assertEquals(1, components.size());

    ComponentRepresentation component = testingClient.server(MIGRATION).fetch(RunHelpers.internalComponent(components.get(0).getId()));
    assertEquals(expectedMigrationRealmKey, component.getConfig().getFirst("privateKey"));

    components = migrationRealm.components().query(MIGRATION, KeyProvider.class.getName(), "hmac-generated");
    assertEquals(1, components.size());
}
 
Example #11
Source File: ImportComponentsIT.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private Optional<ComponentRepresentation> tryToGetComponent(String providerType, String name) {
    RealmResource realmResource = keycloakProvider.get()
            .realm(REALM_NAME);

    Optional<ComponentRepresentation> maybeComponent;

    List<ComponentRepresentation> existingComponents = realmResource.components()
            .query().stream()
            .filter(c -> c.getProviderType().equals(providerType))
            .filter(c -> c.getName().equals(name))
            .filter(c -> c.getSubType() == null)
            .collect(Collectors.toList());

    assertThat(existingComponents, hasSize(1));

    if (existingComponents.isEmpty()) {
        maybeComponent = Optional.empty();
    } else {
        maybeComponent = Optional.of(existingComponents.get(0));
    }

    return maybeComponent;
}
 
Example #12
Source File: ExportImportTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDirRealmExportImport() throws Throwable {
    testingClient.testing()
            .exportImport()
            .setProvider(DirExportProviderFactory.PROVIDER_ID);
    String targetDirPath = testingClient.testing().exportImport().getExportImportTestDirectory() + File.separator + "dirRealmExport";
    DirExportProvider.recursiveDeleteDir(new File(targetDirPath));
    testingClient.testing().exportImport().setDir(targetDirPath);
    testingClient.testing().exportImport().setUsersPerFile(5);

    testRealmExportImport();

    RealmResource testRealmRealm = adminClient.realm("test-realm");
    ExportImportUtil.assertDataImportedInRealm(adminClient, testingClient, testRealmRealm.toRepresentation());

    // There should be 4 files in target directory (1 realm, 12 users, 5 users per file)
    // (+ additional user service-account-test-app-authz that should not be there ???)
    File[] files = new File(targetDirPath).listFiles();
    assertEquals(4, files.length);
}
 
Example #13
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void testAccountClient(RealmResource realm) {
    ClientRepresentation accountClient = realm.clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);

    ClientResource accountResource = realm.clients().get(accountClient.getId());
    RoleRepresentation viewAppRole = accountResource.roles().get(AccountRoles.VIEW_APPLICATIONS).toRepresentation();
    assertNotNull(viewAppRole);
    RoleRepresentation viewConsentRole = accountResource.roles().get(AccountRoles.VIEW_CONSENT).toRepresentation();
    assertNotNull(viewConsentRole);
    RoleResource manageConsentResource = accountResource.roles().get(AccountRoles.MANAGE_CONSENT);
    RoleRepresentation manageConsentRole = manageConsentResource.toRepresentation();
    assertNotNull(manageConsentRole);
    assertTrue(manageConsentRole.isComposite());
    Set<RoleRepresentation> composites = manageConsentResource.getRoleComposites();
    assertEquals(1, composites.size());
    assertEquals(viewConsentRole.getId(), composites.iterator().next().getId());
}
 
Example #14
Source File: GroupTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotAllowSameGroupNameAtTopLevel() throws Exception {
    RealmResource realm = adminClient.realms().realm("test");

    // creating "/test-group"
    GroupRepresentation topGroup = new GroupRepresentation();
    topGroup.setName("test-group");
    topGroup = createGroup(realm, topGroup);
    getCleanup().addGroupId(topGroup.getId());

    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("test-group");
    try (Response response = realm.groups().add(group2)) {
        assertEquals(Status.CONFLICT.getStatusCode(), response.getStatus());
    }
}
 
Example #15
Source File: GroupPathPolicyTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllowParentAndChildren() {
    AuthzClient authzClient = getAuthzClient();
    PermissionRequest request = new PermissionRequest("Resource A");
    String ticket = authzClient.protection().permission().create(request).getTicket();
    AuthorizationResponse response = authzClient.authorization("marta", "password").authorize(new AuthorizationRequest(ticket));

    assertNotNull(response.getToken());

    RealmResource realm = getRealm();
    GroupRepresentation group = getGroup("/Group A/Group B/Group C");
    UserRepresentation user = realm.users().search("kolo").get(0);

    realm.users().get(user.getId()).joinGroup(group.getId());

    ticket = authzClient.protection().permission().create(request).getTicket();
    response = authzClient.authorization("kolo", "password").authorize(new AuthorizationRequest(ticket));

    assertNotNull(response.getToken());
}
 
Example #16
Source File: AccountPageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalizedReferrerLinkContent() {
    ProfileAssume.assumeCommunity();
    
    RealmResource testRealm = testRealm();
    List<ClientRepresentation> foundClients = testRealm.clients().findByClientId("var-named-test-app");
    if (foundClients.isEmpty()) {
        Assert.fail("Unable to find var-named-test-app");
    }
    ClientRepresentation namedClient = foundClients.get(0);

    driver.navigate().to(accountUpdateProfilePage.getPath() + "?referrer=" + namedClient.getClientId());
    loginPage.login("test-user@localhost", "password");
    Assert.assertTrue(accountUpdateProfilePage.isCurrent());

    accountUpdateProfilePage.openLanguage("Deutsch");
    Assert.assertEquals("Deutsch", accountUpdateProfilePage.getLanguageDropdownText());

    // When a client has a name provided as a variable, the name should be resolved using a localized bundle and available to the back link
    Assert.assertEquals("Zur\u00FCck zu Test App Named - Clientkonto", accountUpdateProfilePage.getBackToApplicationLinkText());
    Assert.assertEquals(namedClient.getBaseUrl(), accountUpdateProfilePage.getBackToApplicationLinkHref());
}
 
Example #17
Source File: DefaultHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyRealmFrontendUrl() throws URISyntaxException {
    expectedBackendUrl = AUTH_SERVER_ROOT;
    oauth.clientId("direct-grant");

    RealmResource realmResource = realmsResouce().realm("frontendUrl");
    RealmRepresentation rep = realmResource.toRepresentation();

    try {
        rep.getAttributes().put("frontendUrl", "");
        realmResource.update(rep);

        assertWellKnown("frontendUrl", AUTH_SERVER_ROOT);
    } finally {
        rep.getAttributes().put("frontendUrl", realmFrontEndUrl);
        realmResource.update(rep);
    }
}
 
Example #18
Source File: KcAdmCreateTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateIDPWithoutSyncMode() throws IOException {
    final String realm = "test";
    final RealmResource realmResource = adminClient.realm(realm);

    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        loginAsUser(configFile.getFile(), serverUrl, realm, "user1", "userpass");

        final File idpJson = new File("target/test-classes/cli/idp-keycloak-without-sync-mode.json");
        KcAdmExec exe = execute("create identity-provider/instances/ -r " + realm + " -f " + idpJson.getAbsolutePath() + " --config " + configFile.getFile());
        assertExitCodeAndStdErrSize(exe, 0, 1);
    }

    // If the sync mode is not present on creating the idp, it will never be added automatically. However, the model will always assume "LEGACY", so no errors should occur.
    Assert.assertNull(realmResource.identityProviders().get("idpAlias").toRepresentation().getConfig().get(IdentityProviderModel.SYNC_MODE));
}
 
Example #19
Source File: OIDCPairwiseClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateToPairwiseThroughAdminRESTSuccess() throws Exception {
    OIDCClientRepresentation response = create();
    Assert.assertEquals("public", response.getSubjectType());
    Assert.assertNull(response.getSectorIdentifierUri());

    // Push redirect uris to the sector identifier URI
    List<String> sectorRedirects = new ArrayList<>();
    sectorRedirects.addAll(response.getRedirectUris());
    TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
    oidcClientEndpointsResource.setSectorIdentifierRedirectUris(sectorRedirects);

    String sectorIdentifierUri = TestApplicationResourceUrls.pairwiseSectorIdentifierUri();

    // Add protocolMapper through admin REST endpoint
    String clientId = response.getClientId();
    ProtocolMapperRepresentation pairwiseProtMapper = SHA256PairwiseSubMapper.createPairwiseMapper(sectorIdentifierUri, null);
    RealmResource realmResource = realmsResouce().realm("test");
    ClientManager.realm(realmResource).clientId(clientId).addProtocolMapper(pairwiseProtMapper);

    reg.auth(Auth.token(response));
    OIDCClientRepresentation rep = reg.oidc().get(response.getClientId());
    Assert.assertEquals("pairwise", rep.getSubjectType());
    Assert.assertEquals(sectorIdentifierUri, rep.getSectorIdentifierUri());

}
 
Example #20
Source File: AccountBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void addIdentityProviderToProviderRealm() {
    log.debug("adding identity provider to realm " + bc.consumerRealmName());

    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    realm.identityProviders().create(bc.setUpIdentityProvider()).close();
    realm.identityProviders().get(bc.getIDPAlias());
}
 
Example #21
Source File: ExportImportUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Set<RoleRepresentation> allRoles(RealmResource realmRsc, UserRepresentation user) {
    UserResource userRsc = realmRsc.users().get(user.getId());
    Set<RoleRepresentation> roles = new HashSet<>();

    List<RoleRepresentation> realmRoles = userRsc.roles().getAll().getRealmMappings();
    if (realmRoles != null) roles.addAll(realmRoles);

    roles.addAll(allClientRolesForUser(realmRsc, user));

    return roles;
}
 
Example #22
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void testDockerAuthenticationFlow(RealmResource... realms) {
    for (RealmResource realm : realms) {
        AuthenticationFlowRepresentation flow = null;
        for (AuthenticationFlowRepresentation f : realm.flows().getFlows()) {
            if (DefaultAuthenticationFlows.DOCKER_AUTH.equals(f.getAlias())) {
                flow = f;
            }
        }
        assertNotNull(flow);
    }
}
 
Example #23
Source File: Creator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Creator.Flow create(RealmResource realmResource, AuthenticationFlowRepresentation rep) {
    final AuthenticationManagementResource authMgmgRes = realmResource.flows();
    try (Response response = authMgmgRes.createFlow(rep)) {
        String createdId = getCreatedId(response);
        LOG.debugf("Created flow ID %s", createdId);
        return new Flow(createdId, rep.getAlias(), authMgmgRes, () -> authMgmgRes.deleteFlow(createdId));
    }
}
 
Example #24
Source File: Creator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Creator<ComponentResource> create(RealmResource realmResource, ComponentRepresentation rep) {
    final ComponentsResource components = realmResource.components();
    try (Response response = components.add(rep)) {
        String createdId = getCreatedId(response);
        final ComponentResource r = components.component(createdId);
        LOG.debugf("Created component ID %s", createdId);
        return new Creator(createdId, r, r::remove);
    }
}
 
Example #25
Source File: Creator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Creator<UserResource> create(RealmResource realmResource, UserRepresentation rep) {
    final UsersResource users = realmResource.users();
    try (Response response = users.create(rep)) {
        String createdId = getCreatedId(response);
        final UserResource r = users.get(createdId);
        LOG.debugf("Created user ID %s", createdId);
        return new Creator(createdId, r, r::remove);
    }
}
 
Example #26
Source File: Creator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Creator<ClientResource> create(RealmResource realmResource, ClientRepresentation rep) {
    final ClientsResource clients = realmResource.clients();
    try (Response response = clients.create(rep)) {
        String createdId = getCreatedId(response);
        final ClientResource r = clients.get(createdId);
        LOG.debugf("Created client ID %s", createdId);
        return new Creator(createdId, r, r::remove);
    }
}
 
Example #27
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.OIDCBrokerUserPropertyTest
 */
@Test
public void loginFetchingUserFromUserEndpointWithClaimMapper() {
    RealmResource realm = realmsResouce().realm(bc.providerRealmName());
    ClientsResource clients = realm.clients();
    ClientRepresentation brokerApp = clients.findByClientId("brokerapp").get(0);
    IdentityProviderResource identityProviderResource = getIdentityProviderResource();

    clients.get(brokerApp.getId()).getProtocolMappers().createMapper(createHardcodedClaim("hard-coded", "hard-coded", "hard-coded", "String", true, true)).close();

    IdentityProviderMapperRepresentation hardCodedSessionNoteMapper = new IdentityProviderMapperRepresentation();

    hardCodedSessionNoteMapper.setName("hard-coded");
    hardCodedSessionNoteMapper.setIdentityProviderAlias(bc.getIDPAlias());
    hardCodedSessionNoteMapper.setIdentityProviderMapper(UserAttributeMapper.PROVIDER_ID);
    hardCodedSessionNoteMapper.setConfig(ImmutableMap.<String, String>builder()
            .put(IdentityProviderMapperModel.SYNC_MODE, IdentityProviderMapperSyncMode.INHERIT.toString())
            .put(UserAttributeMapper.USER_ATTRIBUTE, "hard-coded")
            .put(UserAttributeMapper.CLAIM, "hard-coded")
            .build());

    identityProviderResource.addMapper(hardCodedSessionNoteMapper).close();

    loginFetchingUserFromUserEndpoint();

    UserRepresentation user = getFederatedIdentity();

    Assert.assertEquals(1, user.getAttributes().size());
    Assert.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0));
}
 
Example #28
Source File: ConcurrencyTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void run(int threadIndex, Keycloak keycloak, RealmResource realm) throws Throwable {
    String name = "cr-" + uniqueCounter.getAndIncrement();
    RoleRepresentation r = new RoleRepresentation(name, null, false);

    final RolesResource roles = realm.clients().get(clientId).roles();
    roles.create(r);
    assertNotNull(roles.get(name).toRepresentation());
}
 
Example #29
Source File: ClientAttributeUpdater.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@ClientAttributeUpdater} for the given client. The client must exist.
 * @param adminClient
 * @param realm
 * @param clientId
 * @return
 */
public static ClientAttributeUpdater forClient(Keycloak adminClient, String realm, String clientId) {
    RealmResource realmRes = adminClient.realm(realm);
    ClientsResource clients = realmRes.clients();
    List<ClientRepresentation> foundClients = clients.findByClientId(clientId);
    assertThat(foundClients, hasSize(1));
    ClientResource clientRes = clients.get(foundClients.get(0).getId());
    
    return new ClientAttributeUpdater(clientRes, realmRes);
}
 
Example #30
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: PostBrokerFlowTest#testBrokerReauthentication_oidcBrokerWithOTPRequired
 */
@Test
public void testReauthenticationOIDCBrokerWithOTPRequired() throws Exception {
    KcSamlBrokerConfiguration samlBrokerConfig = KcSamlBrokerConfiguration.INSTANCE;
    ClientRepresentation samlClient = samlBrokerConfig.createProviderClients().get(0);
    IdentityProviderRepresentation samlBroker = samlBrokerConfig.setUpIdentityProvider();
    RealmResource consumerRealm = adminClient.realm(bc.consumerRealmName());

    try {
        updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
        adminClient.realm(bc.providerRealmName()).clients().create(samlClient);
        consumerRealm.identityProviders().create(samlBroker);

        driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
        logInWithBroker(samlBrokerConfig);
        logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

        testingClient.server(bc.consumerRealmName()).run(configurePostBrokerLoginWithOTP(bc.getIDPAlias()));
        logInWithBroker(bc);

        waitForPage(driver, "account already exists", false);
        idpConfirmLinkPage.assertCurrent();
        idpConfirmLinkPage.clickLinkAccount();
        logoutFromRealm(getProviderRoot(), bc.providerRealmName());

        driver.navigate().back();
        logInWithBroker(samlBrokerConfig);

        totpPage.assertCurrent();
        String totpSecret = totpPage.getTotpSecret();
        totpPage.configure(totp.generateTOTP(totpSecret));
        logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

        assertNumFederatedIdentities(consumerRealm.users().search(samlBrokerConfig.getUserLogin()).get(0).getId(), 2);
    } finally {
        updateExecutions(AbstractBrokerTest::setUpMissingUpdateProfileOnFirstLogin);
        removeUserByUsername(consumerRealm, "consumer");
    }
}