Java源码示例:org.keycloak.representations.idm.ClientRepresentation

示例1
@Test
public void create() throws ClientRegistrationException, InterruptedException {
    ClientInitialAccessPresentation response = resource.create(new ClientInitialAccessCreatePresentation());

    reg.auth(Auth.token(response));

    ClientRepresentation rep = new ClientRepresentation();

    setTimeOffset(10);

    ClientRepresentation created = reg.create(rep);
    Assert.assertNotNull(created);

    try {
        reg.create(rep);
        Assert.fail("Expected exception");
    } catch (ClientRegistrationException e) {
        assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode());
    }
}
 
示例2
@Test
public void countUsersNotServiceAccount() {
    createUsers();

    Integer count = realm.users().count();
    assertEquals(9, count.intValue());

    ClientRepresentation client = new ClientRepresentation();

    client.setClientId("test-client");
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setServiceAccountsEnabled(true);
    client.setEnabled(true);
    client.setRedirectUris(Arrays.asList("http://url"));

    getAdminClient().realm(REALM_NAME).clients().create(client);

    // KEYCLOAK-5660, should not consider service accounts
    assertEquals(9, realm.users().count().intValue());
}
 
示例3
@Test
public void withServiceAccount() throws ClientRegistrationException {
    authManageClients();
    ClientRepresentation clientRep = buildClient();
    clientRep.setServiceAccountsEnabled(true);

    ClientRepresentation rep = registerClient(clientRep);

    UserRepresentation serviceAccountUser = adminClient.realm("test").clients().get(rep.getId()).getServiceAccountUser();

    assertNotNull(serviceAccountUser);

    deleteClient(rep);

    try {
        adminClient.realm("test").users().get(serviceAccountUser.getId()).toRepresentation();
        fail("Expected NotFoundException");
    } catch (NotFoundException e) {
    }
}
 
示例4
private void assertFail(ClientRegOp operation, ClientRepresentation client, int expectedStatusCode, String expectedErrorContains) {
    try {
        switch (operation) {
            case CREATE: reg.create(client);
                break;
            case UPDATE: reg.update(client);
                break;
            case DELETE: reg.delete(client);
                break;
        }

        Assert.fail("Not expected to successfuly run operation " + operation.toString() + " on client");
    } catch (ClientRegistrationException expected) {
        HttpErrorException httpEx = (HttpErrorException) expected.getCause();
        Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode());
        if (expectedErrorContains != null) {
            assertTrue("Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse(), httpEx.getErrorResponse().contains(expectedErrorContains));
        }
    }
}
 
示例5
private static void readClients(RealmRepresentation r, JsonParser p) throws IOException {
    JsonToken t = p.nextToken();
    if (t != JsonToken.START_ARRAY) {
        throw new RuntimeException("Error reading field 'clients'. Expected array of clients [" + t + "]");
    }

    t = p.nextToken();
    while (t == JsonToken.START_OBJECT) {
        ClientRepresentation u = p.readValueAs(ClientRepresentation.class);
        enqueueCreateClient(r, u);
        t = p.nextToken();
        currentClient += 1;

        // every some users check to see pending errors
        if (currentClient % ERROR_CHECK_INTERVAL == 0) {
            checkPendingErrors(u.getClientId());
        }
    }
}
 
示例6
@Test
public void oauthGrantExpiredAuthSession() throws Exception {
    oauth.clientId(THIRD_PARTY_APP);
    oauth.doLoginGrant("[email protected]", "password");

    grantPage.assertCurrent();

    // Expire cookies
    driver.manage().deleteAllCookies();

    grantPage.accept();

    // Assert link "back to application" present
    errorPage.assertCurrent();
    String backToAppLink = errorPage.getBackToApplicationLink();
    ClientRepresentation thirdParty = findClientByClientId(adminClient.realm(REALM_NAME), THIRD_PARTY_APP).toRepresentation();
    Assert.assertEquals(backToAppLink, thirdParty.getBaseUrl());
}
 
