org.keycloak.admin.client.Keycloak Java Examples

The following examples show how to use org.keycloak.admin.client.Keycloak. 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: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testRealmWithComposites() throws Exception {
    testingClient.server().run(FineGrainAdminUnitTest::setup5152);

    try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(),
            TEST, "realm-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) {
        RoleRepresentation composite = new RoleRepresentation();
        composite.setName("composite");
        composite.setComposite(true);
        realmClient.realm(TEST).roles().create(composite);
        composite = adminClient.realm(TEST).roles().get("composite").toRepresentation();

        ClientRepresentation client = adminClient.realm(TEST).clients().findByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).get(0);
        RoleRepresentation viewUsers = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation();

        List<RoleRepresentation> composites = new LinkedList<>();
        composites.add(viewUsers);
        realmClient.realm(TEST).rolesById().addComposites(composite.getId(), composites);
    }
}
 
Example #2
Source File: DefaultHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void forceBackendUrlToFrontendUrl() throws Exception {
    expectedBackendUrl = AUTH_SERVER_ROOT;

    oauth.clientId("direct-grant");

    try (Keycloak testAdminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), AuthServerTestEnricher.getAuthServerContextRoot())) {
        assertWellKnown("test", expectedBackendUrl);

        configureDefault(globalFrontEndUrl, true, null);

        expectedBackendUrl = globalFrontEndUrl;

        assertWellKnown("test", globalFrontEndUrl);
        assertTokenIssuer("test", globalFrontEndUrl);
        assertInitialAccessTokenFromMasterRealm(testAdminClient,"test", globalFrontEndUrl);

        expectedBackendUrl = realmFrontEndUrl;

        assertWellKnown("frontendUrl", realmFrontEndUrl);
        assertTokenIssuer("frontendUrl", realmFrontEndUrl);
        assertInitialAccessTokenFromMasterRealm(testAdminClient,"frontendUrl", realmFrontEndUrl);
    } finally {
        reset();
    }
}
 
Example #3
Source File: PermissionsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void invoke(InvocationWithResponse invocation, Keycloak client, boolean expectSuccess) {
    int statusCode;
    try {
        AtomicReference<Response> responseReference = new AtomicReference<>();
        invocation.invoke(client.realm(REALM_NAME), responseReference);
        Response response = responseReference.get();
        if (response != null) {
            statusCode = response.getStatus();
        } else {
            // OK (we don't care about the exact status code
            statusCode = 200;
        }
    } catch (ClientErrorException e) {
        statusCode = e.getResponse().getStatus();
    }

    if (expectSuccess) {
        if (!(statusCode == 200 || statusCode == 201 || statusCode == 204 || statusCode == 404 || statusCode == 409 || statusCode == 400)) {
            fail("Expected permitted, but was " + statusCode);
        }
    } else {
        if (statusCode != 403) {
            fail("Expected 403, but was " + statusCode);
        }
    }
}
 
Example #4
Source File: DefaultHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);

    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, token.getIssuer());

    ClientRegistration clientReg = ClientRegistration.create().url(AUTH_SERVER_ROOT, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));

    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);

    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/realms/" + realm, registrationToken.getIssuer());
}
 
Example #5
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertInitialAccessTokenFromMasterRealm(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws JWSInputException, ClientRegistrationException {
    ClientInitialAccessCreatePresentation rep = new ClientInitialAccessCreatePresentation();
    rep.setCount(1);
    rep.setExpiration(10000);

    ClientInitialAccessPresentation initialAccess = testAdminClient.realm(realm).clientInitialAccess().create(rep);
    JsonWebToken token = new JWSInput(initialAccess.getToken()).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, token.getIssuer());

    ClientRegistration clientReg = ClientRegistration.create().url(authServerUrl, realm).build();
    clientReg.auth(Auth.token(initialAccess.getToken()));

    ClientRepresentation client = new ClientRepresentation();
    client.setEnabled(true);
    ClientRepresentation response = clientReg.create(client);

    String registrationAccessToken = response.getRegistrationAccessToken();
    JsonWebToken registrationToken = new JWSInput(registrationAccessToken).readJsonContent(JsonWebToken.class);
    assertEquals(expectedBaseUrl + "/auth/realms/" + realm, registrationToken.getIssuer());
}
 
