Java Code Examples for org.keycloak.admin.client.resource.RealmResource#update()

The following examples show how to use org.keycloak.admin.client.resource.RealmResource#update() . 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: BrowserFlowTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static void revertFlows(RealmResource realmResource, String flowToDeleteAlias) {
    List<AuthenticationFlowRepresentation> flows = realmResource.flows().getFlows();

    // Set default browser flow
    RealmRepresentation realm = realmResource.toRepresentation();
    realm.setBrowserFlow(DefaultAuthenticationFlows.BROWSER_FLOW);
    realmResource.update(realm);

    AuthenticationFlowRepresentation flowRepresentation = AbstractAuthenticationTest.findFlowByAlias(flowToDeleteAlias, flows);

    // Throw error if flow doesn't exists to ensure we did not accidentally use different alias of non-existing flow when
    // calling this method
    if (flowRepresentation == null) {
        throw new IllegalArgumentException("The flow with alias " + flowToDeleteAlias + " did not exists");
    }

    realmResource.flows().deleteFlow(flowRepresentation.getId());
}
 
Example 2
Source File: OpenShiftTokenReviewEndpointTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void hs256() {
    RealmResource realm = adminClient.realm("test");
    RealmRepresentation rep = realm.toRepresentation();

    try {
        rep.setDefaultSignatureAlgorithm(Algorithm.HS256);
        realm.update(rep);

        Review r = new Review().algorithm(Algorithm.HS256).invoke()
                .assertSuccess();

        String userId = testRealm().users().search(r.username).get(0).getId();

        OpenShiftTokenReviewResponseRepresentation.User user = r.response.getStatus().getUser();

        assertEquals(userId, user.getUid());
        assertEquals("test-user@localhost", user.getUsername());
        assertNotNull(user.getExtra());

        r.assertScope("openid", "email", "profile");
    } finally {
        rep.setDefaultSignatureAlgorithm(null);
        realm.update(rep);
    }
}
 
Example 3
Source File: TermsAndConditionsThemeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testTermsAndConditions() {
    String userId = createUser(REALM, HOMER, HOMER_PASS);
    setRequiredActionEnabled(REALM, RequiredActions.TERMS_AND_CONDITIONS, true, false);
    setRequiredActionEnabled(REALM, userId, RequiredActions.TERMS_AND_CONDITIONS, true);
    
    RealmResource realmResource = adminClient.realm(REALM);
    RealmRepresentation realmRepresentation = realmResource.toRepresentation();
    realmRepresentation.setLoginTheme("qe");
    realmResource.update(realmRepresentation);
    
    testRealmAdminConsolePage.navigateTo();
    testRealmLoginPage.form().login(HOMER, HOMER_PASS);

    Assert.assertTrue(termsAndConditionsPage.isCurrent());
    Assert.assertTrue(termsAndConditionsPage.getText().contains("See QA for more information."));
    Assert.assertEquals("Yes", termsAndConditionsPage.getAcceptButtonText());
    Assert.assertEquals("No", termsAndConditionsPage.getDeclineButtonText());
}
 
Example 4
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 5
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testSuccessfulAuthentication_emailTrustEnabled_emailVerifyEnabled_emailUpdatedOnFirstLogin
 */
@Test
public void testVerifyEmailRequiredActionWhenChangingEmailDuringFirstLogin() {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setVerifyEmail(true);

    realm.update(realmRep);

    IdentityProviderRepresentation idpRep = identityProviderResource.toRepresentation();

    idpRep.setTrustEmail(true);

    identityProviderResource.update(idpRep);

    configureSMTPServer();

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

    waitForPage(driver, "update account information", false);
    updateAccountInformationPage.assertCurrent();
    updateAccountInformationPage.updateAccountInformation("[email protected]", "FirstName", "LastName");

    verifyEmailPage.assertCurrent();

    String verificationUrl = assertEmailAndGetUrl(MailServerConfiguration.FROM, "[email protected]",
            "verify your email address", false);

    driver.navigate().to(verificationUrl.trim());
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();

    List<UserRepresentation> users = realm.users().search(bc.getUserLogin());
    assertEquals(1, users.size());
    List<String> requiredActions = users.get(0).getRequiredActions();
    assertEquals(0, requiredActions.size());
}
 
