Java Code Examples for org.keycloak.representations.idm.RealmRepresentation#setAccessTokenLifespan()

The following examples show how to use org.keycloak.representations.idm.RealmRepresentation#setAccessTokenLifespan() . 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: KeycloakDevModeRealmResourceManager.java    From quarkus with Apache License 2.0 8 votes vote down vote up
private static RealmRepresentation createRealm(String name) {
    RealmRepresentation realm = new RealmRepresentation();

    realm.setRealm(name);
    realm.setEnabled(true);
    realm.setUsers(new ArrayList<>());
    realm.setClients(new ArrayList<>());
    realm.setSsoSessionMaxLifespan(2); // sec
    realm.setAccessTokenLifespan(3); // 3 seconds

    RolesRepresentation roles = new RolesRepresentation();
    List<RoleRepresentation> realmRoles = new ArrayList<>();

    roles.setRealm(realmRoles);
    realm.setRoles(roles);

    realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false));
    return realm;
}
 
Example 2
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static RealmRepresentation createRealm(String name) {
    RealmRepresentation realm = new RealmRepresentation();

    realm.setRealm(name);
    realm.setEnabled(true);
    realm.setUsers(new ArrayList<>());
    realm.setClients(new ArrayList<>());
    realm.setAccessTokenLifespan(3);

    RolesRepresentation roles = new RolesRepresentation();
    List<RoleRepresentation> realmRoles = new ArrayList<>();

    roles.setRealm(realmRoles);
    realm.setRoles(roles);

    realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false));
    realm.getRoles().getRealm().add(new RoleRepresentation("admin", null, false));
    realm.getRoles().getRealm().add(new RoleRepresentation("confidential", null, false));

    return realm;
}
 
Example 3
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> start() {

    try {

        RealmRepresentation realm = createRealm(KEYCLOAK_REALM);
        createRealmInKeycloak(realm);
        realms.add(realm);

        RealmRepresentation logoutRealm = createRealm("logout-realm");
        // revoke refresh tokens so that they can only be used once
        logoutRealm.setRevokeRefreshToken(true);
        logoutRealm.setRefreshTokenMaxReuse(0);
        logoutRealm.setSsoSessionMaxLifespan(15);
        logoutRealm.setAccessTokenLifespan(5);
        createRealmInKeycloak(logoutRealm);
        realms.add(logoutRealm);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return Collections.emptyMap();
}
 
Example 4
Source File: AbstractAdvancedBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Refers to in old testsuite: org.keycloak.testsuite.broker.OIDCKeyCloakServerBrokerBasicTest#testLogoutWorksWithTokenTimeout()
 */
@Test
public void testLogoutWorksWithTokenTimeout() {
    try {
        updateExecutions(AbstractBrokerTest::enableUpdateProfileOnFirstLogin);
        RealmRepresentation realm = adminClient.realm(bc.providerRealmName()).toRepresentation();
        assertNotNull(realm);
        realm.setAccessTokenLifespan(1);
        adminClient.realm(bc.providerRealmName()).update(realm);
        IdentityProviderRepresentation idp = adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).toRepresentation();
        idp.getConfig().put("backchannelSupported", "false");
        adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).update(idp);
        Time.setOffset(2);
        driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
        logInWithBroker(bc);
        waitForPage(driver, "update account information", false);
        updateAccountInformationPage.assertCurrent();
        updateAccountInformationPage.updateAccountInformation("FirstName", "LastName");
        accountPage.logOut();
        waitForPage(driver, "log in to", true);
        log.debug("Logging in");
        assertTrue(this.driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/protocol/openid-connect/auth"));
    } finally {
        Time.setOffset(0);
    }
}
 
