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

The following examples show how to use org.keycloak.representations.idm.ClientRepresentation#setConsentRequired() . 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: ConsentsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected List<ClientRepresentation> createProviderClients() {
    ClientRepresentation client = new ClientRepresentation();
    client.setId(CLIENT_ID);
    client.setName(CLIENT_ID);
    client.setSecret(CLIENT_SECRET);
    client.setEnabled(true);
    client.setConsentRequired(true);

    client.setRedirectUris(Collections.singletonList(getAuthRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint/*"));

    client.setAdminUrl(getAuthRoot() +
            "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_OIDC_ALIAS + "/endpoint");

    return Collections.singletonList(client);
}
 
Example 2
Source File: ClientRegistrationPoliciesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE) // We would need to do domain name -> ip address to set trusted host
public void testAnonConsentRequired() throws Exception {
    setTrustedHost("localhost");
    OIDCClientRepresentation client = create();

    // Assert new client has consent required
    String clientId = client.getClientId();
    ClientRepresentation clientRep = ApiUtil.findClientByClientId(realmResource(), clientId).toRepresentation();
    Assert.assertTrue(clientRep.isConsentRequired());

    // Try update with disabled consent required. Should fail
    clientRep.setConsentRequired(false);
    assertFail(ClientRegOp.UPDATE, clientRep, 403, "Not permitted to update consentRequired to false");

    // Try update with enabled consent required. Should pass
    clientRep.setConsentRequired(true);
    reg.update(clientRep);
}
 
Example 3
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 4
Source File: ConsentsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsentCancel() {
    // setup account client to require consent
    RealmResource providerRealm = adminClient.realm(providerRealmName());
    ClientResource accountClient = findClientByClientId(providerRealm, "account");

    ClientRepresentation clientRepresentation = accountClient.toRepresentation();
    clientRepresentation.setConsentRequired(true);
    accountClient.update(clientRepresentation);

    // setup correct realm
    accountPage.setAuthRealm(providerRealmName());

    // navigate to account console and login
    accountPage.navigateTo();
    loginPage.form().login(getUserLogin(), getUserPassword());

    consentPage.assertCurrent();

    consentPage.cancel();

    // check an error page after cancelling the consent
    errorPage.assertCurrent();
    assertEquals("No access", errorPage.getError());

    // follow the link "back to application"
    errorPage.clickBackToApplication();

    loginPage.form().login(getUserLogin(), getUserPassword());
    consentPage.confirm();

    // successful login
    accountPage.assertCurrent();
}
 
Example 5
Source File: ConsentsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void clientConsentRequiredAfterLogin() {
    oauth.realm(TEST_REALM_NAME).clientId("test-app");
    AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
    AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(response.getCode(), "password");

    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    String sessionId = loginEvent.getSessionId();

    ClientRepresentation clientRepresentation = adminClient.realm(TEST_REALM_NAME).clients().findByClientId("test-app").get(0);
    try {
        clientRepresentation.setConsentRequired(true);
        adminClient.realm(TEST_REALM_NAME).clients().get(clientRepresentation.getId()).update(clientRepresentation);

        events.clear();

        // try to refresh the token
        // this fails as client no longer has requested consent from user
        AccessTokenResponse refreshTokenResponse = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken(), "password");
        Assert.assertEquals(OAuthErrorException.INVALID_SCOPE, refreshTokenResponse.getError());
        Assert.assertEquals("Client no longer has requested consent from user", refreshTokenResponse.getErrorDescription());

        events.expectRefresh(accessTokenResponse.getRefreshToken(), sessionId).clearDetails().error(Errors.INVALID_TOKEN).assertEvent();
    } finally {
        clientRepresentation.setConsentRequired(false);
        adminClient.realm(TEST_REALM_NAME).clients().get(clientRepresentation.getId()).update(clientRepresentation);
    }
}
 
Example 6
Source File: KcOidcBrokerPromptNoneRedirectTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source File: RequiredActionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void initiateClientScopesConsent(boolean displayOnConsentScreen, String consentScreenText) {
    ClientRepresentation accountClientRep = testRealmResource().clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);
    ClientResource accountClient = testRealmResource().clients().get(accountClientRep.getId());
    accountClientRep.setConsentRequired(true);
    accountClientRep.getAttributes().put(DISPLAY_ON_CONSENT_SCREEN, String.valueOf(displayOnConsentScreen));
    accountClientRep.getAttributes().put(CONSENT_SCREEN_TEXT, consentScreenText);
    accountClient.update(accountClientRep);

    testRealmAccountPage.navigateTo();
    testRealmLoginPage.form().login(grantRealmUser);
    oAuthGrantPage.assertCurrent();
}
 
Example 8
Source File: JavascriptAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void grantBrowserBasedApp() {
    Assume.assumeTrue("This test doesn't work with phantomjs", !"phantomjs".equals(System.getProperty("js.browser")));

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(adminClient.realm(REALM_NAME), CLIENT_ID);
    ClientRepresentation client = clientResource.toRepresentation();
    try {
        client.setConsentRequired(true);
        clientResource.update(client);

        testExecutor.init(defaultArguments(), this::assertInitNotAuth)
              .login(this::assertOnLoginPage)
              .loginForm(testUser, (driver1, output, events) -> assertTrue(oAuthGrantPage.isCurrent(driver1))
                    // I am not sure why is this driver1 argument to isCurrent necessary, but I got exception without it
              );

        oAuthGrantPage.accept();

        EventRepresentation loginEvent = events.expectLogin()
              .client(CLIENT_ID)
              .detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED)
              .detail(Details.REDIRECT_URI, testAppUrl)
              .detail(Details.USERNAME, testUser.getUsername())
              .assertEvent();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);

        testExecutor.init(defaultArguments(), this::assertSuccessfullyLoggedIn);

        applicationsPage.navigateTo();
        events.expectCodeToToken(codeId, loginEvent.getSessionId()).client(CLIENT_ID).assertEvent();

        applicationsPage.revokeGrantForApplication(CLIENT_ID);
        events.expect(EventType.REVOKE_GRANT)
              .client("account")
              .detail(Details.REVOKED_CLIENT, CLIENT_ID)
              .assertEvent();

        jsDriver.navigate().to(testAppUrl);
        testExecutor.configure() // need to configure because we refreshed page
              .init(defaultArguments(), this::assertInitNotAuth)
              .login((driver1, output, events) -> assertTrue(oAuthGrantPage.isCurrent(driver1)));
    } finally {
        // Clean
        client.setConsentRequired(false);
        clientResource.update(client);
    }
}
 
Example 9
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void grantServerBasedApp() {
    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), "customer-portal");
    ClientRepresentation client = clientResource.toRepresentation();
    client.setConsentRequired(true);
    clientResource.update(client);

    RealmRepresentation realm = testRealmResource().toRepresentation();
    realm.setEventsEnabled(true);
    realm.setEnabledEventTypes(Arrays.asList("REVOKE_GRANT", "LOGIN"));
    realm.setEventsListeners(Arrays.asList("jboss-logging", "event-queue"));
    testRealmResource().update(realm);

    customerPortal.navigateTo();

    loginPage.form().login("[email protected]", "password");

    assertTrue(oAuthGrantPage.isCurrent());

    oAuthGrantPage.accept();

    waitForPageToLoad();
    assertLogged();

    String userId = ApiUtil.findUserByUsername(testRealmResource(), "[email protected]").getId();

    assertEvents.expectLogin()
            .realm(realm.getId())
            .client("customer-portal")
            .user(userId)
            .detail(Details.USERNAME, "[email protected]")
            .detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED)
            .detail(Details.REDIRECT_URI,
                    org.hamcrest.Matchers.anyOf(org.hamcrest.Matchers.equalTo(customerPortal.getInjectedUrl().toString()),
                            org.hamcrest.Matchers.equalTo(customerPortal.getInjectedUrl().toString() + "/")))
            .removeDetail(Details.CODE_ID)
            .assertEvent();

    assertEvents.expectCodeToToken(null, null)
            .realm(realm.getId())
            .client("customer-portal")
            .user(userId)
            .session(AssertEvents.isUUID())
            .removeDetail(Details.CODE_ID)
            .assertEvent();

    applicationsPage.navigateTo();
    applicationsPage.revokeGrantForApplication("customer-portal");

    customerPortal.navigateTo();

    assertTrue(oAuthGrantPage.isCurrent());

    assertEvents.expect(EventType.REVOKE_GRANT)
            .realm(realm.getId())
            .client("account")
            .user(userId)
            .detail(Details.REVOKED_CLIENT, "customer-portal")
            .assertEvent();

    assertEvents.assertEmpty();

    // Revert consent
    client = clientResource.toRepresentation();
    client.setConsentRequired(false);
    clientResource.update(client);
}
 
Example 10
Source File: ClientManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void consentRequired(boolean enable) {
    ClientRepresentation app = clientResource.toRepresentation();
    app.setConsentRequired(enable);
    clientResource.update(app);
}