Example 6
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testSuccessfulAuthenticationWithoutUpdateProfile_emailProvided_emailVerifyEnabled_emailTrustEnabled
 */
@Test
public void testVerifyEmailNotRequiredActionWhenEmailIsTrustedByProvider() {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setVerifyEmail(true);

    realm.update(realmRep);

    IdentityProviderRepresentation idpRep = identityProviderResource.toRepresentation();

    idpRep.setTrustEmail(true);

    identityProviderResource.update(idpRep);

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

    waitForPage(driver, "update account information", false);
    updateAccountInformationPage.assertCurrent();
    updateAccountInformationPage.updateAccountInformation("FirstName", "LastName");

    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();

    List<UserRepresentation> users = realm.users().search(bc.getUserLogin());
    assertEquals(1, users.size());
    List<String> requiredActions = users.get(0).getRequiredActions();
    assertEquals(0, requiredActions.size());
}
 
Example 7
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testSuccessfulAuthenticationWithoutUpdateProfile_emailNotProvided_emailVerifyEnabled
 *
 */
@Test
public void testSuccessfulAuthenticationWithoutUpdateProfile_emailNotProvided_emailVerifyEnabled() {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setVerifyEmail(true);

    realm.update(realmRep);

    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    createUser(bc.providerRealmName(), "no-email", "password", "FirstName", "LastName", null);

    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
    log.debug("Clicking social " + bc.getIDPAlias());
    loginPage.clickSocial(bc.getIDPAlias());
    waitForPage(driver, "log in to", true);
    Assert.assertTrue("Driver should be on the provider realm page right now",
            driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
    log.debug("Logging in");
    loginPage.login("no-email", "password");

    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();

    List<UserRepresentation> users = realm.users().search("no-email");
    assertEquals(1, users.size());
    List<String> requiredActions = users.get(0).getRequiredActions();
    assertEquals(1, requiredActions.size());
    assertEquals(UserModel.RequiredAction.VERIFY_EMAIL.name(), requiredActions.get(0));

}
 
Example 8
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractFirstBrokerLoginTest#testRegistrationWithEmailAsUsername
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testSuccessfulAuthenticationWithoutUpdateProfile_newUser_emailAsUsername()
 */
@Test
public void testRequiredRegistrationEmailAsUserName() {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    updateExecutions(AbstractBrokerTest::enableUpdateProfileOnFirstLogin);
    realmRep.setRegistrationEmailAsUsername(true);
    realm.update(realmRep);

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

    Assert.assertTrue(updateAccountInformationPage.isCurrent());
    Assert.assertTrue("We must be on correct realm right now",
            driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"));

    log.debug("Updating info on updateAccount page");
    try {
        updateAccountInformationPage.updateAccountInformation("test", "[email protected]", "FirstName", "LastName");
        Assert.fail("It is not expected to see username field");
    } catch (NoSuchElementException ignore) {
    }

    updateAccountInformationPage.updateAccountInformation("[email protected]", "FirstName", "LastName");
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();

    assertEquals(1, realm.users().search("[email protected]").size());
}
 
Example 9
Source File: AbstractBaseBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void configureSMTPServer() {
    MailServer.start();
    MailServer.createEmailAccount(USER_EMAIL, "password");
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation master = realm.toRepresentation();
    master.setSmtpServer(suiteContext.getSmtpServer());
    realm.update(master);
}
 
Example 10
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void expiration() throws Exception {
    int sessionMax = (int) TimeUnit.MINUTES.toSeconds(30);
    int sessionIdle = (int) TimeUnit.MINUTES.toSeconds(30);
    int tokenLifespan = (int) TimeUnit.MINUTES.toSeconds(5);

    RealmResource realm = adminClient.realm("test");
    RealmRepresentation rep = realm.toRepresentation();
    Integer originalSessionMax = rep.getSsoSessionMaxLifespan();
    rep.setSsoSessionMaxLifespan(sessionMax);
    realm.update(rep);

    try {
        oauth.doLogin("test-user@localhost", "password");

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
        assertEquals(200, response.getStatusCode());

        // Assert refresh expiration equals session idle
        assertExpiration(response.getRefreshExpiresIn(), sessionIdle);

        // Assert token expiration equals token lifespan
        assertExpiration(response.getExpiresIn(), tokenLifespan);

        setTimeOffset(sessionMax - 60);

        response = oauth.doRefreshTokenRequest(response.getRefreshToken(), "password");
        assertEquals(200, response.getStatusCode());

        // Assert expiration equals session expiration
        assertExpiration(response.getRefreshExpiresIn(), 60);
        assertExpiration(response.getExpiresIn(), 60);
    } finally {
        rep.setSsoSessionMaxLifespan(originalSessionMax);
        realm.update(rep);
    }
}
 
Example 11
Source File: TermsAndConditionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelfRegisteredUser() {
    // enable self-registration
    RealmResource realmResource = adminClient.realm(REALM);
    RealmRepresentation realmRepresentation = realmResource.toRepresentation();
    realmRepresentation.setRegistrationAllowed(true);
    realmResource.update(realmRepresentation);
    
    // enable terms
    setRequiredActionEnabled(REALM, RequiredActions.TERMS_AND_CONDITIONS, true, true);
    
    // self-register
    CredentialRepresentation mrBurnsPassword = new CredentialRepresentation();
    mrBurnsPassword.setType(CredentialRepresentation.PASSWORD);
    mrBurnsPassword.setValue("Excellent.");
    
    List<CredentialRepresentation> credentials = new ArrayList<CredentialRepresentation>();
    credentials.add(mrBurnsPassword);
    
    UserRepresentation mrBurns = new UserRepresentation();
    mrBurns.setUsername("mrburns");
    mrBurns.setFirstName("Montgomery");
    mrBurns.setLastName("Burns");
    mrBurns.setEmail("[email protected]");
    mrBurns.setCredentials(credentials);
    
    testRealmAdminConsolePage.navigateTo();
    testRealmLoginPage.form().register();
    
    registrationPage.register(mrBurns);
    
    // test t&c
    Assert.assertTrue(termsAndConditionsPage.isCurrent());
    
    // disable terms
    setRequiredActionEnabled(REALM, RequiredActions.TERMS_AND_CONDITIONS, false, false);
}
 
Example 12
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testTokenConcurrentRefresh() {
    RealmResource demoRealm = adminClient.realm("demo");
    RealmRepresentation demo = demoRealm.toRepresentation();

    demo.setAccessTokenLifespan(2);
    demo.setRevokeRefreshToken(true);
    demo.setRefreshTokenMaxReuse(0);

    demoRealm.update(demo);

    // Login
    tokenRefreshPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(tokenRefreshPage);

    setAdapterAndServerTimeOffset(5, tokenRefreshPage.toString());

    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie jsessionid = new BasicClientCookie("JSESSIONID", driver.manage().getCookieNamed("JSESSIONID").getValue());

    jsessionid.setDomain("localhost");
    jsessionid.setPath("/");
    cookieStore.addCookie(jsessionid);

    ExecutorService executor = Executors.newWorkStealingPool();
    CompletableFuture future = CompletableFuture.completedFuture(null);

    try {
        for (int i = 0; i < 5; i++) {
            future = CompletableFuture.allOf(future, CompletableFuture.runAsync(() -> {
                try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore)
                        .build()) {
                    HttpUriRequest request = new HttpGet(tokenRefreshPage.getInjectedUrl().toString());
                    try (CloseableHttpResponse httpResponse = client.execute(request)) {
                        assertTrue("Token not refreshed", EntityUtils.toString(httpResponse.getEntity()).contains("accessToken"));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, executor));
        }
        
        future.join();
    } finally {
        executor.shutdownNow();
    }

    // Revert times
    setAdapterAndServerTimeOffset(0, tokenRefreshPage.toString());
}
 
Example 13
Source File: SessionSpringBootTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testSessionInvalidatedAfterFailedRefresh() {
    RealmResource realmResource = adminClient.realm(REALM_NAME);
    RealmRepresentation realmRep = realmResource.toRepresentation();
    ClientResource clientResource = null;
    for (ClientRepresentation clientRep : realmResource.clients().findAll()) {
        if (CLIENT_ID.equals(clientRep.getClientId())) {
            clientResource = realmResource.clients().get(clientRep.getId());
        }
    }

    assertThat(clientResource, is(notNullValue()));

    clientResource.toRepresentation().setAdminUrl("");
    int origTokenLifespan = realmRep.getAccessCodeLifespan();
    realmRep.setAccessCodeLifespan(1);
    realmResource.update(realmRep);

    // Login
    loginAndCheckSession();

    // Logout
    String logoutUri = logoutPage(SERVLET_URL);
    driver.navigate().to(logoutUri);
    waitForPageToLoad();

    // Assert that http session was invalidated
    driver.navigate().to(SERVLET_URL);
    waitForPageToLoad();

    assertCurrentUrlStartsWith(testRealmLoginPage, driver);
    testRealmLoginPage.form().login(USER_LOGIN, USER_PASSWORD);

    sessionPage.assertIsCurrent();
    assertThat(sessionPage.getCounter(), is(equalTo(0)));

    clientResource.toRepresentation().setAdminUrl(BASE_URL);
    realmRep.setAccessCodeLifespan(origTokenLifespan);
    realmResource.update(realmRep);

    driver.navigate().to(logoutUri);
    waitForPageToLoad();
}
 
Example 14
Source File: UserInfoTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testNotBeforeTokens() {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        int time = Time.currentTime() + 60;

        RealmResource realm = adminClient.realm("test");
        RealmRepresentation rep = realm.toRepresentation();
        rep.setNotBefore(time);
        realm.update(rep);

        Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());

        assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());

        response.close();

        events.expect(EventType.USER_INFO_REQUEST_ERROR)
                .error(Errors.INVALID_TOKEN)
                .user(Matchers.nullValue(String.class))
                .session(Matchers.nullValue(String.class))
                .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)
                .client((String) null)
                .assertEvent();

        events.clear();
        rep.setNotBefore(0);
        realm.update(rep);

        // do the same with client's notBefore
        ClientResource clientResource = realm.clients().get(realm.clients().findByClientId("test-app").get(0).getId());
        ClientRepresentation clientRep = clientResource.toRepresentation();
        clientRep.setNotBefore(time);
        clientResource.update(clientRep);

        response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());

        assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());

        response.close();

        events.expect(EventType.USER_INFO_REQUEST_ERROR)
                .error(Errors.INVALID_TOKEN)
                .user(Matchers.nullValue(String.class))
                .session(Matchers.nullValue(String.class))
                .detail(Details.AUTH_METHOD, Details.VALIDATE_ACCESS_TOKEN)
                .client((String) null)
                .assertEvent();

        clientRep.setNotBefore(0);
        clientResource.update(clientRep);
    } finally {
        client.close();
    }
}
 
