org.keycloak.common.util.Time Java Examples

The following examples show how to use org.keycloak.common.util.Time. 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: UpdatePassword.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void evaluateTriggers(RequiredActionContext context) {
    int daysToExpirePassword = context.getRealm().getPasswordPolicy().getDaysToExpirePassword();
    if(daysToExpirePassword != -1) {
        PasswordCredentialProvider passwordProvider = (PasswordCredentialProvider)context.getSession().getProvider(CredentialProvider.class, PasswordCredentialProviderFactory.PROVIDER_ID);
        CredentialModel password = passwordProvider.getPassword(context.getRealm(), context.getUser());
        if (password != null) {
            if(password.getCreatedDate() == null) {
                context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
                logger.debug("User is required to update password");
            } else {
                long timeElapsed = Time.toMillis(Time.currentTime()) - password.getCreatedDate();
                long timeToExpire = TimeUnit.DAYS.toMillis(daysToExpirePassword);

                if(timeElapsed > timeToExpire) {
                    context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
                    logger.debug("User is required to update password");
                }
            }
        }
    }
}
 
Example #2
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public synchronized AccessTokenResponse refreshToken() {
    Form form = new Form().param(GRANT_TYPE, REFRESH_TOKEN)
                          .param(REFRESH_TOKEN, currentToken.getRefreshToken());

    if (config.isPublicClient()) {
        form.param(CLIENT_ID, config.getClientId());
    }

    try {
        int requestTime = Time.currentTime();

        currentToken = tokenService.refreshToken(config.getRealm(), form.asMap());
        expirationTime = requestTime + currentToken.getExpiresIn();
        return currentToken;
    } catch (BadRequestException e) {
        return grantToken();
    }
}
 
Example #3
Source File: JWKPublicKeyLocator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public PublicKey getPublicKey(String kid, KeycloakDeployment deployment) {
    int minTimeBetweenRequests = deployment.getMinTimeBetweenJwksRequests();
    int publicKeyCacheTtl = deployment.getPublicKeyCacheTtl();
    int currentTime = Time.currentTime();

    // Check if key is in cache.
    PublicKey publicKey = lookupCachedKey(publicKeyCacheTtl, currentTime, kid);
    if (publicKey != null) {
        return publicKey;
    }

    // Check if we are allowed to send request
    synchronized (this) {
        currentTime = Time.currentTime();
        if (currentTime > lastRequestTime + minTimeBetweenRequests) {
            sendRequest(deployment);
            lastRequestTime = currentTime;
        } else {
            log.debug("Won't send request to realm jwks url. Last request time was " + lastRequestTime);
        }

        return lookupCachedKey(publicKeyCacheTtl, currentTime, kid);
    }
}
 
Example #4
Source File: AbstractSessionCacheCommand.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRunCacheCommand(KeycloakSession session, Cache<String, SessionEntityWrapper> cache) {
    String realmName = getArg(1);
    int count = getIntArg(2);
    int batchCount = getIntArg(3);

    BatchTaskRunner.runInBatches(0, count, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession batchSession, int firstInIteration, int countInIteration) -> {
        for (int i=0 ; i<countInIteration ; i++) {
            UserSessionEntity userSession = new UserSessionEntity();
            String id = KeycloakModelUtils.generateId();

            userSession.setId(id);
            userSession.setRealmId(realmName);

            userSession.setLastSessionRefresh(Time.currentTime());
            cache.put(id, new SessionEntityWrapper(userSession));
        }

        log.infof("Created '%d' sessions started from offset '%d'", countInIteration, firstInIteration);
    });

    log.infof("Created all '%d' sessions", count);
}
 
Example #5
Source File: ClientResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Register a cluster node with the client
 *
 * Manually register cluster node to this client - usually it's not needed to call this directly as adapter should handle
 * by sending registration request to Keycloak
 *
 * @param formParams
 */
@Path("nodes")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void registerNode(Map<String, String> formParams) {
    auth.clients().requireConfigure(client);

    String node = formParams.get("node");
    if (node == null) {
        throw new BadRequestException("Node not found in params");
    }
    
    ReservedCharValidator.validate(node);
    
    if (logger.isDebugEnabled()) logger.debug("Register node: " + node);
    client.registerNode(node, Time.currentTime());
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.CLUSTER_NODE).resourcePath(session.getContext().getUri(), node).success();
}
 
