Search in sources :

Example 6 with ProfileManager

use of org.pac4j.core.profile.ProfileManager in project pac4j by pac4j.

the class DefaultLogoutLogic method perform.

@Override
public R perform(final C context, final Config config, final HttpActionAdapter<R, C> httpActionAdapter, final String defaultUrl, final String inputLogoutUrlPattern, final Boolean inputLocalLogout, final Boolean inputDestroySession, final Boolean inputCentralLogout) {
    logger.debug("=== LOGOUT ===");
    HttpAction action;
    try {
        // default values
        final String logoutUrlPattern;
        if (inputLogoutUrlPattern == null) {
            logoutUrlPattern = Pac4jConstants.DEFAULT_LOGOUT_URL_PATTERN_VALUE;
        } else {
            logoutUrlPattern = inputLogoutUrlPattern;
        }
        final boolean localLogout;
        if (inputLocalLogout == null) {
            localLogout = true;
        } else {
            localLogout = inputLocalLogout;
        }
        final boolean destroySession;
        if (inputDestroySession == null) {
            destroySession = false;
        } else {
            destroySession = inputDestroySession;
        }
        final boolean centralLogout;
        if (inputCentralLogout == null) {
            centralLogout = false;
        } else {
            centralLogout = inputCentralLogout;
        }
        // checks
        assertNotNull("context", context);
        assertNotNull("config", config);
        assertNotNull("httpActionAdapter", httpActionAdapter);
        assertNotBlank(Pac4jConstants.LOGOUT_URL_PATTERN, logoutUrlPattern);
        final Clients configClients = config.getClients();
        assertNotNull("configClients", configClients);
        // logic
        final ProfileManager manager = getProfileManager(context, config);
        final List<CommonProfile> profiles = manager.getAll(true);
        // compute redirection URL
        final String url = context.getRequestParameter(Pac4jConstants.URL);
        String redirectUrl = defaultUrl;
        if (url != null && Pattern.matches(logoutUrlPattern, url)) {
            redirectUrl = url;
        }
        logger.debug("redirectUrl: {}", redirectUrl);
        if (redirectUrl != null) {
            action = HttpAction.redirect(context, redirectUrl);
        } else {
            action = HttpAction.noContent(context);
        }
        // local logout if requested or multiple profiles
        if (localLogout || profiles.size() > 1) {
            logger.debug("Performing application logout");
            manager.logout();
            if (destroySession) {
                final SessionStore sessionStore = context.getSessionStore();
                if (sessionStore != null) {
                    final boolean removed = sessionStore.destroySession(context);
                    if (!removed) {
                        logger.error("Unable to destroy the web session. The session store may not support this feature");
                    }
                } else {
                    logger.error("No session store available for this web context");
                }
            }
        }
        // central logout
        if (centralLogout) {
            logger.debug("Performing central logout");
            for (final CommonProfile profile : profiles) {
                logger.debug("Profile: {}", profile);
                final String clientName = profile.getClientName();
                if (clientName != null) {
                    final Client client = configClients.findClient(clientName);
                    if (client != null) {
                        final String targetUrl;
                        if (redirectUrl != null && (redirectUrl.startsWith(HttpConstants.SCHEME_HTTP) || redirectUrl.startsWith(HttpConstants.SCHEME_HTTPS))) {
                            targetUrl = redirectUrl;
                        } else {
                            targetUrl = null;
                        }
                        final RedirectAction logoutAction = client.getLogoutAction(context, profile, targetUrl);
                        logger.debug("Logout action: {}", logoutAction);
                        if (logoutAction != null) {
                            action = logoutAction.perform(context);
                            break;
                        }
                    }
                }
            }
        }
    } catch (final RuntimeException e) {
        return handleException(e, httpActionAdapter, context);
    }
    return httpActionAdapter.adapt(action.getCode(), context);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) SessionStore(org.pac4j.core.context.session.SessionStore) CommonProfile(org.pac4j.core.profile.CommonProfile) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) HttpAction(org.pac4j.core.exception.HttpAction) RedirectAction(org.pac4j.core.redirect.RedirectAction)

Example 7 with ProfileManager

use of org.pac4j.core.profile.ProfileManager in project pac4j by pac4j.

the class DefaultSecurityLogic method perform.

