org.keycloak.models.UserSessionModel Java Examples

The following examples show how to use org.keycloak.models.UserSessionModel. 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 testUpdateClientSessionInSameTransaction(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    String userSessionId = sessions[0].getId();
    String clientUUID = realm.getClientByClientId("test-app").getId();

    UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(clientUUID);

    clientSession.setAction(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name());
    clientSession.setNote("foo", "bar");

    AuthenticatedClientSessionModel updated = session.sessions().getUserSession(realm, userSessionId).getAuthenticatedClientSessionByClient(clientUUID);
    assertEquals(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name(), updated.getAction());
    assertEquals("bar", updated.getNote("foo"));
}
 
Example #2
Source File: JpaUserSessionPersisterProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void createUserSession(UserSessionModel userSession, boolean offline) {
    PersistentUserSessionAdapter adapter = new PersistentUserSessionAdapter(userSession);
    PersistentUserSessionModel model = adapter.getUpdatedModel();

    PersistentUserSessionEntity entity = new PersistentUserSessionEntity();
    entity.setUserSessionId(model.getUserSessionId());
    entity.setCreatedOn(model.getStarted());
    entity.setRealmId(adapter.getRealm().getId());
    entity.setUserId(adapter.getUser().getId());
    String offlineStr = offlineToString(offline);
    entity.setOffline(offlineStr);
    entity.setLastSessionRefresh(model.getLastSessionRefresh());
    entity.setData(model.getData());
    em.persist(entity);
    em.flush();
}
 
Example #3
Source File: SAMLAudienceProtocolMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseType transformLoginResponse(ResponseType response,
        ProtocolMapperModel mappingModel, KeycloakSession session,
        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    // read configuration as in OIDC (first clientId, then custom)
    String audience = mappingModel.getConfig().get(INCLUDED_CLIENT_AUDIENCE);
    if (audience == null || audience.isEmpty()) {
        audience = mappingModel.getConfig().get(INCLUDED_CUSTOM_AUDIENCE);
    }
    // locate the first condition that has an audience restriction
    if (audience != null && !audience.isEmpty()) {
        AudienceRestrictionType aud = locateAudienceRestriction(response);
        if (aud != null) {
            logger.debugf("adding audience: %s", audience);
            try {
                aud.addAudience(URI.create(audience));
            } catch (IllegalArgumentException e) {
                logger.warnf(e, "Invalid URI syntax for audience: %s", audience);
            }
        }
    }
    return response;
}
 
Example #4
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 #5
Source File: DeviceActivityTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void clientsTest() {
    String sessionId = createSession(Browsers.CHROME);

    // attach more clients to the session
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);

        ClientModel client2 = session.clientLocalStorage().getClientByClientId(TEST_CLIENT2_ID, realm);
        ClientModel client3 = session.clientLocalStorage().getClientByClientId(TEST_CLIENT3_ID, realm);

        session.sessions().createClientSession(realm, client2, userSession);
        session.sessions().createClientSession(realm, client3, userSession);
    });

    deviceActivityPage.clickRefreshPage();

    List<String> expectedClients = Arrays.asList(TEST_CLIENT_ID, LOCALE_CLIENT_NAME_LOCALIZED, TEST_CLIENT3_NAME);
    String[] actualClients = deviceActivityPage.getSession(sessionId).getClients().split(", ");
    assertThat(expectedClients, containsInAnyOrder(actualClients));

    assertEquals("Account Console", deviceActivityPage.getSessionByIndex(0).getClients());
}
 
Example #6
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
public void testUpdateClientSession(KeycloakSession session) {

    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    String userSessionId = sessions[0].getId();
    String clientUUID = realm.getClientByClientId("test-app").getId();

    UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(clientUUID);

    int time = clientSession.getTimestamp();
    assertNull(clientSession.getAction());

    clientSession.setAction(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name());
    clientSession.setTimestamp(time + 10);

    AuthenticatedClientSessionModel updated = session.sessions().getUserSession(realm, userSessionId).getAuthenticatedClientSessions().get(clientUUID);
    assertEquals(AuthenticatedClientSessionModel.Action.LOGGED_OUT.name(), updated.getAction());
    assertEquals(time + 10, updated.getTimestamp());
}
 