Example #6
Source File: AuthUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String getSignedRequestToken(String keystore, String storePass, String keyPass, String alias, int sigLifetime, String clientId, String realmInfoUrl) {

        KeyPair keypair = KeystoreUtil.loadKeyPairFromKeystore(keystore, storePass, keyPass, alias, KeystoreUtil.KeystoreFormat.JKS);

        JsonWebToken reqToken = new JsonWebToken();
        reqToken.id(UUID.randomUUID().toString());
        reqToken.issuer(clientId);
        reqToken.subject(clientId);
        reqToken.audience(realmInfoUrl);

        int now = Time.currentTime();
        reqToken.issuedAt(now);
        reqToken.expiration(now + sigLifetime);
        reqToken.notBefore(now);

        String signedRequestToken = new JWSBuilder()
                .jsonContent(reqToken)
                .rsa256(keypair.getPrivate());
        return signedRequestToken;
    }
 
Example #7
Source File: ConcurrencyDistributedRemoveSessionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static SessionEntityWrapper<UserSessionEntity> createSessionEntity(String sessionId) {
    // Create 100 initial sessions
    UserSessionEntity session = new UserSessionEntity();
    session.setId(sessionId);
    session.setRealmId("foo");
    session.setBrokerSessionId("!23123123");
    session.setBrokerUserId(null);
    session.setUser("foo");
    session.setLoginUsername("foo");
    session.setIpAddress("123.44.143.178");
    session.setStarted(Time.currentTime());
    session.setLastSessionRefresh(Time.currentTime());

    AuthenticatedClientSessionEntity clientSession = new AuthenticatedClientSessionEntity(UUID.randomUUID());
    clientSession.setAuthMethod("saml");
    clientSession.setAction("something");
    clientSession.setTimestamp(1234);
    session.getAuthenticatedClientSessions().put(CLIENT_1_UUID.toString(), clientSession.getId());

    SessionEntityWrapper<UserSessionEntity> wrappedSession = new SessionEntityWrapper<>(session);
    return wrappedSession;
}
 