Example #6
Source File: AuthServerTestEnricher.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void removeTestRealms(TestContext testContext, Keycloak adminClient) {
    List<RealmRepresentation> testRealmReps = testContext.getTestRealmReps();
    if (testRealmReps != null && !testRealmReps.isEmpty()) {
        log.info("removing test realms after test class");
        StringBuilder realms = new StringBuilder();
        for (RealmRepresentation testRealm : testRealmReps) {
            try {
                adminClient.realms().realm(testRealm.getRealm()).remove();
                realms.append(testRealm.getRealm()).append(", ");
            } catch (NotFoundException e) {
                // Ignore
            }
        }
        log.info("removed realms: " + realms);
    }
}
 
Example #7
Source File: ConcurrencyTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void run(int threadIndex, Keycloak keycloak, RealmResource realm) throws Throwable {
    String name = "c-" + clientIndex.getAndIncrement();
    ClientRepresentation c = new ClientRepresentation();
    c.setClientId(name);
    Response response = realm.clients().create(c);
    String id = ApiUtil.getCreatedId(response);
    response.close();

    c = realm.clients().get(id).toRepresentation();
    assertNotNull(c);
    assertTrue("Client " + name + " not found in client list",
      realm.clients().findAll().stream()
        .map(ClientRepresentation::getClientId)
        .filter(Objects::nonNull)
        .anyMatch(name::equals));
}
 
Example #8
Source File: BruteForceCrossDCTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testBruteForceConcurrentUpdate() throws Exception {
    //Thread.sleep(120000);

    // Enable 1st node on each DC only
    enableDcOnLoadBalancer(DC.FIRST);
    enableDcOnLoadBalancer(DC.SECOND);

    // Clear all
    adminClient.realms().realm(REALM_NAME).attackDetection().clearAllBruteForce();
    assertStatistics("After brute force cleared", 0, 0, 0);

    // create the entry manually in DC0
    addUserLoginFailure(getTestingClientForStartedNodeInDc(0));
    assertStatistics("After create entry1", 1, 0, 1);

    AbstractConcurrencyTest.KeycloakRunnable runnable = (int threadIndex, Keycloak keycloak, RealmResource realm1) -> {
        createBruteForceFailures(1, "login-test-1");
    };

    AbstractConcurrencyTest.run(2, 20, this, runnable);

    Retry.execute(() -> {
        int dc0user1 = (Integer) getAdminClientForStartedNodeInDc(0).realm(REALM_NAME).attackDetection().bruteForceUserStatus("login-test-1").get("numFailures");
        int dc1user1 = (Integer) getAdminClientForStartedNodeInDc(1).realm(REALM_NAME).attackDetection().bruteForceUserStatus("login-test-1").get("numFailures");

        log.infof("After concurrent update entry1: dc0User1=%d, dc1user1=%d", dc0user1, dc1user1);

        // TODO: The number of failures should be ideally exactly 21 in both DCs. Once we improve cross-dc, then improve this test and rather check for "Assert.assertEquals(dc0user1, 21)" and "Assert.assertEquals(dc1user1, 21)"
        Assert.assertThat(dc0user1, Matchers.greaterThan(11));
        Assert.assertThat(dc1user1, Matchers.greaterThan(11));
    }, 50, 50);
}
 
Example #9
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void adminCanExportMasterRealm() throws IOException {
    //TODO activate Full scope Mapping in admin-cli programmatically
    Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
    String token = keycloak.tokenManager().getAccessTokenString();
    RealmRepresentation realmRepresentation = exportRealm(token, "master");
    Assert.assertNotNull(realmRepresentation);
    Assert.assertEquals("master", realmRepresentation.getRealm());
    Assert.assertTrue(realmRepresentation.getUsers().stream().anyMatch(ur -> ur.getUsername().equals("admin")));
    Assert.assertTrue(realmRepresentation.getClients().size() > 0);
}
 