Example #7
Source File: SimpleSamlMapper.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
@Override
public void transformAttributeStatement(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {

    // transform attributeStatement here
    LOGGER.infof("transformAttributeStatement");

    AttributeType bubu = new AttributeType("bubu");
    bubu.setFriendlyName("FriendlyBubu");
    bubu.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");
    bubu.setName("Bubu");

    bubu.addAttributeValue("Object allowed but only Strings or NameIDType supported here...");
    // see: bottom of org.keycloak.saml.processing.core.saml.v2.writers.BaseWriter.writeAttributeTypeWithoutRootTag

    attributeStatement.addAttribute(new AttributeStatementType.ASTChoiceType(bubu));
}
 
Example #8
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Response keycloakInitiatedBrowserLogout(KeycloakSession session, UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
    if (getConfig().getLogoutUrl() == null || getConfig().getLogoutUrl().trim().equals("")) return null;
    String idToken = getIDTokenForLogout(session, userSession);
    if (idToken != null && getConfig().isBackchannelSupported()) {
        backchannelLogout(userSession, idToken);
        return null;
    } else {
        String sessionId = userSession.getId();
        UriBuilder logoutUri = UriBuilder.fromUri(getConfig().getLogoutUrl())
                .queryParam("state", sessionId);
        if (idToken != null) logoutUri.queryParam("id_token_hint", idToken);
        String redirect = RealmsResource.brokerUrl(uriInfo)
                .path(IdentityBrokerService.class, "getEndpoint")
                .path(OIDCEndpoint.class, "logoutResponse")
                .build(realm.getName(), getConfig().getAlias()).toString();
        logoutUri.queryParam("post_logout_redirect_uri", redirect);
        Response response = Response.status(302).location(logoutUri.build()).build();
        return response;
    }
}
 
Example #9
Source File: AbstractOAuth2IdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected Response exchangeStoredToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(tokenSubject, getConfig().getAlias(), authorizedClient.getRealm());
    if (model == null || model.getToken() == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeNotLinked(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    String accessToken = extractTokenFromResponse(model.getToken(), getAccessTokenResponseParameter());
    if (accessToken == null) {
        model.setToken(null);
        session.users().updateFederatedIdentity(authorizedClient.getRealm(), tokenSubject, model);
        event.detail(Details.REASON, "requested_issuer token expired");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    AccessTokenResponse tokenResponse = new AccessTokenResponse();
    tokenResponse.setToken(accessToken);
    tokenResponse.setIdToken(null);
    tokenResponse.setRefreshToken(null);
    tokenResponse.setRefreshExpiresIn(0);
    tokenResponse.getOtherClaims().clear();
    tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    event.success();
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
Example #10
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@ModelTest
public void testCreateAndGetInSameTransaction(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    ClientModel client = realm.getClientByClientId("test-app");
    UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.2", "form", true, null, null);
    AuthenticatedClientSessionModel clientSession = createClientSession(session, client, userSession, "http://redirect", "state");

    UserSessionModel userSessionLoaded = session.sessions().getUserSession(realm, userSession.getId());
    AuthenticatedClientSessionModel clientSessionLoaded = userSessionLoaded.getAuthenticatedClientSessions().get(client.getId());
    Assert.assertNotNull(userSessionLoaded);
    Assert.assertNotNull(clientSessionLoaded);

    Assert.assertEquals(userSession.getId(), clientSessionLoaded.getUserSession().getId());
    Assert.assertEquals(1, userSessionLoaded.getAuthenticatedClientSessions().size());
}
 
Example #11
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void backchannelLogout(UserSessionModel userSession, String idToken) {
    String sessionId = userSession.getId();
    UriBuilder logoutUri = UriBuilder.fromUri(getConfig().getLogoutUrl())
            .queryParam("state", sessionId);
    logoutUri.queryParam("id_token_hint", idToken);
    String url = logoutUri.build().toString();
    try {
        int status = SimpleHttp.doGet(url, session).asStatus();
        boolean success = status >= 200 && status < 400;
        if (!success) {
            logger.warn("Failed backchannel broker logout to: " + url);
        }
    } catch (Exception e) {
        logger.warn("Failed backchannel broker logout to: " + url, e);
    }
}
 
Example #12
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void assertSessions(List<UserSessionModel> actualSessions, UserSessionModel... expectedSessions) {
    String[] expected = new String[expectedSessions.length];
    for (int i = 0; i < expected.length; i++) {
        expected[i] = expectedSessions[i].getId();
    }

    String[] actual = new String[actualSessions.size()];
    for (int i = 0; i < actual.length; i++) {
        actual[i] = actualSessions.get(i).getId();
    }

    Arrays.sort(expected);
    Arrays.sort(actual);

    assertArrayEquals(expected, actual);
}
 
Example #13
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Response browserLogoutAllClients(UserSessionModel userSession, KeycloakSession session, RealmModel realm, HttpHeaders headers, UriInfo uriInfo, AuthenticationSessionModel logoutAuthSession) {
    Map<Boolean, List<AuthenticatedClientSessionModel>> acss = userSession.getAuthenticatedClientSessions().values().stream()
      .filter(clientSession -> ! Objects.equals(AuthenticationSessionModel.Action.LOGGED_OUT.name(), clientSession.getAction()))
      .filter(clientSession -> clientSession.getProtocol() != null)
      .collect(Collectors.partitioningBy(clientSession -> clientSession.getClient().isFrontchannelLogout()));

    final List<AuthenticatedClientSessionModel> backendLogoutSessions = acss.get(false) == null ? Collections.emptyList() : acss.get(false);
    backendLogoutSessions.forEach(acs -> backchannelLogoutClientSession(session, realm, acs, logoutAuthSession, uriInfo, headers));

    final List<AuthenticatedClientSessionModel> redirectClients = acss.get(true) == null ? Collections.emptyList() : acss.get(true);
    for (AuthenticatedClientSessionModel nextRedirectClient : redirectClients) {
        Response response = frontchannelLogoutClientSession(session, realm, nextRedirectClient, logoutAuthSession, uriInfo, headers);
        if (response != null) {
            return response;
        }
    }

    return null;
}
 
Example #14
Source File: UserResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove all user sessions associated with the user
 *
 * Also send notification to all clients that have an admin URL to invalidate the sessions for the particular user.
 *
 */
@Path("logout")
@POST
public void logout() {
    auth.users().requireManage(user);

    session.users().setNotBeforeForUser(realm, user, Time.currentTime());

    List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, user);
    for (UserSessionModel userSession : userSessions) {
        AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
 
Example #15
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessToken generateToken(UserModel user, String scopeParam) {
    AuthenticationSessionModel authSession = null;
    UserSessionModel userSession = null;
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);

    try {
        RootAuthenticationSessionModel rootAuthSession = authSessionManager.createAuthenticationSession(realm, false);
        authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setAuthenticatedUser(user);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scopeParam);

        userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, user, user.getUsername(),
                clientConnection.getRemoteAddr(), "example-auth", false, null, null);

        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

        TokenManager tokenManager = new TokenManager();

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx)
                .generateAccessToken();

        return responseBuilder.getAccessToken();

    } finally {
        if (authSession != null) {
            authSessionManager.removeAuthenticationSession(realm, authSession, false);
        }
        if (userSession != null) {
            session.sessions().removeUserSession(realm, userSession);
        }
    }
}
 
Example #16
Source File: UserSessionPersisterProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<UserSessionModel> loadPersistedSessionsPaginated(KeycloakSession session, boolean offline, int sessionsPerPage, int expectedPageCount, int expectedSessionsCount) {
    UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);

    int count = persister.getUserSessionsCount(offline);

    int pageCount = 0;
    boolean next = true;
    List<UserSessionModel> result = new ArrayList<>();
    int lastCreatedOn = 0;
    String lastSessionId = "abc";

    while (next) {
        List<UserSessionModel> sess = persister.loadUserSessions(0, sessionsPerPage, offline, lastCreatedOn, lastSessionId);

        if (sess.size() < sessionsPerPage) {
            next = false;

            // We had at least some session
            if (sess.size() > 0) {
                pageCount++;
            }
        } else {
            pageCount++;

            UserSessionModel lastSession = sess.get(sess.size() - 1);
            lastCreatedOn = lastSession.getStarted();
            lastSessionId = lastSession.getId();
        }

        result.addAll(sess);
    }

    Assert.assertEquals(expectedPageCount, pageCount);
    Assert.assertEquals(expectedSessionsCount, result.size());
    return result;
}
 