@Override
public R perform(final C context, final Config config, final SecurityGrantedAccessAdapter<R, C> securityGrantedAccessAdapter, final HttpActionAdapter<R, C> httpActionAdapter, final String clients, final String authorizers, final String matchers, final Boolean inputMultiProfile, final Object... parameters) {
    logger.debug("=== SECURITY ===");
    HttpAction action;
    try {
        // default value
        final boolean multiProfile;
        if (inputMultiProfile == null) {
            multiProfile = false;
        } else {
            multiProfile = inputMultiProfile;
        }
        // checks
        assertNotNull("context", context);
        assertNotNull("config", config);
        assertNotNull("httpActionAdapter", httpActionAdapter);
        assertNotNull("clientFinder", clientFinder);
        assertNotNull("authorizationChecker", authorizationChecker);
        assertNotNull("matchingChecker", matchingChecker);
        assertNotNull("profileStorageDecision", profileStorageDecision);
        final Clients configClients = config.getClients();
        assertNotNull("configClients", configClients);
        // logic
        logger.debug("url: {}", context.getFullRequestURL());
        logger.debug("matchers: {}", matchers);
        if (matchingChecker.matches(context, matchers, config.getMatchers())) {
            logger.debug("clients: {}", clients);
            final List<Client> currentClients = clientFinder.find(configClients, context, clients);
            logger.debug("currentClients: {}", currentClients);
            final boolean loadProfilesFromSession = profileStorageDecision.mustLoadProfilesFromSession(context, currentClients);
            logger.debug("loadProfilesFromSession: {}", loadProfilesFromSession);
            final ProfileManager manager = getProfileManager(context, config);
            List<CommonProfile> profiles = manager.getAll(loadProfilesFromSession);
            logger.debug("profiles: {}", profiles);
            // no profile and some current clients
            if (isEmpty(profiles) && isNotEmpty(currentClients)) {
                boolean updated = false;
                // loop on all clients searching direct ones to perform authentication
                for (final Client currentClient : currentClients) {
                    if (currentClient instanceof DirectClient) {
                        logger.debug("Performing authentication for direct client: {}", currentClient);
                        final Credentials credentials = currentClient.getCredentials(context);
                        logger.debug("credentials: {}", credentials);
                        final CommonProfile profile = currentClient.getUserProfile(credentials, context);
                        logger.debug("profile: {}", profile);
                        if (profile != null) {
                            final boolean saveProfileInSession = profileStorageDecision.mustSaveProfileInSession(context, currentClients, (DirectClient) currentClient, profile);
                            logger.debug("saveProfileInSession: {} / multiProfile: {}", saveProfileInSession, multiProfile);
                            manager.save(saveProfileInSession, profile, multiProfile);
                            updated = true;
                            if (!multiProfile) {
                                break;
                            }
                        }
                    }
                }
                if (updated) {
                    profiles = manager.getAll(loadProfilesFromSession);
                    logger.debug("new profiles: {}", profiles);
                }
            }
            // we have profile(s) -> check authorizations
            if (isNotEmpty(profiles)) {
                logger.debug("authorizers: {}", authorizers);
                if (authorizationChecker.isAuthorized(context, profiles, authorizers, config.getAuthorizers())) {
                    logger.debug("authenticated and authorized -> grant access");
                    return securityGrantedAccessAdapter.adapt(context, profiles, parameters);
                } else {
                    logger.debug("forbidden");
                    action = forbidden(context, currentClients, profiles, authorizers);
                }
            } else {
                if (startAuthentication(context, currentClients)) {
                    logger.debug("Starting authentication");
                    saveRequestedUrl(context, currentClients);
                    action = redirectToIdentityProvider(context, currentClients);
                } else {
                    logger.debug("unauthorized");
                    action = unauthorized(context, currentClients);
                }
            }
        } else {
            logger.debug("no matching for this request -> grant access");
            return securityGrantedAccessAdapter.adapt(context, Arrays.asList(), parameters);
        }
    } catch (final Exception e) {
        return handleException(e, httpActionAdapter, context);
    }
    return httpActionAdapter.adapt(action.getCode(), context);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) DirectClient(org.pac4j.core.client.DirectClient) CommonProfile(org.pac4j.core.profile.CommonProfile) Clients(org.pac4j.core.client.Clients) DirectClient(org.pac4j.core.client.DirectClient) Client(org.pac4j.core.client.Client) IndirectClient(org.pac4j.core.client.IndirectClient) HttpAction(org.pac4j.core.exception.HttpAction) Credentials(org.pac4j.core.credentials.Credentials)

Example 8 with ProfileManager

use of org.pac4j.core.profile.ProfileManager in project pac4j by pac4j.

the class SAML2LogoutRequestBuilder method buildLogoutRequest.