Example 15
Source File: RefreshTokenTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * KEYCLOAK-1267
 * @throws Exception
 */
@Test
public void refreshTokenUserSessionMaxLifespanWithRememberMe() throws Exception {

    RealmResource testRealm = adminClient.realm("test");
    RealmRepresentation testRealmRep = testRealm.toRepresentation();
    Boolean previousRememberMe = testRealmRep.isRememberMe();
    int previousSsoMaxLifespanRememberMe = testRealmRep.getSsoSessionMaxLifespanRememberMe();

    try {
        testRealmRep.setRememberMe(true);
        testRealm.update(testRealmRep);

        oauth.doRememberMeLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String sessionId = loginEvent.getSessionId();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");

        events.poll();

        String refreshId = oauth.parseRefreshToken(tokenResponse.getRefreshToken()).getId();

        testRealmRep.setSsoSessionMaxLifespanRememberMe(1);
        testRealm.update(testRealmRep);

        setTimeOffset(2);

        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        assertEquals(400, tokenResponse.getStatusCode());
        assertNull(tokenResponse.getAccessToken());
        assertNull(tokenResponse.getRefreshToken());

        events.expectRefresh(refreshId, sessionId).error(Errors.INVALID_TOKEN);
        events.clear();

    } finally {
        testRealmRep.setSsoSessionMaxLifespanRememberMe(previousSsoMaxLifespanRememberMe);
        testRealmRep.setRememberMe(previousRememberMe);
        testRealm.update(testRealmRep);
        setTimeOffset(0);
    }
}
 
