Search in sources :

Example 31 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class JpaUserSessionPersisterProvider method toAdapter.

private PersistentUserSessionAdapter toAdapter(RealmModel realm, PersistentUserSessionEntity entity) {
    PersistentUserSessionModel model = new PersistentUserSessionModel();
    model.setUserSessionId(entity.getUserSessionId());
    model.setStarted(entity.getCreatedOn());
    model.setLastSessionRefresh(entity.getLastSessionRefresh());
    model.setData(entity.getData());
    model.setOffline(offlineFromString(entity.getOffline()));
    Map<String, AuthenticatedClientSessionModel> clientSessions = new HashMap<>();
    return new PersistentUserSessionAdapter(session, model, realm, entity.getUserId(), clientSessions);
}
Also used : PersistentUserSessionAdapter(org.keycloak.models.session.PersistentUserSessionAdapter) HashMap(java.util.HashMap) PersistentUserSessionModel(org.keycloak.models.session.PersistentUserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 32 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method createClientSession.

protected static AuthenticatedClientSessionModel createClientSession(KeycloakSession session, String realmId, ClientModel client, UserSessionModel userSession, String redirect, String state) {
    RealmModel realm = session.realms().getRealm(realmId);
    AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, client, userSession);
    clientSession.setRedirectUri(redirect);
    if (state != null)
        clientSession.setNote(OIDCLoginProtocol.STATE_PARAM, state);
    return clientSession;
}
Also used : RealmModel(org.keycloak.models.RealmModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Example 33 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class UserSessionPersisterProviderTest method testUpdateAndRemove.

@Test
public void testUpdateAndRemove() {
    int started = Time.currentTime();
    AtomicReference<UserSessionModel[]> origSessionsAt = new AtomicReference<>();
    AtomicReference<List<UserSessionModel>> loadedSessionsAt = new AtomicReference<>();
    AtomicReference<UserSessionModel> userSessionAt = new AtomicReference<>();
    AtomicReference<UserSessionModel> persistedSessionAt = new AtomicReference<>();
    inComittedTransaction(session -> {
        // Create some sessions in infinispan
        UserSessionModel[] origSessions = createSessions(session, realmId);
        origSessionsAt.set(origSessions);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionModel[] origSessions = origSessionsAt.get();
        // Persist 1 offline session
        UserSessionModel userSession = session.sessions().getUserSession(realm, origSessions[1].getId());
        userSessionAt.set(userSession);
        persistUserSession(session, userSession, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        // Load offline session
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        loadedSessionsAt.set(loadedSessions);
        UserSessionModel persistedSession = loadedSessions.get(0);
        persistedSessionAt.set(persistedSession);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app");
        // create new clientSession
        AuthenticatedClientSessionModel clientSession = createClientSession(session, realmId, realm.getClientByClientId("third-party"), session.sessions().getUserSession(realm, persistedSession.getId()), "http://redirect", "state");
        persister.createClientSession(clientSession, true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        UserSessionModel userSession = userSessionAt.get();
        // Remove clientSession
        persister.removeClientSession(userSession.getId(), realm.getClientByClientId("third-party").getId(), true);
    });
    inComittedTransaction(session -> {
        RealmModel realm = session.realms().getRealm(realmId);
        UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
        // Assert clientSession removed
        List<UserSessionModel> loadedSessions = loadPersistedSessionsPaginated(session, true, 10, 1, 1);
        UserSessionModel persistedSession = loadedSessions.get(0);
        assertSession(persistedSession, session.users().getUserByUsername(realm, "user1"), "127.0.0.2", started, started, "test-app");
        // Remove userSession
        persister.removeUserSession(persistedSession.getId(), true);
    });
    inComittedTransaction(session -> {
        // Assert nothing found
        loadPersistedSessionsPaginated(session, true, 10, 0, 0);
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 34 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class IdentityBrokerService method clientInitiatedAccountLinking.

@GET
@NoCache
@Path("/{provider_id}/link")
public Response clientInitiatedAccountLinking(@PathParam("provider_id") String providerId, @QueryParam("redirect_uri") String redirectUri, @QueryParam("client_id") String clientId, @QueryParam("nonce") String nonce, @QueryParam("hash") String hash) {
    this.event.event(EventType.CLIENT_INITIATED_ACCOUNT_LINKING);
    checkRealm();
    ClientModel client = checkClient(clientId);
    redirectUri = RedirectUtils.verifyRedirectUri(session, redirectUri, client);
    if (redirectUri == null) {
        event.error(Errors.INVALID_REDIRECT_URI);
        throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    event.detail(Details.REDIRECT_URI, redirectUri);
    if (nonce == null || hash == null) {
        event.error(Errors.INVALID_REDIRECT_URI);
        throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    AuthenticationManager.AuthResult cookieResult = AuthenticationManager.authenticateIdentityCookie(session, realmModel, true);
    String errorParam = "link_error";
    if (cookieResult == null) {
        event.error(Errors.NOT_LOGGED_IN);
        UriBuilder builder = UriBuilder.fromUri(redirectUri).queryParam(errorParam, Errors.NOT_LOGGED_IN).queryParam("nonce", nonce);
        return Response.status(302).location(builder.build()).build();
    }
    cookieResult.getSession();
    event.session(cookieResult.getSession());
    event.user(cookieResult.getUser());
    event.detail(Details.USERNAME, cookieResult.getUser().getUsername());
    AuthenticatedClientSessionModel clientSession = null;
    for (AuthenticatedClientSessionModel cs : cookieResult.getSession().getAuthenticatedClientSessions().values()) {
        if (cs.getClient().getClientId().equals(clientId)) {
            byte[] decoded = Base64Url.decode(hash);
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance("SHA-256");
            } catch (NoSuchAlgorithmException e) {
                throw new ErrorPageException(session, Response.Status.INTERNAL_SERVER_ERROR, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST);
            }
            String input = nonce + cookieResult.getSession().getId() + clientId + providerId;
            byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
            if (MessageDigest.isEqual(decoded, check)) {
                clientSession = cs;
                break;
            }
        }
    }
    if (clientSession == null) {
        event.error(Errors.INVALID_TOKEN);
        throw new ErrorPageException(session, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }
    event.detail(Details.IDENTITY_PROVIDER, providerId);
    ClientModel accountService = this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
    if (!accountService.getId().equals(client.getId())) {
        RoleModel manageAccountRole = accountService.getRole(AccountRoles.MANAGE_ACCOUNT);
        // Ensure user has role and client has "role scope" for this role
        ClientSessionContext ctx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSession, session);
        Set<RoleModel> userAccountRoles = ctx.getRolesStream().collect(Collectors.toSet());
        if (!userAccountRoles.contains(manageAccountRole)) {
            RoleModel linkRole = accountService.getRole(AccountRoles.MANAGE_ACCOUNT_LINKS);
            if (!userAccountRoles.contains(linkRole)) {
                event.error(Errors.NOT_ALLOWED);
                UriBuilder builder = UriBuilder.fromUri(redirectUri).queryParam(errorParam, Errors.NOT_ALLOWED).queryParam("nonce", nonce);
                return Response.status(302).location(builder.build()).build();
            }
        }
    }
    IdentityProviderModel identityProviderModel = realmModel.getIdentityProviderByAlias(providerId);
    if (identityProviderModel == null) {
        event.error(Errors.UNKNOWN_IDENTITY_PROVIDER);
        UriBuilder builder = UriBuilder.fromUri(redirectUri).queryParam(errorParam, Errors.UNKNOWN_IDENTITY_PROVIDER).queryParam("nonce", nonce);
        return Response.status(302).location(builder.build()).build();
    }
    // Create AuthenticationSessionModel with same ID like userSession and refresh cookie
    UserSessionModel userSession = cookieResult.getSession();
    // Auth session with ID corresponding to our userSession may already exists in some rare cases (EG. if some client tried to login in another browser tab with "prompt=login")
    RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().getRootAuthenticationSession(realmModel, userSession.getId());
    if (rootAuthSession == null) {
        rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realmModel, userSession.getId());
    }
    AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
    // Refresh the cookie
    new AuthenticationSessionManager(session).setAuthSessionCookie(userSession.getId(), realmModel);
    ClientSessionCode<AuthenticationSessionModel> clientSessionCode = new ClientSessionCode<>(session, realmModel, authSession);
    clientSessionCode.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
    clientSessionCode.getOrGenerateCode();
    authSession.setProtocol(client.getProtocol());
    authSession.setRedirectUri(redirectUri);
    authSession.setClientNote(OIDCLoginProtocol.STATE_PARAM, UUID.randomUUID().toString());
    authSession.setAuthNote(LINKING_IDENTITY_PROVIDER, cookieResult.getSession().getId() + clientId + providerId);
    event.detail(Details.CODE_ID, userSession.getId());
    event.success();
    try {
        IdentityProvider identityProvider = getIdentityProvider(session, realmModel, providerId);
        Response response = identityProvider.performLogin(createAuthenticationRequest(providerId, clientSessionCode));
        if (response != null) {
            if (isDebugEnabled()) {
                logger.debugf("Identity provider [%s] is going to send a request [%s].", identityProvider, response);
            }
            return response;
        }
    } catch (IdentityBrokerException e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.COULD_NOT_SEND_AUTHENTICATION_REQUEST, e, providerId);
    } catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.UNEXPECTED_ERROR_HANDLING_REQUEST, e, providerId);
    }
    return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.COULD_NOT_PROCEED_WITH_AUTHENTICATION_REQUEST);
}
Also used : UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) RoleModel(org.keycloak.models.RoleModel) SocialIdentityProvider(org.keycloak.broker.social.SocialIdentityProvider) IdentityProvider(org.keycloak.broker.provider.IdentityProvider) ErrorPageException(org.keycloak.services.ErrorPageException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) ClientSessionCode(org.keycloak.services.managers.ClientSessionCode) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) OAuthErrorException(org.keycloak.OAuthErrorException) NotFoundException(javax.ws.rs.NotFoundException) ErrorPageException(org.keycloak.services.ErrorPageException) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) ClientModel(org.keycloak.models.ClientModel) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) UriBuilder(javax.ws.rs.core.UriBuilder) MessageDigest(java.security.MessageDigest) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 35 with AuthenticatedClientSessionModel