@SuppressWarnings("unchecked")
protected final LogoutRequest buildLogoutRequest(final SAML2MessageContext context, final AssertionConsumerService assertionConsumerService, final SingleLogoutService ssoService) {
    final SAMLObjectBuilder<LogoutRequest> builder = (SAMLObjectBuilder<LogoutRequest>) this.builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    final LogoutRequest request = builder.buildObject();
    final SAMLSelfEntityContext selfContext = context.getSAMLSelfEntityContext();
    request.setID(generateID());
    request.setIssuer(getIssuer(selfContext.getEntityId()));
    request.setIssueInstant(DateTime.now(DateTimeZone.UTC).plusSeconds(this.issueInstantSkewSeconds));
    request.setVersion(SAMLVersion.VERSION_20);
    request.setDestination(ssoService.getLocation());
    // very very bad...
    ProfileManager manager = new ProfileManager(context.getWebContext());
    Optional<UserProfile> p = manager.get(true);
    if (p.isPresent() && p.get() instanceof SAML2Profile) {
        final SAML2Profile samlP = (SAML2Profile) p.get();
        // name id added (id of profile)
        final SAMLObjectBuilder<NameID> nameIdBuilder = (SAMLObjectBuilder<NameID>) this.builderFactory.getBuilder(NameID.DEFAULT_ELEMENT_NAME);
        final NameID nameId = nameIdBuilder.buildObject();
        nameId.setValue(samlP.getId());
        nameId.setFormat(samlP.getSamlNameIdFormat());
        nameId.setNameQualifier(samlP.getSamlNameIdNameQualifier());
        nameId.setSPNameQualifier(samlP.getSamlNameIdSpNameQualifier());
        nameId.setSPProvidedID(samlP.getSamlNameIdSpProviderId());
        request.setNameID(nameId);
        // session index added
        final String sessIdx = (String) samlP.getAttribute("sessionindex");
        final SAMLObjectBuilder<SessionIndex> sessionIndexBuilder = (SAMLObjectBuilder<SessionIndex>) this.builderFactory.getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
        final SessionIndex sessionIdx = sessionIndexBuilder.buildObject();
        sessionIdx.setSessionIndex(sessIdx);
        request.getSessionIndexes().add(sessionIdx);
    }
    return request;
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) SAMLSelfEntityContext(org.opensaml.saml.common.messaging.context.SAMLSelfEntityContext) UserProfile(org.pac4j.core.profile.UserProfile) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) NameID(org.opensaml.saml.saml2.core.NameID) SAML2Profile(org.pac4j.saml.profile.SAML2Profile) SessionIndex(org.opensaml.saml.saml2.core.SessionIndex) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest)

Example 9 with ProfileManager

use of org.pac4j.core.profile.ProfileManager in project pac4j by pac4j.

the class DefaultCasLogoutHandler method destroy.

protected void destroy(final C context, final SessionStore sessionStore, final String channel) {
    // remove profiles
    final ProfileManager manager = new ProfileManager(context, sessionStore);
    manager.logout();
    logger.debug("destroy the user profiles");
    // and optionally the web session
    if (destroySession) {
        logger.debug("destroy the whole session");
        final boolean invalidated = sessionStore.destroySession(context);
        if (!invalidated) {
            logger.error("The session has not been invalidated for {} channel logout", channel);
        }
    }
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager)

Example 10 with ProfileManager

use of org.pac4j.core.profile.ProfileManager in project cas by apereo.

the class WebUtils method getAuthenticatedUsername.

/**
     * Return the username of the authenticated user (based on pac4j security).
     *
     * @return the authenticated username.
     */
public static String getAuthenticatedUsername() {
    final HttpServletRequest request = getHttpServletRequestFromRequestAttributes();
    final HttpServletResponse response = getHttpServletResponseFromRequestAttributes();
    if (request != null && response != null) {
        final ProfileManager manager = getPac4jProfileManager(request, response);
        final Optional<UserProfile> profile = manager.get(true);
        if (profile != null && profile.isPresent()) {
            final String id = profile.get().getId();
            if (id != null) {
                return id;
            }
        }
    }
    return PrincipalResolver.UNKNOWN_USER;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Aggregations

ProfileManager (org.pac4j.core.profile.ProfileManager)20 J2EContext (org.pac4j.core.context.J2EContext)10 UserProfile (org.pac4j.core.profile.UserProfile)9 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)4 GetMapping (org.springframework.web.bind.annotation.GetMapping)4 Authentication (org.apereo.cas.authentication.Authentication)3 CommonProfile (org.pac4j.core.profile.CommonProfile)3 HttpSession (javax.servlet.http.HttpSession)2 PrincipalException (org.apereo.cas.authentication.PrincipalException)2 Service (org.apereo.cas.authentication.principal.Service)2 OAuthUserProfile (org.apereo.cas.support.oauth.profile.OAuthUserProfile)2 Client (org.pac4j.core.client.Client)2 Clients (org.pac4j.core.client.Clients)2 HttpAction (org.pac4j.core.exception.HttpAction)2 Subject (javax.security.auth.Subject)1 PrimaryPrincipal (org.apache.knox.gateway.security.PrimaryPrincipal)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1