示例7
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    super.configureTestRealm(testRealm);
    RealmRepresentation realmRepresentation = testRealm;

    realmRepresentation.setUserManagedAccessAllowed(true);

    testRealm.getUsers().add(createUser("alice", "password"));
    testRealm.getUsers().add(createUser("jdoe", "password"));
    testRealm.getUsers().add(createUser("bob", "password"));

    ClientRepresentation client = ClientBuilder.create()
            .clientId("my-resource-server")
            .authorizationServicesEnabled(true)
            .serviceAccountsEnabled(true)
            .secret("secret")
            .name("My Resource Server")
            .baseUrl("http://resourceserver.com")
            .directAccessGrants().build();

    testRealm.getClients().add(client);
}
 
示例8
@Override
public List<ClientRepresentation> createProviderClients() {
    List<ClientRepresentation> clientRepresentationList = super.createProviderClients();

    for (ClientRepresentation client : clientRepresentationList) {
        client.setClientAuthenticatorType("client-secret");
        client.setSurrogateAuthRequired(false);

        Map<String, String> attributes = client.getAttributes();
        if (attributes == null) {
            attributes = new HashMap<>();
            client.setAttributes(attributes);
        }

        attributes.put("saml.assertion.signature", "false");
        attributes.put("saml.server.signature", "true");
        attributes.put("saml.client.signature", "true");
        attributes.put("saml.signature.algorithm", "RSA_SHA256");
        attributes.put("saml.signing.private.key", IDP_SAML_SIGN_KEY);
        attributes.put("saml.signing.certificate", IDP_SAML_SIGN_CERT);
    }

    return clientRepresentationList;
}
 
示例9
@Test
public void testMasterRealmWithComposites() throws Exception {
    RoleRepresentation composite = new RoleRepresentation();
    composite.setName("composite");
    composite.setComposite(true);
    adminClient.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 createClient = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation();
    RoleRepresentation queryRealms = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.QUERY_REALMS).toRepresentation();
    List<RoleRepresentation> composites = new LinkedList<>();
    composites.add(createClient);
    composites.add(queryRealms);
    adminClient.realm(TEST).rolesById().addComposites(composite.getId(), composites);
}
 
示例10
@Test
public void testRedirectLoginNoNameIdPolicyForcePostBinding() throws Exception {
    ClientsResource clients = adminClient.realm(REALM_NAME).clients();
    List<ClientRepresentation> foundClients = clients.findByClientId(SAML_CLIENT_ID_SALES_POST);
    assertThat(foundClients, hasSize(1));
    ClientResource clientRes = clients.get(foundClients.get(0).getId());
    ClientRepresentation client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "true");
    clientRes.update(client);

    testLoginWithNameIdPolicy(Binding.REDIRECT, Binding.POST, null, is("bburke"));

    // Revert
    client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "false");
    clientRes.update(client);
}
 
示例11
@Test
public void createClientRole() throws Throwable {
    ClientRepresentation c = new ClientRepresentation();
    c.setClientId("client");
    Response response = adminClient.realm(REALM_NAME).clients().create(c);
    final String clientId = ApiUtil.getCreatedId(response);
    response.close();

    AtomicInteger uniqueCounter = new AtomicInteger();
    concurrentTest(new CreateClientRole(uniqueCounter, clientId));
}
 
示例12
/**
 * 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));
}
 
示例13
private static ClientRepresentation createClient(String clientId) {
    ClientRepresentation client = new ClientRepresentation();

    client.setClientId(clientId);
    client.setEnabled(true);
    client.setRedirectUris(Arrays.asList("*"));
    client.setClientAuthenticatorType("client-secret");
    client.setSecret("secret");

    return client;
}
 
示例14
/**
 * Tests that an auth request with {@code prompt=none} that is forwarded to a default IDP returns a {@code interaction_required}
 * error message if the IDP requires consent as part of the authentication process. Per spec, when {@code prompt=none} is used
 * the server must not display any authentication or consent user interface pages.
 *
 * @throws Exception if an error occurs while running the test.
 */
@Test
public void testRequireConsentReturnsInteractionRequired() throws Exception {
    RealmResource brokeredRealm = adminClient.realm(bc.providerRealmName());
    List<ClientRepresentation> clients = brokeredRealm.clients().findByClientId(CLIENT_ID);
    org.junit.Assert.assertEquals(1, clients.size());
    ClientRepresentation brokerApp = clients.get(0);
    brokerApp.setConsentRequired(true);
    brokeredRealm.clients().get(brokerApp.getId()).update(brokerApp);
    /* verify that the interaction_required error is returned with sending auth request to the consumer realm with prompt=none. */
    checkAuthWithPromptNoneReturnsInteractionRequired();
}
 