Example #8
Source File: JpaUpdate4_7_0_OfflineSessionsTimestamps.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String offlineUserSessionsTableName = database.correctObjectName("OFFLINE_USER_SESSION", Table.class);

    try {
        int currentTime = Time.currentTime();

        UpdateStatement updateStatement = new UpdateStatement(null, null, offlineUserSessionsTableName)
                .addNewColumnValue("LAST_SESSION_REFRESH", currentTime);

        statements.add(updateStatement);

        confirmationMessage.append("Updated column LAST_SESSION_REFRESH in OFFLINE_USER_SESSION table with time " + currentTime);
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #9
Source File: CustomLockService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void waitForLock(LockDatabaseChangeLogStatement lockStmt) {
    boolean locked = false;
    long startTime = Time.toMillis(Time.currentTime());
    long timeToGiveUp = startTime + (getChangeLogLockWaitTime());
    boolean nextAttempt = true;

    while (nextAttempt) {
        locked = acquireLock(lockStmt);
        if (!locked) {
            int remainingTime = ((int)(timeToGiveUp / 1000)) - Time.currentTime();
            if (remainingTime > 0) {
                log.debugf("Will try to acquire log another time. Remaining time: %d seconds", remainingTime);
            } else {
                nextAttempt = false;
            }
        } else {
            nextAttempt = false;
        }
    }

    if (!locked) {
        int timeout = ((int)(getChangeLogLockWaitTime() / 1000));
        throw new IllegalStateException("Could not acquire change log lock within specified timeout " + timeout + " seconds.  Currently locked by other transaction");
    }
}
 
Example #10
Source File: JpaUserSessionPersisterProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void removeExpired(RealmModel realm) {
    int expiredOffline = Time.currentTime() - realm.getOfflineSessionIdleTimeout() - SessionTimeoutHelper.PERIODIC_CLEANER_IDLE_TIMEOUT_WINDOW_SECONDS;

    String offlineStr = offlineToString(true);

    logger.tracef("Trigger removing expired user sessions for realm '%s'", realm.getName());

    int cs = em.createNamedQuery("deleteExpiredClientSessions")
            .setParameter("realmId", realm.getId())
            .setParameter("lastSessionRefresh", expiredOffline)
            .setParameter("offline", offlineStr)
            .executeUpdate();

    int us = em.createNamedQuery("deleteExpiredUserSessions")
            .setParameter("realmId", realm.getId())
            .setParameter("lastSessionRefresh", expiredOffline)
            .setParameter("offline", offlineStr)
            .executeUpdate();

    logger.debugf("Removed %d expired user sessions and %d expired client sessions in realm '%s'", us, cs, realm.getName());

}
 
Example #11
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String getIDTokenForLogout(KeycloakSession session, UserSessionModel userSession) {
    String tokenExpirationString = userSession.getNote(FEDERATED_TOKEN_EXPIRATION);
    long exp = tokenExpirationString == null ? 0 : Long.parseLong(tokenExpirationString);
    int currentTime = Time.currentTime();
    if (exp > 0 && currentTime > exp) {
        String response = refreshTokenForLogout(session, userSession);
        AccessTokenResponse tokenResponse = null;
        try {
            tokenResponse = JsonSerialization.readValue(response, AccessTokenResponse.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tokenResponse.getIdToken();
    } else {
        return userSession.getNote(FEDERATED_ID_TOKEN);

    }
}
 
Example #12
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count) {
    RealmEntity realmEntity = em.find(RealmEntity.class, realm.getId());

    ClientInitialAccessEntity entity = new ClientInitialAccessEntity();
    entity.setId(KeycloakModelUtils.generateId());
    entity.setRealm(realmEntity);

    entity.setCount(count);
    entity.setRemainingCount(count);

    int currentTime = Time.currentTime();
    entity.setTimestamp(currentTime);
    entity.setExpiration(expiration);

    em.persist(entity);

    return entityToModel(entity);
}
 
Example #13
Source File: IdentityServiceRemoteUserMapperTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Utility method to create tokens for testing.
 * 
 * @param expired Determines whether to create an expired JWT
 * @return The string representation of the JWT
 */
private String generateToken(boolean expired) throws Exception
{
    String issuerUrl = this.identityServiceConfig.getAuthServerUrl() + "/realms/" + this.identityServiceConfig.getRealm();
    
    AccessToken token = new AccessToken();
    token.type("Bearer");
    token.id("1234");
    token.subject("abc123");
    token.issuer(issuerUrl);
    token.setPreferredUsername(TEST_USER_USERNAME);
    token.setEmail(TEST_USER_EMAIL);
    token.setGivenName("Joe");
    token.setFamilyName("Bloggs");
    
    if (expired)
    {
        token.expiration(Time.currentTime() - 60);
    }

    String jwt = new JWSBuilder()
            .jsonContent(token)
            .rsa256(keyPair.getPrivate());
    
    return jwt;
}
 
Example #14
Source File: CASLoginProtocol.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@Override
public Response authenticated(AuthenticationSessionModel authSession, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();

    String service = authSession.getRedirectUri();
    //TODO validate service

    OAuth2Code codeData = new OAuth2Code(UUID.randomUUID(),
            Time.currentTime() + userSession.getRealm().getAccessCodeLifespan(),
            null, null, authSession.getRedirectUri(), null, null);
    String code = OAuth2CodeParser.persistCode(session, clientSession, codeData);

    KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(service);
    uriBuilder.queryParam(TICKET_RESPONSE_PARAM, SERVICE_TICKET_PREFIX + code);

    URI redirectUri = uriBuilder.build();

    Response.ResponseBuilder location = Response.status(302).location(redirectUri);
    return location.build();
}
 
Example #15
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponse grantToken() {
    Form form = new Form().param(GRANT_TYPE, accessTokenGrantType);
    if (PASSWORD.equals(accessTokenGrantType)) {
        form.param("username", config.getUsername())
            .param("password", config.getPassword());
    }

    if (config.isPublicClient()) {
        form.param(CLIENT_ID, config.getClientId());
    }

    int requestTime = Time.currentTime();
    synchronized (this) {
        currentToken = tokenService.grantToken(config.getRealm(), form.asMap());
        expirationTime = requestTime + currentToken.getExpiresIn();
    }
    return currentToken;
}
 
Example #16
Source File: DistributedCacheConcurrentWritesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static SessionEntityWrapper<UserSessionEntity> createEntityInstance(String id) {
    // Create initial item
    UserSessionEntity session = new UserSessionEntity();
    session.setId(id);
    session.setRealmId("foo");
    session.setBrokerSessionId("!23123123");
    session.setBrokerUserId(null);
    session.setUser("foo");
    session.setLoginUsername("foo");
    session.setIpAddress("123.44.143.178");
    session.setStarted(Time.currentTime());
    session.setLastSessionRefresh(Time.currentTime());

    AuthenticatedClientSessionEntity clientSession = new AuthenticatedClientSessionEntity(UUID.randomUUID());
    clientSession.setAuthMethod("saml");
    clientSession.setAction("something");
    clientSession.setTimestamp(1234);
    session.getAuthenticatedClientSessions().put("foo-client", clientSession.getId());

    return new SessionEntityWrapper<>(session);
}
 
Example #17
Source File: UserSessionManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void createOrUpdateOfflineSession(AuthenticatedClientSessionModel clientSession, UserSessionModel userSession) {
    UserModel user = userSession.getUser();

    // Create and persist offline userSession if we don't have one
    UserSessionModel offlineUserSession = kcSession.sessions().getOfflineUserSession(clientSession.getRealm(), userSession.getId());
    if (offlineUserSession == null) {
        offlineUserSession = createOfflineUserSession(user, userSession);
    } else {
        // update lastSessionRefresh but don't need to persist
        offlineUserSession.setLastSessionRefresh(Time.currentTime());
    }

    // Create and persist clientSession
    AuthenticatedClientSessionModel offlineClientSession = offlineUserSession.getAuthenticatedClientSessionByClient(clientSession.getClient().getId());
    if (offlineClientSession == null) {
        createOfflineClientSession(user, clientSession, offlineUserSession);
    }
}
 
Example #18
Source File: InfinispanPublicKeyStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public PublicKeysEntry call() throws Exception {
    PublicKeysEntry entry = keys.get(modelKey);

    int lastRequestTime = entry==null ? 0 : entry.getLastRequestTime();
    int currentTime = Time.currentTime();

    // Check again if we are allowed to send request. There is a chance other task was already finished and removed from tasksInProgress in the meantime.
    if (currentTime > lastRequestTime + minTimeBetweenRequests) {

        Map<String, KeyWrapper> publicKeys = delegate.loadKeys();

        if (log.isDebugEnabled()) {
            log.debugf("Public keys retrieved successfully for model %s. New kids: %s", modelKey, publicKeys.keySet().toString());
        }

        entry = new PublicKeysEntry(currentTime, publicKeys);

        keys.put(modelKey, entry);
    }
    return entry;
}
 
Example #19
Source File: InfinispanClusterProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected int initClusterStartupTime(KeycloakSession session) {
    Integer existingClusterStartTime = (Integer) crossDCAwareCacheFactory.getCache().get(InfinispanClusterProvider.CLUSTER_STARTUP_TIME_KEY);
    if (existingClusterStartTime != null) {
        logger.debugf("Loaded cluster startup time: %s", Time.toDate(existingClusterStartTime).toString());
        return existingClusterStartTime;
    } else {
        // clusterStartTime not yet initialized. Let's try to put our startupTime
        int serverStartTime = (int) (session.getKeycloakSessionFactory().getServerStartupTimestamp() / 1000);

        existingClusterStartTime = putIfAbsentWithRetries(crossDCAwareCacheFactory, InfinispanClusterProvider.CLUSTER_STARTUP_TIME_KEY, serverStartTime, -1);
        if (existingClusterStartTime == null) {
            logger.debugf("Initialized cluster startup time to %s", Time.toDate(serverStartTime).toString());
            return serverStartTime;
        } else {
            logger.debugf("Loaded cluster startup time: %s", Time.toDate(existingClusterStartTime).toString());
            return existingClusterStartTime;
        }
    }
}
 
Example #20
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testOIDCParamsForwarding() {
    // test login to customer-portal which does a bearer request to customer-db
    securePortal.navigateTo();
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    waitForPageToLoad();
    assertCurrentUrlStartsWith(securePortal);
    assertLogged();

    int currentTime = Time.currentTime();
    try {
        setAdapterAndServerTimeOffset(10, securePortal.toString());

        // Test I need to reauthenticate with prompt=login
        String appUri = tokenMinTTLPage.getUriBuilder().queryParam(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN).build().toString();
        URLUtils.navigateToUri(appUri);
        assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
        testRealmLoginPage.form().login("[email protected]", "password");
        AccessToken token = tokenMinTTLPage.getAccessToken();
        int authTime = token.getAuthTime();
        assertThat(authTime, is(greaterThanOrEqualTo(currentTime + 10)));
    } finally {
        setAdapterAndServerTimeOffset(0, securePortal.toString());
    }
}
 
Example #21
Source File: OfflinePersistentUserSessionLoader.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public OfflinePersistentWorkerResult loadSessions(KeycloakSession session, OfflinePersistentLoaderContext loaderContext, OfflinePersistentWorkerContext ctx) {
    int first = ctx.getWorkerId() * sessionsPerSegment;

    log.tracef("Loading sessions for segment=%d createdOn=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastCreatedOn(), ctx.getLastSessionId());

    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
    List<UserSessionModel> sessions = persister.loadUserSessions(first, sessionsPerSegment, true, ctx.getLastCreatedOn(), ctx.getLastSessionId());

    log.tracef("Sessions loaded from DB - segment=%d createdOn=%d lastSessionId=%s", ctx.getSegment(), ctx.getLastCreatedOn(), ctx.getLastSessionId());

    UserSessionModel lastSession = null;
    if (!sessions.isEmpty()) {
        lastSession = sessions.get(sessions.size() - 1);

        // Save to memory/infinispan
        session.sessions().importUserSessions(sessions, true);
    }

    int lastCreatedOn = lastSession==null ? Time.currentTime() + 100000 : lastSession.getStarted();
    String lastSessionId = lastSession==null ? FIRST_SESSION_ID : lastSession.getId();

    log.tracef("Sessions imported to infinispan - segment: %d, lastCreatedOn: %d, lastSessionId: %s", ctx.getSegment(), lastCreatedOn, lastSessionId);

    return new OfflinePersistentWorkerResult(true, ctx.getSegment(), ctx.getWorkerId(), lastCreatedOn, lastSessionId);
}
 
Example #22
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static AuthResult authenticateIdentityCookie(KeycloakSession session, RealmModel realm, boolean checkActive) {
    Cookie cookie = CookieHelper.getCookie(session.getContext().getRequestHeaders().getCookies(), KEYCLOAK_IDENTITY_COOKIE);
    if (cookie == null || "".equals(cookie.getValue())) {
        logger.debugv("Could not find cookie: {0}", KEYCLOAK_IDENTITY_COOKIE);
        return null;
    }

    String tokenString = cookie.getValue();
    AuthResult authResult = verifyIdentityToken(session, realm, session.getContext().getUri(), session.getContext().getConnection(), checkActive, false, true, tokenString, session.getContext().getRequestHeaders(), VALIDATE_IDENTITY_COOKIE);
    if (authResult == null) {
        expireIdentityCookie(realm, session.getContext().getUri(), session.getContext().getConnection());
        expireOldIdentityCookie(realm, session.getContext().getUri(), session.getContext().getConnection());
        return null;
    }
    authResult.getSession().setLastSessionRefresh(Time.currentTime());
    return authResult;
}
 
Example #23
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotBeforeBad() {
    token.notBefore(Time.currentTime() + 100);

    String encoded = new JWSBuilder()
            .jsonContent(token)
            .rsa256(idpPair.getPrivate());

    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
        Assert.fail();
    } catch (VerificationException ignored) {
        System.out.println(ignored.getMessage());
    }
}
 
Example #24
Source File: RealmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void pushNotBefore() {
    setupTestAppAndUser();

    int time = Time.currentTime() - 60;

    RealmRepresentation rep = realm.toRepresentation();
    rep.setNotBefore(time);
    realm.update(rep);
    assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, Matchers.nullValue(String.class), rep, ResourceType.REALM);

    GlobalRequestResult globalRequestResult = realm.pushRevocation();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "push-revocation", globalRequestResult, ResourceType.REALM);

    assertThat(globalRequestResult.getSuccessRequests(), containsInAnyOrder(oauth.AUTH_SERVER_ROOT + "/realms/master/app/admin"));
    assertNull(globalRequestResult.getFailedRequests());

    PushNotBeforeAction adminPushNotBefore = testingClient.testApp().getAdminPushNotBefore();
    assertEquals(time, adminPushNotBefore.getNotBefore());
}
 