Example 16
Source File: RefreshTokenTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testUserSessionRefreshAndIdleRememberMe() throws Exception {
    RealmResource testRealm = adminClient.realm("test");
    RealmRepresentation testRealmRep = testRealm.toRepresentation();
    Boolean previousRememberMe = testRealmRep.isRememberMe();
    int originalIdleRememberMe = testRealmRep.getSsoSessionIdleTimeoutRememberMe();

    try {
        testRealmRep.setRememberMe(true);
        testRealm.update(testRealmRep);

        oauth.doRememberMeLogin("test-user@localhost", "password");

        EventRepresentation loginEvent = events.expectLogin().assertEvent();

        String sessionId = loginEvent.getSessionId();

        String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");

        events.poll();

        String refreshId = oauth.parseRefreshToken(tokenResponse.getRefreshToken()).getId();
        int last = testingClient.testing().getLastSessionRefresh("test", sessionId, false);

        setTimeOffset(2);
        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");
        oauth.verifyToken(tokenResponse.getAccessToken());
        oauth.parseRefreshToken(tokenResponse.getRefreshToken());
        assertEquals(200, tokenResponse.getStatusCode());

        int next = testingClient.testing().getLastSessionRefresh("test", sessionId, false);
        Assert.assertNotEquals(last, next);

        testRealmRep.setSsoSessionIdleTimeoutRememberMe(1);
        testRealm.update(testRealmRep);

        events.clear();
        // Needs to add some additional time due the tollerance allowed by IDLE_TIMEOUT_WINDOW_SECONDS
        setTimeOffset(6 + SessionTimeoutHelper.IDLE_TIMEOUT_WINDOW_SECONDS);
        tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken(), "password");

        // test idle remember me timeout
        assertEquals(400, tokenResponse.getStatusCode());
        assertNull(tokenResponse.getAccessToken());
        assertNull(tokenResponse.getRefreshToken());

        events.expectRefresh(refreshId, sessionId).error(Errors.INVALID_TOKEN);
        events.clear();

    } finally {
        testRealmRep.setSsoSessionIdleTimeoutRememberMe(originalIdleRememberMe);
        testRealmRep.setRememberMe(previousRememberMe);
        testRealm.update(testRealmRep);
        setTimeOffset(0);
    }
}
 