Example #17
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response browserLogout(KeycloakSession session,
                                     RealmModel realm,
                                     UserSessionModel userSession,
                                     UriInfo uriInfo,
                                     ClientConnection connection,
                                     HttpHeaders headers,
                                     String initiatingIdp) {
    if (userSession == null) return null;

    if (logger.isDebugEnabled()) {
        UserModel user = userSession.getUser();
        logger.debugv("Logging out: {0} ({1})", user.getUsername(), userSession.getId());
    }
    
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);

    Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession);
    if (response != null) {
        return response;
    }

    String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
    if (brokerId != null && !brokerId.equals(initiatingIdp)) {
        IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
        response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm);
        if (response != null) {
            return response;
        }
    }

    return finishBrowserLogout(session, realm, userSession, uriInfo, connection, headers);
}
 
Example #18
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public IDToken transformIDToken(IDToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    if (!OIDCAttributeMapperHelper.includeInIDToken(mappingModel)){
        return token;
    }

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}
 
Example #19
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void dettachClientSession(UserSessionProvider sessions, RealmModel realm, AuthenticatedClientSessionModel clientSession) {
    UserSessionModel userSession = clientSession.getUserSession();
    if (userSession == null) {
        return;
    }

    clientSession.detachFromUserSession();

    // TODO: Might need optimization to prevent loading client sessions from cache in getAuthenticatedClientSessions()
    if (userSession.getAuthenticatedClientSessions().isEmpty()) {
        sessions.removeUserSession(realm, userSession);
    }
}
 