Example #25
Source File: RealmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void pushNotBeforeWithSamlApp() {
    setupTestAppAndUser();
    setupTestSamlApp();

    int time = Time.currentTime() - 60;

    RealmRepresentation rep = realm.toRepresentation();
    rep.setNotBefore(time);
    realm.update(rep);
    assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, Matchers.nullValue(String.class), rep, ResourceType.REALM);

    GlobalRequestResult globalRequestResult = realm.pushRevocation();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "push-revocation", globalRequestResult, ResourceType.REALM);

    assertThat(globalRequestResult.getSuccessRequests(), containsInAnyOrder(oauth.AUTH_SERVER_ROOT + "/realms/master/app/admin"));
    assertThat(globalRequestResult.getFailedRequests(), containsInAnyOrder(oauth.AUTH_SERVER_ROOT + "/realms/master/saml-app/saml"));

    PushNotBeforeAction adminPushNotBefore = testingClient.testApp().getAdminPushNotBefore();
    assertEquals(time, adminPushNotBefore.getNotBefore());
}
 
Example #26
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Response finishOrRedirectToPostBrokerLogin(AuthenticationSessionModel authSession, BrokeredIdentityContext context, boolean wasFirstBrokerLogin, ClientSessionCode<AuthenticationSessionModel> clientSessionCode) {
    String postBrokerLoginFlowId = context.getIdpConfig().getPostBrokerLoginFlowId();
    if (postBrokerLoginFlowId == null) {

        logger.debugf("Skip redirect to postBrokerLogin flow. PostBrokerLogin flow not set for identityProvider '%s'.", context.getIdpConfig().getAlias());
        return afterPostBrokerLoginFlowSuccess(authSession, context, wasFirstBrokerLogin, clientSessionCode);
    } else {

        logger.debugf("Redirect to postBrokerLogin flow after authentication with identityProvider '%s'.", context.getIdpConfig().getAlias());

        authSession.getParentSession().setTimestamp(Time.currentTime());

        SerializedBrokeredIdentityContext ctx = SerializedBrokeredIdentityContext.serialize(context);
        ctx.saveToAuthenticationSession(authSession, PostBrokerLoginConstants.PBL_BROKERED_IDENTITY_CONTEXT);

        authSession.setAuthNote(PostBrokerLoginConstants.PBL_AFTER_FIRST_BROKER_LOGIN, String.valueOf(wasFirstBrokerLogin));

        URI redirect = LoginActionsService.postBrokerLoginProcessor(session.getContext().getUri())
                .queryParam(Constants.CLIENT_ID, authSession.getClient().getClientId())
                .queryParam(Constants.TAB_ID, authSession.getTabId())
                .build(realmModel.getName());
        return Response.status(302).location(redirect).build();
    }
}
 