示例15
@Test
public void testIdTokenEncryptedResponse() throws Exception {
    OIDCClientRepresentation response = null;
    OIDCClientRepresentation updated = null;
    try {
         // create (no specification)
         OIDCClientRepresentation clientRep = createRep();

         response = reg.oidc().create(clientRep);
         Assert.assertEquals(Boolean.FALSE, response.getTlsClientCertificateBoundAccessTokens());
         Assert.assertNotNull(response.getClientSecret());

         // Test Keycloak representation
         ClientRepresentation kcClient = getClient(response.getClientId());
         OIDCAdvancedConfigWrapper config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient);
         Assert.assertNull(config.getIdTokenEncryptedResponseAlg());
         Assert.assertNull(config.getIdTokenEncryptedResponseEnc());

         // update (alg RSA1_5, enc A128CBC-HS256)
         reg.auth(Auth.token(response));
         response.setIdTokenEncryptedResponseAlg(JWEConstants.RSA1_5);
         response.setIdTokenEncryptedResponseEnc(JWEConstants.A128CBC_HS256);
         updated = reg.oidc().update(response);
         Assert.assertEquals(JWEConstants.RSA1_5, updated.getIdTokenEncryptedResponseAlg());
         Assert.assertEquals(JWEConstants.A128CBC_HS256, updated.getIdTokenEncryptedResponseEnc());

         // Test Keycloak representation
         kcClient = getClient(updated.getClientId());
         config = OIDCAdvancedConfigWrapper.fromClientRepresentation(kcClient);
         Assert.assertEquals(JWEConstants.RSA1_5, config.getIdTokenEncryptedResponseAlg());
         Assert.assertEquals(JWEConstants.A128CBC_HS256, config.getIdTokenEncryptedResponseEnc());

    } finally {
        // revert
        reg.auth(Auth.token(updated));
        updated.setIdTokenEncryptedResponseAlg(null);
        updated.setIdTokenEncryptedResponseEnc(null);
        reg.oidc().update(updated);
    }
}
 
示例16
private AuthzClient createAuthzClient(ClientRepresentation client) {
    Map<String, Object> credentials = new HashMap<>();

    credentials.put("secret", "secret");

    return AuthzClient
            .create(new Configuration(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth",
                    testRealm().toRepresentation().getRealm(), client.getClientId(),
                    credentials, httpClient));
}
 
示例17
/**
 * Refers to in old test suite: PostBrokerFlowTest#testBrokerReauthentication_samlBrokerWithOTPRequired
 */
@Test
public void testReauthenticationSamlBrokerWithOTPRequired() 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()));
        testingClient.server(bc.consumerRealmName()).run(configurePostBrokerLoginWithOTP(samlBrokerConfig.getIDPAlias()));
        logInWithBroker(samlBrokerConfig);

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

        logInWithBroker(bc);

        waitForPage(driver, "account already exists", false);
        idpConfirmLinkPage.assertCurrent();
        idpConfirmLinkPage.clickLinkAccount();

        loginPage.clickSocial(samlBrokerConfig.getIDPAlias());
        waitForPage(driver, "log in to", true);
        log.debug("Logging in");
        loginTotpPage.login(totp.generateTOTP(totpSecret));

        assertNumFederatedIdentities(consumerRealm.users().search(samlBrokerConfig.getUserLogin()).get(0).getId(), 2);
    } finally {
        updateExecutions(AbstractBrokerTest::setUpMissingUpdateProfileOnFirstLogin);
        removeUserByUsername(consumerRealm, "consumer");
    }
}
 
示例18
@Override
public List<ClientRepresentation> createProviderClients() {
    List<ClientRepresentation> clientsRepList = super.createProviderClients();
    log.info("Update provider clients to accept JWT authentication");
    KeyMetadataRepresentation keyRep = KeyUtils.getActiveKey(adminClient.realm(consumerRealmName()).keys().getKeyMetadata(), Algorithm.RS256);
    for (ClientRepresentation client: clientsRepList) {
        client.setClientAuthenticatorType(JWTClientAuthenticator.PROVIDER_ID);
        if (client.getAttributes() == null) {
            client.setAttributes(new HashMap<String, String>());
        }
        client.getAttributes().put(JWTClientAuthenticator.CERTIFICATE_ATTR, keyRep.getCertificate());
    }
    return clientsRepList;
}
 