Example #20
Source File: FullNameMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    List<String> parts = new LinkedList<>();
    Optional.ofNullable(user.getFirstName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    Optional.ofNullable(user.getLastName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    if (!parts.isEmpty()) {
        token.getOtherClaims().put("name", String.join(" ", parts));
    }
}
 
Example #21
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response finishedRequiredActions(KeycloakSession session, AuthenticationSessionModel authSession, UserSessionModel userSession,
                                               ClientConnection clientConnection, HttpRequest request, UriInfo uriInfo, EventBuilder event) {
    String actionTokenKeyToInvalidate = authSession.getAuthNote(INVALIDATE_ACTION_TOKEN);
    if (actionTokenKeyToInvalidate != null) {
        ActionTokenKeyModel actionTokenKey = DefaultActionTokenKey.from(actionTokenKeyToInvalidate);
        
        if (actionTokenKey != null) {
            ActionTokenStoreProvider actionTokenStore = session.getProvider(ActionTokenStoreProvider.class);
            actionTokenStore.put(actionTokenKey, null); // Token is invalidated
        }
    }

    if (authSession.getAuthNote(END_AFTER_REQUIRED_ACTIONS) != null) {
        LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession)
                .setSuccess(Messages.ACCOUNT_UPDATED);
        if (authSession.getAuthNote(SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS) != null) {
            if (authSession.getRedirectUri() != null) {
                infoPage.setAttribute("pageRedirectUri", authSession.getRedirectUri());
            }

        } else {
            infoPage.setAttribute(Constants.SKIP_LINK, true);
        }
        Response response = infoPage
                .createInfoPage();

        new AuthenticationSessionManager(session).removeAuthenticationSession(authSession.getRealm(), authSession, true);

        return response;
    }
    RealmModel realm = authSession.getRealm();

    ClientSessionContext clientSessionCtx = AuthenticationProcessor.attachSession(authSession, userSession, session, realm, clientConnection, event);
    userSession = clientSessionCtx.getClientSession().getUserSession();

    event.event(EventType.LOGIN);
    event.session(userSession);
    event.success();
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession);
}
 
Example #22
Source File: TestingResourceProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/get-last-session-refresh")
@Produces(MediaType.APPLICATION_JSON)
public Integer getLastSessionRefresh(@QueryParam("realm") final String name, @QueryParam("session") final String sessionId, @QueryParam("offline") boolean offline) {
    RealmModel realm = getRealmByName(name);

    UserSessionModel sessionModel = offline ? session.sessions().getOfflineUserSession(realm, sessionId) : session.sessions().getUserSession(realm, sessionId);
    if (sessionModel == null) {
        throw new NotFoundException("Session not found");
    }

    return sessionModel.getLastSessionRefresh();
}
 
