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

The following examples show how to use org.keycloak.admin.client.resource.RealmResource#toRepresentation() . 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: RealmRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private Optional<RealmRepresentation> tryToLoadRealm(String realm) {
    Optional<RealmRepresentation> maybeRealm;

    try {
        RealmResource realmResource = loadRealm(realm);

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

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

    return maybeRealm;
}
 
Example 2
Source File: UncaughtErrorPageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void internationalisationEnabled() throws MalformedURLException {
    RealmResource testRealm = realmsResouce().realm("master");
    RealmRepresentation rep = testRealm.toRepresentation();
    rep.setInternationalizationEnabled(true);
    rep.setDefaultLocale("en");
    rep.setSupportedLocales(Collections.singleton("en"));
    testRealm.update(rep);

    try {
        checkPageNotFound("/auth/realms/master/nosuch");
        checkPageNotFound("/auth/nosuch");
    } finally {
        rep.setInternationalizationEnabled(false);
        testRealm.update(rep);
    }
}
 
Example 3
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 4
Source File: AppInitiatedActionTotpSetupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void setupTotpModifiedPolicy() {
    RealmResource realm = testRealm();
    RealmRepresentation rep = realm.toRepresentation();
    rep.setOtpPolicyDigits(8);
    rep.setOtpPolicyType("hotp");
    rep.setOtpPolicyAlgorithm("HmacSHA256");
    realm.update(rep);
    try {
        loginPage.open();
        loginPage.clickRegister();
        registerPage.register("firstName", "lastName", "[email protected]", "setupTotpModifiedPolicy", "password", "password");

        doAIA();
        
        String pageSource = driver.getPageSource();

        assertTrue(pageSource.contains("FreeOTP"));
        assertFalse(pageSource.contains("Google Authenticator"));

        totpPage.clickManual();

        assertEquals("Type: Counter-based", driver.findElement(By.id("kc-totp-type")).getText());
        assertEquals("Algorithm: SHA256", driver.findElement(By.id("kc-totp-algorithm")).getText());
        assertEquals("Digits: 8", driver.findElement(By.id("kc-totp-digits")).getText());
        assertEquals("Counter: 0", driver.findElement(By.id("kc-totp-counter")).getText());
    } finally {
        rep.setOtpPolicyDigits(6);
        rep.setOtpPolicyType("totp");
        rep.setOtpPolicyAlgorithm("HmacSHA1");
        realm.update(rep);
    }
}
 
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#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 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_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 7
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 8
Source File: RequiredActionTotpSetupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void setupTotpModifiedPolicy() {
    RealmResource realm = testRealm();
    RealmRepresentation rep = realm.toRepresentation();
    rep.setOtpPolicyDigits(8);
    rep.setOtpPolicyType("hotp");
    rep.setOtpPolicyAlgorithm("HmacSHA256");
    realm.update(rep);
    try {
        loginPage.open();
        loginPage.clickRegister();
        registerPage.register("firstName", "lastName", "[email protected]", "setupTotpModifiedPolicy", "password", "password");

        String pageSource = driver.getPageSource();

        assertTrue(pageSource.contains("FreeOTP"));
        assertFalse(pageSource.contains("Google Authenticator"));

        totpPage.clickManual();

        assertEquals("Type: Counter-based", driver.findElement(By.id("kc-totp-type")).getText());
        assertEquals("Algorithm: SHA256", driver.findElement(By.id("kc-totp-algorithm")).getText());
        assertEquals("Digits: 8", driver.findElement(By.id("kc-totp-digits")).getText());
        assertEquals("Counter: 0", driver.findElement(By.id("kc-totp-counter")).getText());
    } finally {
        rep.setOtpPolicyDigits(6);
        rep.setOtpPolicyType("totp");
        rep.setOtpPolicyAlgorithm("HmacSHA1");
        realm.update(rep);
    }
}
 
Example 9
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 10
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 11
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void testDuplicateEmailSupport(RealmResource... realms) {
    log.info("testing duplicate email");
    for (RealmResource realm : realms) {
        RealmRepresentation rep = realm.toRepresentation();
        assertTrue("LoginWithEmailAllowed should be enabled.", rep.isLoginWithEmailAllowed());
        assertFalse("DuplicateEmailsAllowed should be disabled.", rep.isDuplicateEmailsAllowed());
    }
}
 
Example 12
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
@Test
@Order(6)
void shouldUpdateRealmAndNotRemoveUsers() {
    // Create Users
    doImport("06_update_realm_and_not_remove_user.json");

    RealmResource realmResource = keycloakProvider.get().realm(REALM_NAME);
    final RealmRepresentation createdRealm = realmResource.toRepresentation();
    assertThat(createdRealm.getRealm(), is(REALM_NAME));
    assertThat(createdRealm.isEnabled(), is(true));
    assertThat(realmResource.users().list(), is(hasSize(8)));
}
 
Example 13
Source File: ImportUsersIT.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
/**
 * https://github.com/adorsys/keycloak-config-cli/issues/68
 */

@Test
@Order(5)
void coverGitHubIssue68() {
    // Create Users
    doImport("05_1_issue_gh_68.json");
    // Update Users
    doImport("05_2_issue_gh_68.json");

    RealmResource realmResource = keycloakProvider.get().realm(REALM_NAME);
    final RealmRepresentation createdRealm = realmResource.toRepresentation();
    assertThat(createdRealm.getRealm(), is(REALM_NAME));
    assertThat(createdRealm.isEnabled(), is(true));
}
 
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
@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 16
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 17
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 18
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 19
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractFirstBrokerLoginTest#testLinkAccountByReauthentication_forgetPassword
 */
@Test
public void testLinkAccountByLogInAsUserAfterResettingPassword() throws InterruptedException {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setResetPasswordAllowed(true);

    realm.update(realmRep);

    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    String existingUser = createUser("consumer");
    UserResource providerUser = adminClient.realm(bc.providerRealmName()).users().get(userId);
    UserRepresentation userResource = providerUser.toRepresentation();

    userResource.setEmail(USER_EMAIL);
    userResource.setFirstName("FirstName");
    userResource.setLastName("LastName");

    providerUser.update(userResource);

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

    logInWithBroker(bc);

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

    configureSMTPServer();

    this.loginPage.resetPassword();
    this.loginPasswordResetPage.assertCurrent();
    this.loginPasswordResetPage.changePassword();
    assertEquals("You should receive an email shortly with further instructions.", this.loginPage.getSuccessMessage());
    assertEquals(1, MailServer.getReceivedMessages().length);
    MimeMessage message = MailServer.getLastReceivedMessage();
    String linkFromMail = assertEmailAndGetUrl(MailServerConfiguration.FROM, USER_EMAIL,
            "credentials", false);

    driver.navigate().to(linkFromMail.trim());

    // Need to update password now
    this.passwordUpdatePage.assertCurrent();
    this.passwordUpdatePage.changePassword("password", "password");

    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();
    assertNumFederatedIdentities(existingUser, 1);
}
 
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();
}