Examples of ClientSessionModel


Examples of org.keycloak.models.ClientSessionModel

    @GET
    @Path("callback")
    public Response callback(@QueryParam("state") String encodedState) throws URISyntaxException, IOException {
        ClientSessionCode clientCode = null;
        ClientSessionModel clientSession = null;
        try {
            clientCode = ClientSessionCode.parse(encodedState, session);
            if (clientCode == null) {
                return Flows.forms(session, null, null, uriInfo).setError("Unexpected callback").createErrorPage();
            }
            clientSession = clientCode.getClientSession();
            if (!clientCode.isValid(ClientSessionModel.Action.SOCIAL_CALLBACK)) {
                return Flows.forwardToSecurityFailurePage(session, clientSession.getRealm(), uriInfo, "Invalid code, please login again through your application.");
            }
        } catch (Throwable t) {
            logger.error("Invalid social callback", t);
            return Flows.forms(session, null, null, uriInfo).setError("Unexpected callback").createErrorPage();
        }
        String providerId = clientSession.getNote("social_provider");
        SocialProvider provider = SocialLoader.load(providerId);

        String authMethod = "social@" + provider.getId();

        RealmModel realm = clientSession.getRealm();

        EventBuilder event = new EventsManager(realm, session, clientConnection).createEventBuilder()
                .event(EventType.LOGIN)
                .client(clientSession.getClient())
                .detail(Details.REDIRECT_URI, clientSession.getRedirectUri())
                .detail(Details.AUTH_METHOD, authMethod);

        if (!realm.isEnabled()) {
            event.error(Errors.REALM_DISABLED);
            return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Realm not enabled.");
        }

        String key = realm.getSocialConfig().get(provider.getId() + ".key");
        String secret = realm.getSocialConfig().get(provider.getId() + ".secret");
        String callbackUri = Urls.socialCallback(uriInfo.getBaseUri()).toString();
        SocialProviderConfig config = new SocialProviderConfig(key, secret, callbackUri);

        Map<String, String[]> queryParams = getQueryParams();

        AuthCallback callback = new AuthCallback(queryParams);

        SocialUser socialUser;
        try {
            socialUser = provider.processCallback(clientSession, config, callback);
        } catch (SocialAccessDeniedException e) {
            event.error(Errors.REJECTED_BY_USER);
            clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE);
            return  Flows.forms(session, realm, clientSession.getClient(), uriInfo).setClientSessionCode(clientCode.getCode()).setWarning("Access denied").createLogin();
        } catch (SocialProviderException e) {
            logger.error("Failed to process social callback", e);
            return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Failed to process social callback");
        }

        event.detail(Details.USERNAME, socialUser.getId() + "@" + provider.getId());

        try {
            SocialLinkModel socialLink = new SocialLinkModel(provider.getId(), socialUser.getId(), socialUser.getUsername());
            UserModel user = session.users().getUserBySocialLink(socialLink, realm);

            // Check if user is already authenticated (this means linking social into existing user account)
            if (clientSession.getUserSession() != null) {

                UserModel authenticatedUser = clientSession.getUserSession().getUser();

                event.event(EventType.SOCIAL_LINK).user(authenticatedUser.getId());

                if (user != null) {
                    event.error(Errors.SOCIAL_ID_IN_USE);
                    return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "This social account is already linked to other user");
                }

                if (!authenticatedUser.isEnabled()) {
                    event.error(Errors.USER_DISABLED);
                    return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "User is disabled");
                }

                if (!authenticatedUser.hasRole(realm.getApplicationByName(Constants.ACCOUNT_MANAGEMENT_APP).getRole(AccountRoles.MANAGE_ACCOUNT))) {
                    event.error(Errors.NOT_ALLOWED);
                    return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Insufficient permissions to link social account");
                }

                session.users().addSocialLink(realm, authenticatedUser, socialLink);
                logger.debugv("Social provider {0} linked with user {1}", provider.getId(), authenticatedUser.getUsername());

                event.success();
                return Response.status(302).location(UriBuilder.fromUri(clientSession.getRedirectUri()).build()).build();
            }

            if (user == null) {
                user = session.users().addUser(realm, KeycloakModelUtils.generateId());
                user.setEnabled(true);
                user.setFirstName(socialUser.getFirstName());
                user.setLastName(socialUser.getLastName());
                user.setEmail(socialUser.getEmail());

                if (realm.isUpdateProfileOnInitialSocialLogin()) {
                    user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
                }

                session.users().addSocialLink(realm, user, socialLink);

                event.clone().user(user).event(EventType.REGISTER)
                        .detail(Details.REGISTER_METHOD, "social@" + provider.getId())
                        .detail(Details.EMAIL, socialUser.getEmail())
                        .removeDetail("auth_method")
                        .success();
            }

            event.user(user);

            if (!user.isEnabled()) {
                event.error(Errors.USER_DISABLED);
                return Flows.forwardToSecurityFailurePage(session, realm, uriInfo, "Your account is not enabled.");
            }

            String username = socialLink.getSocialUserId() + "@" + socialLink.getSocialProvider();

            UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, clientConnection.getRemoteAddr(), authMethod, false);
            event.session(userSession);
            TokenManager.attachClientSession(userSession, clientSession);

            AuthenticationManager authManager = new AuthenticationManager();
            Response response = authManager.nextActionAfterAuthentication(session, userSession, clientSession, clientConnection, request, uriInfo, event);
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
            return response;
        } catch (ModelDuplicateException e) {
            // Assume email is the duplicate as there's nothing else atm
            return Flows.forms(session, realm, clientSession.getClient(), uriInfo)
                    .setClientSessionCode(clientCode.getCode())
                    .setError("socialEmailExists")
                    .createLogin();
        }
    }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

        List<ClientSessionModel> clientSessions = session.sessions().getUserSession(realm, sessions[0].getId()).getClientSessions();
        assertEquals(2, clientSessions.size());

        String client1 = realm.findClient("test-app").getId();

        ClientSessionModel session1;

        if (clientSessions.get(0).getClient().getId().equals(client1)) {
            session1 = clientSessions.get(0);
        } else {
            session1 = clientSessions.get(1);
        }

        assertEquals(null, session1.getAction());
        assertEquals(realm.findClient("test-app").getClientId(), session1.getClient().getClientId());
        assertEquals(sessions[0].getId(), session1.getUserSession().getId());
        assertEquals("http://redirect", session1.getRedirectUri());
        assertEquals("state", session1.getNote(OpenIDConnect.STATE_PARAM));
        assertEquals(2, session1.getRoles().size());
        assertTrue(session1.getRoles().contains("one"));
        assertTrue(session1.getRoles().contains("two"));
    }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

    public void testUpdateClientSession() {
        UserSessionModel[] sessions = createSessions();

        String id = sessions[0].getClientSessions().get(0).getId();

        ClientSessionModel clientSession = session.sessions().getClientSession(realm, id);

        int time = clientSession.getTimestamp();
        assertEquals(null, clientSession.getAction());

        clientSession.setAction(ClientSessionModel.Action.CODE_TO_TOKEN);
        clientSession.setTimestamp(time + 10);

        kc.stopSession(session, true);
        session = kc.startSession();

        ClientSessionModel updated = session.sessions().getClientSession(realm, id);
        assertEquals(ClientSessionModel.Action.CODE_TO_TOKEN, updated.getAction());
        assertEquals(time + 10, updated.getTimestamp());
    }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

            UserSessionModel s = session.sessions().createUserSession(realm, session.users().getUserByUsername("user2", realm), "user2", "127.0.0.1", "form", true);
            //s.setLastSessionRefresh(Time.currentTime() - (realm.getSsoSessionIdleTimeout() + 1));
            s.setLastSessionRefresh(0);
            expired.add(s.getId());

            ClientSessionModel clSession = session.sessions().createClientSession(realm, client);
            clSession.setUserSession(s);
            expiredClientSessions.add(clSession.getId());

            Set<String> valid = new HashSet<String>();
            Set<String> validClientSessions = new HashSet<String>();

            valid.add(session.sessions().createUserSession(realm, session.users().getUserByUsername("user1", realm), "user1", "127.0.0.1", "form", true).getId());
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

    public void testGetByClientPaginated() {
        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);
                ClientSessionModel clientSession = session.sessions().createClientSession(realm, realm.findClient("test-app"));
                clientSession.setUserSession(userSession);
                clientSession.setRedirectUri("http://redirect");
                clientSession.setRoles(new HashSet<String>());
                clientSession.setNote(OpenIDConnect.STATE_PARAM, "state");
                clientSession.setTimestamp(userSession.getStarted());
            }
        } finally {
            Time.setOffset(0);
        }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

        assertNull(session.sessions().getUserLoginFailure(realm, "user1@localhost"));
        assertNotNull(session.sessions().getUserLoginFailure(realm, "user2"));
    }

    private ClientSessionModel createClientSession(ClientModel client, UserSessionModel userSession, String redirect, String state, Set<String> roles) {
        ClientSessionModel clientSession = session.sessions().createClientSession(realm, client);
        if (userSession != null) clientSession.setUserSession(userSession);
        clientSession.setRedirectUri(redirect);
        if (state != null) clientSession.setNote(OpenIDConnect.STATE_PARAM, state);
        if (roles != null) clientSession.setRoles(roles);
        return clientSession;
    }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

                        associated = true;
                        break;
                    }
                }
                if (!associated) {
                    ClientSessionModel clientSession = session.sessions().createClientSession(realm, application);
                    clientSession.setUserSession(userSession);
                    auth.setClientSession(clientSession);
                }
            }

            account.setUser(auth.getUser());
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

        switch (accountSocialAction) {
            case ADD:
                String redirectUri = UriBuilder.fromUri(Urls.accountSocialPage(uriInfo.getBaseUri(), realm.getName())).build().toString();

                try {
                    ClientSessionModel clientSession = auth.getClientSession();
                    clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE);
                    clientSession.setRedirectUri(redirectUri);
                    clientSession.setNote(OpenIDConnect.STATE_PARAM, UUID.randomUUID().toString());
                    ClientSessionCode clientSessionCode = new ClientSessionCode(realm, clientSession);
                    return Flows.social(realm, uriInfo, clientConnection, provider)
                            .redirectToSocialProvider(clientSessionCode);
                } catch (SocialProviderException spe) {
                    setReferrerOnPage();
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

        if (entity.getClientSessions() == null) {
            return sessions;
        }

        for (String id : entity.getClientSessions()) {
            ClientSessionModel clientSession = provider.getClientSession(realm, id);
            if (clientSession == null) continue;
            sessions.add(clientSession);
        }
        return sessions;
    }
View Full Code Here

Examples of org.keycloak.models.ClientSessionModel

        if (!checks.check(code)) {
            return checks.response;
        }
        event.detail(Details.CODE_ID, code);
        ClientSessionCode clientSessionCode = checks.clientCode;
        ClientSessionModel clientSession = clientSessionCode.getClientSession();



        LoginFormsProvider forms = Flows.forms(session, realm, clientSession.getClient(), uriInfo)
                .setClientSessionCode(clientSessionCode.getCode());

        return forms.createLogin();
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.