Example #27
Source File: InfinispanUserSessionProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
void updateSessionEntity(UserSessionEntity entity, RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
    entity.setRealmId(realm.getId());
    entity.setUser(user.getId());
    entity.setLoginUsername(loginUsername);
    entity.setIpAddress(ipAddress);
    entity.setAuthMethod(authMethod);
    entity.setRememberMe(rememberMe);
    entity.setBrokerSessionId(brokerSessionId);
    entity.setBrokerUserId(brokerUserId);

    int currentTime = Time.currentTime();

    entity.setStarted(currentTime);
    entity.setLastSessionRefresh(currentTime);


}
 
Example #28
Source File: JWTClientSecretCredentialsProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    // According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication">OIDC's client authentication spec</a>,
    // JWT claims is the same as one by private_key_jwt

    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    // the same as in KEYCLOAK-2986, JWTClientCredentialsProvider's timeout field
    reqToken.expiration(now + 10);
    reqToken.notBefore(now);
    return reqToken;
}
 
Example #29
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 #30
Source File: XMLTimeUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a XMLGregorianCalendar in the timezone specified. If the timezone is not valid, then the timezone falls
 * back to
 * "GMT"
 *
 * @param timezone
 *
 * @return
 */
public static XMLGregorianCalendar getIssueInstant(String timezone) {
    TimeZone tz = TimeZone.getTimeZone(timezone);
    DatatypeFactory dtf;
    dtf = DATATYPE_FACTORY.get();

    GregorianCalendar gc = new GregorianCalendar(tz);
    XMLGregorianCalendar xgc = dtf.newXMLGregorianCalendar(gc);

    Long offsetMilis = TimeUnit.MILLISECONDS.convert(Time.getOffset(), TimeUnit.SECONDS);
    if (offsetMilis != 0) {
        if (logger.isDebugEnabled()) logger.debug(XMLTimeUtil.class.getName() + " timeOffset: " + offsetMilis);
        xgc.add(parseAsDuration(offsetMilis.toString()));
    }
    if (logger.isDebugEnabled()) logger.debug(XMLTimeUtil.class.getName() + " issueInstant: " + xgc.toString());
    return xgc;
}