Example #10
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void initRealmAndUsers() throws IOException {
    Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
    clientBeforeChanges = keycloak.realms().realm("master").clients().findByClientId(CLIENT).get(0);
    createTestUser("admin", "admin", "master", TEST_USER, "password", "user");
    //just making sure realm is not already present
    String token = keycloak.tokenManager().getAccessTokenString();
    RealmRepresentation nullRealm = null;
    try {
        nullRealm = exportRealm(token, TEST_REALM_NAME);
    } catch (HttpResponseException e) {
        Assert.assertEquals(404, e.getStatusCode());
    }
    Assert.assertNull(nullRealm);
    //end just making sure realm is not already present
}
 
Example #11
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 #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 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 #13
Source File: DatasetLoader.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public DatasetLoader(Dataset dataset, boolean delete) {
    Validate.notNull(dataset);
    this.dataset = dataset;
    this.delete = delete;
    logger().info(String.format("Opening %s admin clients.", TestConfig.numOfWorkers));
    for (int i = 0; i < TestConfig.numOfWorkers; i++) {
        adminClients.add(Keycloak.getInstance(
                TestConfig.serverUrisIterator.next(),
                TestConfig.authRealm,
                TestConfig.authUser,
                TestConfig.authPassword,
                TestConfig.authClient));
    }
}
 
Example #14
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void fixedHostnameAlwaysHttpsHttpsPort() throws Exception {
    // Make sure request are always sent with http
    authServerUrl = "http://localhost:8180/auth";
    oauth.baseUrl(authServerUrl);

    oauth.clientId("direct-grant");

    try (Keycloak testAdminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), "http://localhost:8180")) {
        assertWellKnown("test", "http://localhost:8180");
        assertSamlIdPDescriptor("test", "http://localhost:8180");

        configureFixed("keycloak.127.0.0.1.nip.io", -1, 443, true);

        assertWellKnown("test", "https://keycloak.127.0.0.1.nip.io");
        assertSamlIdPDescriptor("test", "https://keycloak.127.0.0.1.nip.io");
        assertWellKnown("hostname", "https://custom-domain.127.0.0.1.nip.io");
        assertSamlIdPDescriptor("hostname", "https://custom-domain.127.0.0.1.nip.io");

        assertTokenIssuer("test", "https://keycloak.127.0.0.1.nip.io");
        assertTokenIssuer("hostname", "https://custom-domain.127.0.0.1.nip.io");

        assertInitialAccessTokenFromMasterRealm(testAdminClient, "test", "https://keycloak.127.0.0.1.nip.io");
        assertSamlLogin(testAdminClient, "test", "https://keycloak.127.0.0.1.nip.io");
        assertInitialAccessTokenFromMasterRealm(testAdminClient, "hostname", "https://custom-domain.127.0.0.1.nip.io");
        assertSamlLogin(testAdminClient, "hostname", "https://custom-domain.127.0.0.1.nip.io");
    } finally {
        reset();
    }
}
 
Example #15
Source File: AbstractClusterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void closeClients() {
    backendAdminClients.values().forEach(Keycloak::close);
    backendAdminClients.clear();

    backendTestingClients.values().forEach(KeycloakTestingClient::close);
    backendTestingClients.clear();

}
 
Example #16
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 = "r-" + uniqueCounter.getAndIncrement();
    RoleRepresentation r = new RoleRepresentation(name, null, false);

    final RolesResource roles = realm.roles();
    roles.create(r);
    assertNotNull(roles.get(name).toRepresentation());
}
 
Example #17
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 #18
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void nonAdminCantExportMaster() throws IOException {
    Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", TEST_USER, "password", CLIENT);
    String token = keycloak.tokenManager().getAccessTokenString();
    expectedEx.expect(HttpResponseException.class);
    expectedEx.expect(hasProperty("statusCode", is(403)));
    exportRealm(token, "master");
}
 
Example #19
Source File: AbstractCrossDCTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Keycloak getAdminClientForStartedNodeInDc(int dcIndex) {
    ContainerInfo firstStartedNode = this.suiteContext.getDcAuthServerBackendsInfo().get(dcIndex).stream()
            .filter(ContainerInfo::isStarted)
            .findFirst().get();

    return getAdminClientFor(firstStartedNode);
}
 