Example 17
Source File: AbstractBaseBrokerTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void removeSMTPConfiguration(RealmResource consumerRealm) {
    RealmRepresentation master = consumerRealm.toRepresentation();
    master.setSmtpServer(Collections.emptyMap());
    consumerRealm.update(master);
}
 
Example 18
Source File: AbstractAdvancedBrokerTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testPostBrokerLoginFlowWithOTP_bruteForceEnabled() {
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    testingClient.server(bc.consumerRealmName()).run(configurePostBrokerLoginWithOTP(bc.getIDPAlias()));

    // Enable brute force protector in cosumer realm
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation consumerRealmRep = realm.toRepresentation();
    consumerRealmRep.setBruteForceProtected(true);
    consumerRealmRep.setFailureFactor(2);
    consumerRealmRep.setMaxDeltaTimeSeconds(20);
    consumerRealmRep.setMaxFailureWaitSeconds(100);
    consumerRealmRep.setWaitIncrementSeconds(5);
    realm.update(consumerRealmRep);

    try {
        driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));

        logInWithBroker(bc);

        totpPage.assertCurrent();
        String totpSecret = totpPage.getTotpSecret();
        totpPage.configure(totp.generateTOTP(totpSecret));
        assertNumFederatedIdentities(realm.users().search(bc.getUserLogin()).get(0).getId(), 1);
        logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

        logInWithBroker(bc);

        loginTotpPage.assertCurrent();

        // Login for 2 times with incorrect TOTP. This should temporarily disable the user
        loginTotpPage.login("bad-totp");
        Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getError());

        loginTotpPage.login("bad-totp");
        Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getError());

        // Login with valid TOTP. I should not be able to login
        loginTotpPage.login(totp.generateTOTP(totpSecret));
        Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getError());

        // Clear login failures
        String userId = ApiUtil.findUserByUsername(realm, bc.getUserLogin()).getId();
        realm.attackDetection().clearBruteForceForUser(userId);

        loginTotpPage.login(totp.generateTOTP(totpSecret));
        waitForAccountManagementTitle();
        logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());
    } finally {
        testingClient.server(bc.consumerRealmName()).run(disablePostBrokerLoginFlow(bc.getIDPAlias()));

        // Disable brute force protector
        consumerRealmRep = realm.toRepresentation();
        consumerRealmRep.setBruteForceProtected(false);
        realm.update(consumerRealmRep);
    }
}
 
