Java Code Examples for org.keycloak.common.util.Time#setOffset()

The following examples show how to use org.keycloak.common.util.Time#setOffset() . 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: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
public void testRestartSession(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    int started = Time.currentTime();
    UserSessionModel[] sessions = createSessions(session);

    Time.setOffset(100);

    UserSessionModel userSession = session.sessions().getUserSession(realm, sessions[0].getId());
    assertSession(userSession, session.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party");

    userSession.restartSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.6", "form", true, null, null);

    userSession = session.sessions().getUserSession(realm, sessions[0].getId());
    assertSession(userSession, session.users().getUserByUsername("user2", realm), "127.0.0.6", started + 100, started + 100);

    Time.setOffset(0);
}
 
Example 2
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
 public void testRemovingExpiredSession(KeycloakSession session) {
    UserSessionModel[] sessions = createSessions(session);
    try {
        Time.setOffset(3600000);
        UserSessionModel userSession = sessions[0];
        RealmModel realm = userSession.getRealm();
        session.sessions().removeExpired(realm);

        // Assert no exception is thrown here
        session.sessions().removeUserSession(realm, userSession);
    } finally {
        Time.setOffset(0);
        session.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
    }
}
 
Example 3
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 4
Source File: AdapterActionsFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest servletReq = (HttpServletRequest) request;
    HttpServletResponse servletResp = (HttpServletResponse) response;

    //Accept timeOffset as argument to enforce timeouts
    String timeOffsetParam = request.getParameter(TIME_OFFSET_PARAM);
    String resetDeploymentParam = request.getParameter(RESET_DEPLOYMENT_PARAM);

    if (timeOffsetParam != null && !timeOffsetParam.isEmpty()) {
        int timeOffset = Integer.parseInt(timeOffsetParam);
        log.infof("Time offset updated to %d for application %s", timeOffset, servletReq.getRequestURI());
        Time.setOffset(timeOffset);
        writeResponse(servletResp, "Offset set successfully");
    } else if (resetDeploymentParam != null && !resetDeploymentParam.isEmpty()) {
        AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) request.getServletContext().getAttribute(AdapterDeploymentContext.class.getName());

        Field field = Reflections.findDeclaredField(AdapterDeploymentContext.class, "deployment");
        Reflections.setAccessible(field);
        KeycloakDeployment deployment = (KeycloakDeployment) Reflections.getFieldValue(field, deploymentContext);

        Time.setOffset(0);
        deployment.setNotBefore(0);
        if (deployment.getPublicKeyLocator() instanceof JWKPublicKeyLocator) {
            deployment.setPublicKeyLocator(new JWKPublicKeyLocator());
        }

        log.infof("Restarted PublicKeyLocator, notBefore and timeOffset for application %s", servletReq.getRequestURI());
        writeResponse(servletResp, "Restarted PublicKeyLocator, notBefore and timeOffset successfully");
    } else {
        // Continue request
        chain.doFilter(request, response);
    }

}
 
Example 5
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testGetByClientPaginated(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    try {
        for (int i = 0; i < 25; i++) {
            Time.setOffset(i);
            UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0." + i, "form", false, null, null);
            AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, realm.getClientByClientId("test-app"), userSession);
            assertNotNull(clientSession);
            clientSession.setRedirectUri("http://redirect");
            clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, "state");
            clientSession.setTimestamp(userSession.getStarted());
            userSession.setLastSessionRefresh(userSession.getStarted());
        }
    } finally {
        Time.setOffset(0);
    }

    KeycloakTransaction transaction = session.getTransactionManager();
    if (!transaction.getRollbackOnly()) {
        transaction.commit();
    }

    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 0, 1, 1);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 0, 10, 10);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 10, 10, 10);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 20, 10, 5);
    assertPaginatedSession(session, realm, realm.getClientByClientId("test-app"), 30, 10, 0);
}
 
Example 6
Source File: TestingResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/time-offset")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> setTimeOffset(Map<String, String> time) {
    int offset = Integer.parseInt(time.get("offset"));
    Time.setOffset(offset);

    // Time offset was restarted
    if (offset == 0) {
        session.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
    }

    return getTimeOffset();
}
 
Example 7
Source File: AbstractKeycloakTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected String invokeTimeOffset(int offset) {
    // adminClient depends on Time.offset for auto-refreshing tokens
    Time.setOffset(offset);
    Map result = testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(offset)));
    return String.valueOf(result);
}
 
Example 8
Source File: InfinispanKeyStorageProviderTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
    Time.setOffset(0);
}
 
Example 9
Source File: InfinispanKeyStorageProviderTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@After
public void after() {
    Time.setOffset(0);
}