Example #20
Source File: RealmRepository.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public void create(RealmRepresentation realmToCreate) {
    Keycloak keycloak = keycloakProvider.get();
    RealmsResource realmsResource = keycloak.realms();

    try {
        realmsResource.create(realmToCreate);
    } catch (WebApplicationException error) {
        String errorMessage = ResponseUtil.getErrorMessage(error);
        throw new KeycloakRepositoryException(
                "Cannot create realm '" + realmToCreate.getRealm() + "': " + errorMessage,
                error
        );
    }
}
 
Example #21
Source File: KeycloakProvider.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public Keycloak get() {
    if (keycloak == null || isClosed) {
        keycloak = createKeycloak(properties);
        isClosed = false;
    }

    return keycloak;
}
 
Example #22
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 #23
Source File: ImpersonationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Cookie testSuccessfulImpersonation(String admin, String adminRealm) {
    ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder();
    resteasyClientBuilder.connectionPoolSize(10);
    resteasyClientBuilder.httpEngine(AdminClientUtil.getCustomClientHttpEngine(resteasyClientBuilder, 10));
    ResteasyClient resteasyClient = resteasyClientBuilder.build();

    // Login adminClient
    try (Keycloak client = login(admin, adminRealm, resteasyClient)) {
        // Impersonate
        return impersonate(client, admin, adminRealm);
    }
}
 
Example #24
Source File: ClientRoleMappings.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void update(Keycloak adminClient) {
    getRoleMapper()
            .roleMappingResource(adminClient)
            .clientLevel(getClient().getId())
            .add(getRepresentation());
}
 
Example #25
Source File: AuthServerTestEnricher.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void afterClass(@Observes(precedence = 1) AfterClass event) throws Exception {
    //check if a test accidentally left the auth-server not running
    ContainerController controller = containerConroller.get();
    if (!controller.isStarted(suiteContext.getAuthServerInfo().getQualifier())) {
        log.warn("Auth server wasn't running. Starting " + suiteContext.getAuthServerInfo().getQualifier());
        controller.start(suiteContext.getAuthServerInfo().getQualifier());
    }

    TestContext testContext = testContextProducer.get();

    Keycloak adminClient = testContext.getAdminClient();
    KeycloakTestingClient testingClient = testContext.getTestingClient();

    removeTestRealms(testContext, adminClient);

    if (!isAuthServerRemote() && event.getTestClass().isAnnotationPresent(EnableVault.class)) {
        VaultUtils.disableVault(suiteContext, event.getTestClass().getAnnotation(EnableVault.class).providerId());
        restartAuthServer();
        testContext.reconnectAdminClient();
    }

    if (adminClient != null) {
        adminClient.close();
    }

    if (testingClient != null) {
        testingClient.close();
    }
}
 
Example #26
Source File: Creatable.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public default String getIdAndReadIfNull(Keycloak adminClient) {
    if (getId() == null) {
        logger().debug("id of entity " + this + " was null, reading from server");
        readAndSetId(adminClient);
    }
    return getId();
}
 
Example #27
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 #28
Source File: TokenSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignature(String sigAlgName, String token, Keycloak adminClient) throws Exception {
    PublicKey publicKey = getRealmPublicKey(TEST_REALM_NAME, sigAlgName, adminClient);
    JWSInput jws = new JWSInput(token);
    Signature verifier = getSignature(sigAlgName);
    verifier.initVerify(publicKey);
    verifier.update(jws.getEncodedSignatureInput().getBytes("UTF-8"));
    return verifier.verify(jws.getSignature());
}
 
Example #29
Source File: Resource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Response create(Keycloak adminClient) {
    Validate.notNull(getResourceServer());
    Validate.notNull(getResourceServer().getClient());
    Validate.notNull(getResourceServer().getClient().getRepresentation().getBaseUrl());
    return resourcesResource(adminClient).create(getRepresentation());
}
 
Example #30
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);
}