Examples of ClientSessionCode


Examples of org.keycloak.services.managers.ClientSessionCode

    protected ClientConnection clientConnection;

    @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.services.managers.ClientSessionCode

        Checks checks = new Checks();
        if (!checks.check(event, realm, code, ClientSessionModel.Action.AUTHENTICATE)) {
            return checks.response;
        }

        ClientSessionCode clientSessionCode = checks.clientCode;

        try {
            return Flows.social(realm, uriInfo, clientConnection, provider)
                    .redirectToSocialProvider(clientSessionCode);
        } catch (Throwable t) {
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

                .assertEvent();
        //assertCode(codeId, response.getCode());
    }

    private void assertCode(String expectedCodeId, String actualCode) {
        ClientSessionCode code = keycloakRule.verifyCode(actualCode);
        assertEquals(expectedCodeId, code.getClientSession().getId());
    }
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

            Response response = authManager.checkNonFormAuthentication(session, clientSession, realm, uriInfo, request, clientConnection, headers, event);
            if (response != null) return response;

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

            String rememberMeUsername = AuthenticationManager.getRememberMeUsername(realm, headers);

            if (rememberMeUsername != null) {
                MultivaluedMap<String, String> formData = new MultivaluedMapImpl<String, String>();
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

        //audit.session(userSession);
        ClientSessionModel clientSession = session.sessions().createClientSession(realm, client);
        clientSession.setAuthMethod(OpenIDConnect.LOGIN_PROTOCOL);
        clientSession.setRedirectUri(redirect);
        clientSession.setUserSession(userSession);
        ClientSessionCode accessCode = new ClientSessionCode(realm, clientSession);

        accessCode.setRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);

        try {
            UriBuilder builder = Urls.loginPasswordResetBuilder(uriInfo.getBaseUri());
            builder.queryParam("code", accessCode.getCode());

            String link = builder.build(realm.getName()).toString();
            long expiration = TimeUnit.SECONDS.toMinutes(realm.getAccessCodeLifespanUserAction());

            this.session.getProvider(EmailProvider.class).setRealm(realm).setUser(user).sendPasswordReset(link, expiration);
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

                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();
                    return account.setError(Messages.SOCIAL_REDIRECT_ERROR).createResponse(AccountPages.SOCIAL);
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

            error.put(OAuth2Constants.ERROR, "invalid_request");
            error.put(OAuth2Constants.ERROR_DESCRIPTION, "code not specified");
            event.error(Errors.INVALID_CODE);
            throw new BadRequestException("Code not specified", Response.status(Response.Status.BAD_REQUEST).entity(error).type("application/json").build());
        }
        ClientSessionCode accessCode = ClientSessionCode.parse(code, session, realm);
        if (accessCode == null) {
            String[] parts = code.split("\\.");
            if (parts.length == 2) {
                try {
                    event.detail(Details.CODE_ID, new String(parts[1]));
                } catch (Throwable t) {
                }
            }
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "Code not found");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }
        ClientSessionModel clientSession = accessCode.getClientSession();
        event.detail(Details.CODE_ID, clientSession.getId());
        if (!accessCode.isValid(ClientSessionModel.Action.CODE_TO_TOKEN)) {
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "Code is expired");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }

        accessCode.setAction(null);
        UserSessionModel userSession = clientSession.getUserSession();
        event.user(userSession.getUser());
        event.session(userSession.getId());

        ClientModel client = authorizeClient(authorizationHeader, formData, event);

        if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "Auth error");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }

        UserModel user = session.users().getUserById(userSession.getUser().getId(), realm);
        if (user == null) {
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "User not found");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }

        if (!user.isEnabled()) {
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "User disabled");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }

        if (!AuthenticationManager.isSessionValid(realm, userSession)) {
            AuthenticationManager.logout(session, realm, userSession, uriInfo, clientConnection);
            Map<String, String> res = new HashMap<String, String>();
            res.put(OAuth2Constants.ERROR, "invalid_grant");
            res.put(OAuth2Constants.ERROR_DESCRIPTION, "Session not active");
            event.error(Errors.INVALID_CODE);
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(res)
                    .build();
        }

        String adapterSessionId = formData.getFirst(AdapterConstants.APPLICATION_SESSION_STATE);
        if (adapterSessionId != null) {
            String adapterSessionHost = formData.getFirst(AdapterConstants.APPLICATION_SESSION_HOST);
            logger.debugf("Adapter Session '%s' saved in ClientSession for client '%s'. Host is '%s'", adapterSessionId, client.getClientId(), adapterSessionHost);

            event.detail(AdapterConstants.APPLICATION_SESSION_STATE, adapterSessionId);
            clientSession.setNote(AdapterConstants.APPLICATION_SESSION_STATE, adapterSessionId);
            event.detail(AdapterConstants.APPLICATION_SESSION_HOST, adapterSessionHost);
            clientSession.setNote(AdapterConstants.APPLICATION_SESSION_HOST, adapterSessionHost);
        }

        AccessToken token = tokenManager.createClientAccessToken(accessCode.getRequestedRoles(), realm, client, user, userSession);

        try {
            tokenManager.verifyAccess(token, realm, client, user);
        } catch (OAuthErrorException e) {
            Map<String, String> error = new HashMap<String, String>();
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

            OpenIDConnect oauth = new OpenIDConnect(session, realm, uriInfo);
            return oauth.cancelLogin(clientSession);
        }

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

        String rememberMeUsername = AuthenticationManager.getRememberMeUsername(realm, headers);

        if (loginHint != null || rememberMeUsername != null) {
            MultivaluedMap<String, String> formData = new MultivaluedMapImpl<String, String>();
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode


        authManager.expireIdentityCookie(realm, uriInfo, clientConnection);

        return Flows.forms(session, realm, clientSession.getClient(), uriInfo)
                .setClientSessionCode(new ClientSessionCode(realm, clientSession).getCode())
                .createRegistration();
    }
View Full Code Here

Examples of org.keycloak.services.managers.ClientSessionCode

        Checks checks = new Checks();
        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.