Example 19
Source File: AuthorizationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveDefaultResourceWithAdminEventsEnabled() {
    RealmResource realmResource = testRealmResource();
    RealmRepresentation realmRepresentation = realmResource.toRepresentation();

    realmRepresentation.setAdminEventsEnabled(true);

    realmResource.update(realmRepresentation);

    ClientResource clientResource = getClientResource();
    ClientRepresentation resourceServer = getResourceServer();

    ResourceServerRepresentation settings = clientResource.authorization().getSettings();

    assertEquals(PolicyEnforcerConfig.EnforcementMode.ENFORCING.name(), settings.getPolicyEnforcementMode().name());
    assertEquals(resourceServer.getId(), settings.getClientId());
    List<ResourceRepresentation> defaultResources = clientResource.authorization().resources().resources();

    assertEquals(1, defaultResources.size());

    clientResource.authorization().resources().resource(defaultResources.get(0).getId()).remove();

    assertTrue(clientResource.authorization().resources().resources().isEmpty());
}
 
Example 20
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 3 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testSuccessfulAuthenticationWithoutUpdateProfile_emailProvided_emailVerifyEnabled
 */
@Test
public void testLinkAccountWithUntrustedEmailVerified() {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setVerifyEmail(true);

    realm.update(realmRep);

    IdentityProviderRepresentation idpRep = identityProviderResource.toRepresentation();

    idpRep.setTrustEmail(false);

    identityProviderResource.update(idpRep);

    configureSMTPServer();

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

    waitForPage(driver, "update account information", false);
    updateAccountInformationPage.assertCurrent();
    updateAccountInformationPage.updateAccountInformation("FirstName", "LastName");

    verifyEmailPage.assertCurrent();

    String verificationUrl = assertEmailAndGetUrl(MailServerConfiguration.FROM, USER_EMAIL,
            "verify your email address", false);

    driver.navigate().to(verificationUrl.trim());
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();
}