use of org.keycloak.models.AuthenticatedClientSessionModel in project keycloak by keycloak.

the class AuthenticationManager method redirectAfterSuccessfulFlow.

public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession, ClientSessionContext clientSessionCtx, HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection, EventBuilder event, AuthenticationSessionModel authSession, LoginProtocol protocol) {
    Cookie sessionCookie = getCookie(request.getHttpHeaders().getCookies(), AuthenticationManager.KEYCLOAK_SESSION_COOKIE);
    if (sessionCookie != null) {
        String[] split = sessionCookie.getValue().split("/");
        if (split.length >= 3) {
            String oldSessionId = split[2];
            if (!oldSessionId.equals(userSession.getId())) {
                UserSessionModel oldSession = session.sessions().getUserSession(realm, oldSessionId);
                if (oldSession != null) {
                    logger.debugv("Removing old user session: session: {0}", oldSessionId);
                    session.sessions().removeUserSession(realm, oldSession);
                }
            }
        }
    }
    // Updates users locale if required
    session.getContext().resolveLocale(userSession.getUser());
    // refresh the cookies!
    createLoginCookie(session, realm, userSession.getUser(), userSession, uriInfo, clientConnection);
    if (userSession.getState() != UserSessionModel.State.LOGGED_IN)
        userSession.setState(UserSessionModel.State.LOGGED_IN);
    if (userSession.isRememberMe()) {
        createRememberMeCookie(realm, userSession.getLoginUsername(), uriInfo, clientConnection);
    } else {
        expireRememberMeCookie(realm, uriInfo, clientConnection);
    }
    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    // Update userSession note with authTime. But just if flag SSO_AUTH is not set
    boolean isSSOAuthentication = AuthenticatorUtil.isSSOAuthentication(authSession);
    if (isSSOAuthentication) {
        clientSession.setNote(SSO_AUTH, "true");
        authSession.removeAuthNote(SSO_AUTH);
    } else {
        int authTime = Time.currentTime();
        userSession.setNote(AUTH_TIME, String.valueOf(authTime));
        clientSession.removeNote(SSO_AUTH);
    }
    // The user has successfully logged in and we can clear his/her previous login failure attempts.
    logSuccess(session, authSession);
    return protocol.authenticated(authSession, userSession, clientSessionCtx);
}
Also used : NewCookie(javax.ws.rs.core.NewCookie) Cookie(javax.ws.rs.core.Cookie) CookieHelper.getCookie(org.keycloak.services.util.CookieHelper.getCookie) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel)

Aggregations

AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)59 UserSessionModel (org.keycloak.models.UserSessionModel)35 RealmModel (org.keycloak.models.RealmModel)25 ClientModel (org.keycloak.models.ClientModel)23 Test (org.junit.Test)16 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)13 UserModel (org.keycloak.models.UserModel)12 KeycloakSession (org.keycloak.models.KeycloakSession)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)11 HashMap (java.util.HashMap)10 Map (java.util.Map)9 ClientSessionContext (org.keycloak.models.ClientSessionContext)9 LinkedList (java.util.LinkedList)8 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)8 OAuthErrorException (org.keycloak.OAuthErrorException)6 VerificationException (org.keycloak.common.VerificationException)6 AccessToken (org.keycloak.representations.AccessToken)6 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)6 HashSet (java.util.HashSet)5 List (java.util.List)5