Example #23
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public  void testCreateSessions(KeycloakSession session) {
    int started = Time.currentTime();
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel[] sessions = createSessions(session);

    assertSession(session.sessions().getUserSession(realm, sessions[0].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.1", started, started, "test-app", "third-party");
    assertSession(session.sessions().getUserSession(realm, sessions[1].getId()), session.users().getUserByUsername("user1", realm), "127.0.0.2", started, started, "test-app");
    assertSession(session.sessions().getUserSession(realm, sessions[2].getId()), session.users().getUserByUsername("user2", realm), "127.0.0.3", started, started, "test-app");
}
 
Example #24
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void backchannelLogout(KeycloakSession session, UserSessionModel userSession, boolean logoutBroker) {
    backchannelLogout(
            session,
            session.getContext().getRealm(),
            userSession,
            session.getContext().getUri(),
            session.getContext().getConnection(),
            session.getContext().getRequestHeaders(),
            logoutBroker
    );
}
 
Example #25
Source File: UserSessionProviderOfflineTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static AuthenticatedClientSessionModel createClientSession(KeycloakSession sessionParam, ClientModel
        client, UserSessionModel userSession, String redirect, String state) {
    AuthenticatedClientSessionModel clientSession = sessionParam.sessions().createClientSession(client.getRealm(), client, userSession);
    clientSession.setRedirectUri(redirect);
    if (state != null) clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, state);
    return clientSession;
}
 
Example #26
Source File: AllowedWebOriginsProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    ClientModel client = clientSessionCtx.getClientSession().getClient();

    Set<String> allowedOrigins = client.getWebOrigins();
    if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
        token.setAllowedOrigins(WebOriginsUtils.resolveValidWebOrigins(session, client));
    }

    return token;
}
 
Example #27
Source File: UserSessionProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@ModelTest
public void testRemoveUserSession(KeycloakSession session) {
    RealmModel realm = session.realms().getRealmByName("test");
    UserSessionModel userSession = createSessions(session)[0];

    session.sessions().removeUserSession(realm, userSession);

    assertNull(session.sessions().getUserSession(realm, userSession.getId()));
}
 
Example #28
Source File: UserSessionPersisterProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AuthenticatedClientSessionModel createClientSession(KeycloakSession session, ClientModel client, UserSessionModel userSession, String redirect, String state) {
    RealmModel realm = session.realms().getRealm("test");
    AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, client, userSession);
    clientSession.setRedirectUri(redirect);
    if (state != null) clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, state);
    return clientSession;
}
 
Example #29
Source File: KeycloakIdentity.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserModel getUserFromSessionState() {
    UserSessionProvider sessions = keycloakSession.sessions();
    UserSessionModel userSession = sessions.getUserSession(realm, accessToken.getSessionState());

    if (userSession == null) {
        userSession = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
    }

    return userSession.getUser();
}
 
Example #30
Source File: GroupMembershipMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void transformAttributeStatement(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
    String single = mappingModel.getConfig().get(SINGLE_GROUP_ATTRIBUTE);
    boolean singleAttribute = Boolean.parseBoolean(single);

    boolean fullPath = useFullPath(mappingModel);
    AttributeType singleAttributeType = null;
    for (GroupModel group : userSession.getUser().getGroups()) {
        String groupName;
        if (fullPath) {
            groupName = ModelToRepresentation.buildGroupPath(group);
        } else {
            groupName = group.getName();
        }
        AttributeType attributeType = null;
        if (singleAttribute) {
            if (singleAttributeType == null) {
                singleAttributeType = AttributeStatementHelper.createAttributeType(mappingModel);
                attributeStatement.addAttribute(new AttributeStatementType.ASTChoiceType(singleAttributeType));
            }
            attributeType = singleAttributeType;
        } else {
            attributeType = AttributeStatementHelper.createAttributeType(mappingModel);
            attributeStatement.addAttribute(new AttributeStatementType.ASTChoiceType(attributeType));
        }
        attributeType.addAttributeValue(groupName);
    }
}