Example 5
Source File: KeycloakRealmResourceManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static RealmRepresentation createRealm(String name) {
    RealmRepresentation realm = new RealmRepresentation();

    realm.setRealm(name);
    realm.setEnabled(true);
    realm.setUsers(new ArrayList<>());
    realm.setClients(new ArrayList<>());
    realm.setSsoSessionMaxLifespan(3); // sec
    realm.setAccessTokenLifespan(4); // 3 seconds

    RolesRepresentation roles = new RolesRepresentation();
    List<RoleRepresentation> realmRoles = new ArrayList<>();

    roles.setRealm(realmRoles);
    realm.setRoles(roles);

    realm.getRoles().getRealm().add(new RoleRepresentation("user", null, false));
    realm.getRoles().getRealm().add(new RoleRepresentation("admin", null, false));
    realm.getRoles().getRealm().add(new RoleRepresentation("confidential", null, false));

    realm.getClients().add(createClient("quarkus-app"));
    realm.getClients().add(createClientJwt("quarkus-app-jwt"));
    realm.getUsers().add(createUser("alice", "user"));
    realm.getUsers().add(createUser("admin", "user", "admin"));
    realm.getUsers().add(createUser("jdoe", "user", "confidential"));

    return realm;
}
 
Example 6
Source File: AbstractBasePhotozExampleAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addAdapterTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation realm = loadRealm(new File(TEST_APPS_HOME_DIR + "/photoz/photoz-realm.json"));

    realm.setAccessTokenLifespan(30 + TOKEN_LIFESPAN_LEEWAY); // seconds

    testRealms.add(realm);
}
 
Example 7
Source File: OIDCPublicKeyRotationAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicKeyCacheTtl() {
    // increase accessTokenLifespan to 1200
    RealmRepresentation demoRealm = adminClient.realm(DEMO).toRepresentation();
    demoRealm.setAccessTokenLifespan(1200);
    adminClient.realm(DEMO).update(demoRealm);

    // authenticate in tokenMinTTL app
    loginToTokenMinTtlApp();
    String accessTokenString = tokenMinTTLPage.getAccessTokenString();

    // Send REST request to customer-db app. I should be successfully authenticated
    int status = invokeRESTEndpoint(accessTokenString);
    Assert.assertEquals(200, status);

    // Re-generate realm public key and remove the old key
    String oldActiveKeyProviderId = getActiveKeyProvider();
    generateNewRealmKey();
    adminClient.realm(DEMO).components().component(oldActiveKeyProviderId).remove();

    // Send REST request to the customer-db app. Should be still succcessfully authenticated as the JWKPublicKeyLocator cache is still valid
    status = invokeRESTEndpoint(accessTokenString);
    Assert.assertEquals(200, status);

    // TimeOffset to 900 on the REST app side. Token is still valid (1200) but JWKPublicKeyLocator should try to download new key (public-key-cache-ttl=600)
    setAdapterAndServerTimeOffset(900, customerDb.toString() + "/unsecured/foo");

    // Send REST request. New request to the publicKey cache should be sent, and key is no longer returned as token contains the old kid
    status = invokeRESTEndpoint(accessTokenString);
    Assert.assertEquals(401, status);

    // Revert public keys change and time offset
    resetKeycloakDeploymentForAdapter(customerDb.toString() + "/unsecured/foo");
    resetKeycloakDeploymentForAdapter(tokenMinTTLPage.toString() + "/unsecured/foo");
}
 
Example 8
Source File: SessionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    super.addTestRealms(testRealms);
    RealmRepresentation realm = testRealms.get(0);

    // in seconds
    realm.setSsoSessionIdleTimeout(1);
    realm.setAccessTokenLifespan(10);
}
 