示例19
private MultivaluedHashMap<String, RoleRepresentation> findClientComposites(String realm, Supplier<RoleResource> roleSupplier) {
    MultivaluedHashMap<String, RoleRepresentation> clientComposites = new MultivaluedHashMap<>();

    List<ClientRepresentation> clients = clientRepository.getClients(realm);

    for (ClientRepresentation client : clients) {
        Set<RoleRepresentation> clientRoleComposites = findClientComposites(realm, client.getClientId(), roleSupplier);
        clientComposites.addAll(client.getClientId(), new ArrayList<>(clientRoleComposites));
    }

    return clientComposites;
}
 
示例20
public void addClientRoles(String realm, String groupId, String clientId, List<String> roleNames) {
    GroupResource groupResource = loadGroupById(realm, groupId);
    RoleMappingResource rolesResource = groupResource.roles();

    ClientRepresentation client = clientRepository.getClientByClientId(realm, clientId);
    RoleScopeResource groupClientRolesResource = rolesResource.clientLevel(client.getId());

    List<RoleRepresentation> clientRoles = roleRepository.searchClientRoles(realm, clientId, roleNames);
    groupClientRolesResource.add(clientRoles);
}
 
示例21
@Test
public void testCreate() throws Exception {
    ClientsResource clients = getAdminClient().realms().realm(TEST).clients();
    ClientRepresentation client = clients.findByClientId("myclient").get(0);
    ResourceServerRepresentation settings = JsonSerialization.readValue(getClass().getResourceAsStream("/authorization-test/acme-resource-server-cleanup-test.json"), ResourceServerRepresentation.class);

    clients.get(client.getId()).authorization().importSettings(settings);

    testingClient.server().run(AuthzCleanupTest::setup);
}
 
示例22
@Test
public void testRoleBasedPolicy() {
    ClientResource clientResource = getClientResource();
    AuthorizationResource authorizationResource = clientResource.authorization();
    
    ClientRepresentation account = testRealmResource().clients().findByClientId("account").get(0);
    RoleRepresentation role = testRealmResource().clients().get(account.getId()).roles().get("view-profile").toRepresentation();
    
    PolicyRepresentation policy = new PolicyRepresentation();
    policy.setName("role-based-policy");
    policy.setType("role");
    Map<String, String> config = new HashMap<>();
    config.put("roles", "[{\"id\":\"" + role.getId() +"\"}]");
    policy.setConfig(config);
    Response create = authorizationResource.policies().create(policy);
    try {
        Assert.assertEquals(Status.CREATED, create.getStatusInfo());
    } finally {
        create.close();
    }
    
    //this call was messing up with DB, see KEYCLOAK-4340
    authorizationResource.exportSettings();
    
    //this call failed with NPE
    authorizationResource.exportSettings();
}
 
示例23
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test
public void testAddClientsWithServiceAccountsAndAuthorization() throws IOException {
    setFail();
    addClients(true);

    PartialImportResults results = doImport();
    assertEquals(NUM_ENTITIES * 2, results.getAdded());

    for (PartialImportResult result : results.getResults()) {
        if (result.getResourceType().equals(ResourceType.CLIENT)) {
            String id = result.getId();
            ClientResource clientRsc = testRealmResource().clients().get(id);
            ClientRepresentation client = clientRsc.toRepresentation();
            assertTrue(client.getName().startsWith(CLIENT_PREFIX));
            Assert.assertTrue(client.isServiceAccountsEnabled());
            Assert.assertTrue(client.getAuthorizationServicesEnabled());
            AuthorizationResource authRsc = clientRsc.authorization();
            ResourceServerRepresentation authRep = authRsc.exportSettings();
            Assert.assertNotNull(authRep);
            Assert.assertEquals(2, authRep.getResources().size());
            Assert.assertEquals(3, authRep.getPolicies().size());
        } else {
            UserResource userRsc = testRealmResource().users().get(result.getId());
            Assert.assertTrue(userRsc.toRepresentation().getUsername().startsWith(
                    ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + CLIENT_PREFIX));
        }
    }
}
 