Example 9
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testTokenInCookieRefresh() {
    log.debug("Set token timeout 10 sec");
    RealmRepresentation demo = adminClient.realm("demo").toRepresentation();
    int originalTokenTimeout = demo.getAccessTokenLifespan();
    demo.setAccessTokenLifespan(10);
    adminClient.realm("demo").update(demo);

    try {
        log.debug("login to customer-cookie-portal");
        String tokenCookie1 = loginToCustomerCookiePortal();

        log.debug("Simulate waiting 12 seconds");
        setAdapterAndServerTimeOffset(12, customerCookiePortal.toString());

        log.debug("assert cookie was refreshed");
        customerCookiePortal.navigateTo();
        assertCurrentUrlEquals(customerCookiePortal);
        assertLogged();
        String tokenCookie2 = driver.manage().getCookieNamed(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE).getValue();
        assertNotEquals(tokenCookie1, tokenCookie2);
        
        log.debug("login to 2nd app and logout from it");
        customerPortal.navigateTo();
        assertCurrentUrlEquals(customerPortal);
        assertLogged();
        
        driver.navigate().to(customerPortal.logout().toASCIIString());
        WaitUtils.waitUntilElement(By.id("customer_portal_logout")).is().present();
        customerPortal.navigateTo();
        assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
        
        log.debug("Simulate another 12 seconds");
        setAdapterAndServerTimeOffset(24, customerCookiePortal.toString());
        
        log.debug("assert not logged in customer-cookie-portal");
        customerCookiePortal.navigateTo();
        assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    } finally {
        log.debug("Set token timeout to original");
        demo.setAccessTokenLifespan(originalTokenTimeout);
        adminClient.realm("demo").update(demo);
        
        log.debug("reset time offset");
        setAdapterAndServerTimeOffset(0, customerCookiePortal.toString().concat("/unsecured"));
    }
}
 
Example 10
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 11
Source File: OIDCPublicKeyRotationAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testPublicKeyCacheInvalidatedWhenPushedNotBefore() {
    driver.manage().timeouts().pageLoadTimeout(1000, TimeUnit.SECONDS);
    String customerDBUnsecuredUrl = customerDb.getUriBuilder().clone().path("unsecured").path("foo").build().toASCIIString();
    String customerDBUrlNoTrailSlash = customerDb.getUriBuilder().build().toASCIIString();
    customerDBUrlNoTrailSlash = customerDBUrlNoTrailSlash.substring(0, customerDBUrlNoTrailSlash.length() - 1);
    String tokenMinTTLUnsecuredUrl = tokenMinTTLPage.getUriBuilder().clone().path("unsecured").path("foo").build().toASCIIString();

    // increase accessTokenLifespan to 1200
    RealmRepresentation demoRealm = adminClient.realm(DEMO).toRepresentation();
    demoRealm.setAccessTokenLifespan(1200);
    adminClient.realm(DEMO).update(demoRealm);

    // authenticate in tokenMinTTL app
    loginToTokenMinTtlApp();
    String accessTokenString = tokenMinTTLPage.getAccessTokenString();

    // Generate new realm public key
    String oldActiveKeyProviderId = getActiveKeyProvider();

    generateNewRealmKey();

    // Send REST request to customer-db app. It should be successfully authenticated even that token is signed by the old key
    int status = invokeRESTEndpoint(accessTokenString);
    Assert.assertEquals(200, status);

    // Remove the old realm key now
    adminClient.realm(DEMO).components().component(oldActiveKeyProviderId).remove();

    // Set some offset to ensure pushing notBefore will pass
    setAdapterAndServerTimeOffset(130, customerDBUnsecuredUrl, tokenMinTTLUnsecuredUrl);

    // Send notBefore policy from the realm
    demoRealm.setNotBefore(Time.currentTime() - 1);
    adminClient.realm(DEMO).update(demoRealm);
    GlobalRequestResult result = adminClient.realm(DEMO).pushRevocation();
    Assert.assertTrue(result.getSuccessRequests().contains(customerDBUrlNoTrailSlash));

    // Send REST request. New request to the publicKey cache should be sent, and key is no longer returned as token contains the old kid
    status = invokeRESTEndpoint(accessTokenString);
    Assert.assertEquals(401, status);

    // Revert public keys change and time offset
    resetKeycloakDeploymentForAdapter(customerDBUnsecuredUrl);
    resetKeycloakDeploymentForAdapter(tokenMinTTLUnsecuredUrl);
}