示例24
private void testGroupPolicyTypeFineGrainedAdminPermission() {
    ClientsResource clients = migrationRealm.clients();
    ClientRepresentation clientRepresentation = clients.findByClientId("realm-management").get(0);
    List<ResourceRepresentation> resources = clients.get(clientRepresentation.getId()).authorization().resources().resources();

    assertEquals(5, resources.size());

    for (ResourceRepresentation resource : resources) {
        assertEquals("Group", resource.getType());
    }
}
 
示例25
private void configureAuthorizationServices() {
    ClientsResource clients = realmsResouce().realm(REALM_NAME).clients();
    ClientRepresentation client = clients.findByClientId(RESOURCE_SERVER_ID).get(0);

    client.setAuthorizationServicesEnabled(false);

    // disables authorization services and remove authorization configuration from the client app
    clients.get(client.getId()).update(client);

    client.setAuthorizationServicesEnabled(true);

    // enable authorization services in order to generate the default config and continue with tests
    clients.get(client.getId()).update(client);
}
 
示例26
@Test
public void clientInvalidationTest() throws Exception {
    enableDcOnLoadBalancer(DC.FIRST);
    enableDcOnLoadBalancer(DC.SECOND);

    ClientResource clientResourceDc0 = ApiUtil.findClientByClientId(getAdminClientForStartedNodeInDc(0).realms().realm(REALM_NAME), "named-test-app");
    ClientResource clientResourceDc1 = ApiUtil.findClientByClientId(getAdminClientForStartedNodeInDc(1).realms().realm(REALM_NAME), "named-test-app");
    ClientRepresentation clientDc0 = clientResourceDc0.toRepresentation();
    ClientRepresentation clientDc1 = clientResourceDc1.toRepresentation();

    // Test same client on both DCs
    Assert.assertEquals("My Named Test App", clientDc0.getName());
    Assert.assertEquals("My Named Test App", clientDc1.getName());

    // Update client on DC0
    clientDc0.setName("Changed Test App");
    clientResourceDc0.update(clientDc0);

    // Assert updated on both DC0 and DC1 (here retry is needed. We need to wait until invalidation message arrives)
    clientDc0 = clientResourceDc0.toRepresentation();
    Assert.assertEquals("Changed Test App", clientDc0.getName());

    AtomicInteger i = new AtomicInteger(0);
    Retry.execute(() -> {
        i.incrementAndGet();
        ClientRepresentation clientDcc1 = clientResourceDc1.toRepresentation();
        Assert.assertEquals("Changed Test App", clientDcc1.getName());
    }, 50, 50);

    log.infof("clientInvalidationTest: Passed after '%d' iterations", i.get());
}
 
示例27
private void updateClient() throws ClientRegistrationException {
    ClientRepresentation client = reg.get(CLIENT_ID);
    client.setRedirectUris(Collections.singletonList("http://localhost:8080/app"));

    reg.update(client);

    ClientRepresentation updatedClient = reg.get(CLIENT_ID);

    assertEquals(1, updatedClient.getRedirectUris().size());
    assertEquals("http://localhost:8080/app", updatedClient.getRedirectUris().get(0));
}
 
示例28
private ClientRepresentation loadClientByClientId(String realm, String clientId) {
    List<ClientRepresentation> foundClients = realmRepository.loadRealm(realm)
            .clients()
            .findByClientId(clientId);

    if (foundClients.isEmpty()) {
        throw new KeycloakRepositoryException("Cannot find client by clientId '" + clientId + "'");
    }

    return foundClients.get(0);
}
 
示例29
public final Set<String> getClientIds(String realm) {
    return realmRepository.loadRealm(realm)
            .clients()
            .findAll()
            .stream()
            .map(ClientRepresentation::getClientId)
            .collect(Collectors.toSet());
}
 
示例30
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    super.addTestRealms(testRealms);
    RealmRepresentation testRealm = testRealms.get(0);

    ClientRepresentation samlApp = KeycloakModelUtils.createClient(testRealm, "oidc-client");
    samlApp.setSecret("secret");
    samlApp.setServiceAccountsEnabled(true);
    samlApp.setDirectAccessGrantsEnabled(true);
}