Search in sources :

Example 1 with SessionStore

use of org.pac4j.core.context.session.SessionStore in project knox by apache.

the class Pac4jDispatcherFilter method init.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // JWT service
    final ServletContext context = filterConfig.getServletContext();
    CryptoService cryptoService = null;
    String clusterName = null;
    if (context != null) {
        GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        clusterName = (String) context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
        if (services != null) {
            keystoreService = (KeystoreService) services.getService(GatewayServices.KEYSTORE_SERVICE);
            cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
            aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE);
            masterService = (MasterService) services.getService("MasterService");
        }
    }
    // crypto service, alias service and cluster name are mandatory
    if (cryptoService == null || aliasService == null || clusterName == null) {
        log.cryptoServiceAndAliasServiceAndClusterNameRequired();
        throw new ServletException("The crypto service, alias service and cluster name are required.");
    }
    try {
        aliasService.getPasswordFromAliasForCluster(clusterName, KnoxSessionStore.PAC4J_PASSWORD, true);
    } catch (AliasServiceException e) {
        log.unableToGenerateAPasswordForEncryption(e);
        throw new ServletException("Unable to generate a password for encryption.");
    }
    // url to SSO authentication provider
    String pac4jCallbackUrl = filterConfig.getInitParameter(PAC4J_CALLBACK_URL);
    if (pac4jCallbackUrl == null) {
        log.ssoAuthenticationProviderUrlRequired();
        throw new ServletException("Required pac4j callback URL is missing.");
    }
    // add the callback parameter to know it's a callback
    pac4jCallbackUrl = CommonHelper.addParameter(pac4jCallbackUrl, PAC4J_CALLBACK_PARAMETER, "true");
    final Config config;
    final String clientName;
    // client name from servlet parameter (mandatory)
    final String clientNameParameter = filterConfig.getInitParameter("clientName");
    if (clientNameParameter == null) {
        log.clientNameParameterRequired();
        throw new ServletException("Required pac4j clientName parameter is missing.");
    }
    if (TEST_BASIC_AUTH.equalsIgnoreCase(clientNameParameter)) {
        // test configuration
        final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
        indirectBasicAuthClient.setRealmName("Knox TEST");
        config = new Config(pac4jCallbackUrl, indirectBasicAuthClient);
        clientName = "IndirectBasicAuthClient";
    } else {
        // get clients from the init parameters
        final Map<String, String> properties = new HashMap<>();
        final Enumeration<String> names = filterConfig.getInitParameterNames();
        addDefaultConfig(clientNameParameter, properties);
        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            properties.put(key, filterConfig.getInitParameter(key));
        }
        final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
        config = propertiesConfigFactory.build();
        final List<Client> clients = config.getClients().getClients();
        if (clients == null || clients.size() == 0) {
            log.atLeastOnePac4jClientMustBeDefined();
            throw new ServletException("At least one pac4j client must be defined.");
        }
        if (CommonHelper.isBlank(clientNameParameter)) {
            clientName = clients.get(0).getName();
        } else {
            clientName = clientNameParameter;
        }
    }
    callbackFilter = new CallbackFilter();
    callbackFilter.init(filterConfig);
    callbackFilter.setConfigOnly(config);
    securityFilter = new SecurityFilter();
    securityFilter.setClients(clientName);
    securityFilter.setConfigOnly(config);
    final String domainSuffix = filterConfig.getInitParameter(PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM);
    final String sessionStoreVar = filterConfig.getInitParameter(PAC4J_SESSION_STORE);
    SessionStore sessionStore;
    if (!StringUtils.isBlank(sessionStoreVar) && J2ESessionStore.class.getName().contains(sessionStoreVar)) {
        sessionStore = new J2ESessionStore();
    } else {
        sessionStore = new KnoxSessionStore(cryptoService, clusterName, domainSuffix);
    }
    config.setSessionStore(sessionStore);
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) HashMap(java.util.HashMap) Config(org.pac4j.core.config.Config) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) SessionStore(org.pac4j.core.context.session.SessionStore) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) CryptoService(org.apache.knox.gateway.services.security.CryptoService) PropertiesConfigFactory(org.pac4j.config.client.PropertiesConfigFactory) SecurityFilter(org.pac4j.j2e.filter.SecurityFilter) CallbackFilter(org.pac4j.j2e.filter.CallbackFilter) Client(org.pac4j.core.client.Client) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) SimpleTestUsernamePasswordAuthenticator(org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator)

Example 2 with SessionStore

use of org.pac4j.core.context.session.SessionStore 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 3 with SessionStore

use of org.pac4j.core.context.session.SessionStore in project pac4j by pac4j.

the class DefaultCasLogoutHandler method recordSession.

@Override
public void recordSession(final C context, final String ticket) {
    final SessionStore sessionStore = context.getSessionStore();
    if (sessionStore == null) {
        logger.error("No session store available for this web context");
    } else {
        final String sessionId = sessionStore.getOrCreateSessionId(context);
        final Object trackableSession = sessionStore.getTrackableSession(context);
        if (trackableSession != null) {
            logger.debug("ticket: {} -> trackableSession: {}", ticket, trackableSession);
            logger.debug("sessionId: {}", sessionId);
            store.set(ticket, trackableSession);
            store.set(sessionId, ticket);
        } else {
            logger.debug("No trackable session for the current session store: {}", sessionStore);
        }
    }
}
Also used : SessionStore(org.pac4j.core.context.session.SessionStore)

Example 4 with SessionStore

use of org.pac4j.core.context.session.SessionStore in project cas by apereo.

the class OidcPrivateKeyJwtAuthenticator method validate.

@Override
public void validate(final Credentials creds, final WebContext webContext, final SessionStore sessionStore) {
    val credentials = (UsernamePasswordCredentials) creds;
    val registeredService = verifyCredentials(credentials, webContext);
    if (registeredService == null) {
        LOGGER.warn("Unable to verify credentials");
        return;
    }
    val clientId = registeredService.getClientId();
    val audience = casProperties.getServer().getPrefix().concat('/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.ACCESS_TOKEN_URL);
    val keys = OidcJsonWebKeyStoreUtils.getJsonWebKeySet(registeredService, applicationContext, Optional.of(OidcJsonWebKeyUsage.SIGNING));
    keys.ifPresent(Unchecked.consumer(jwks -> jwks.getJsonWebKeys().forEach(jsonWebKey -> {
        val consumer = new JwtConsumerBuilder().setVerificationKey(jsonWebKey.getKey()).setRequireSubject().setExpectedSubject(clientId).setRequireJwtId().setRequireExpirationTime().setExpectedIssuer(true, clientId).setExpectedAudience(true, audience).build();
        determineUserProfile(credentials, consumer);
    })));
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) Unchecked(org.jooq.lambda.Unchecked) CommonProfile(org.pac4j.core.profile.CommonProfile) SneakyThrows(lombok.SneakyThrows) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) WebContext(org.pac4j.core.context.WebContext) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) OidcJsonWebKeyStoreUtils(org.apereo.cas.oidc.jwks.OidcJsonWebKeyStoreUtils) Optional(java.util.Optional) Credentials(org.pac4j.core.credentials.Credentials) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) Algorithm(com.nimbusds.jose.Algorithm) OidcJsonWebKeyUsage(org.apereo.cas.oidc.jwks.OidcJsonWebKeyUsage) ServicesManager(org.apereo.cas.services.ServicesManager) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 5 with SessionStore

use of org.pac4j.core.context.session.SessionStore in project cas by apereo.

the class SamlIdPUtils method retrieveSamlRequest.

/**
 * Retrieve authn request authn request.
 *
 * @param context            the context
 * @param sessionStore       the session store
 * @param openSamlConfigBean the open saml config bean
 * @param clazz              the clazz
 * @return the request
 */
public static Optional<Pair<? extends RequestAbstractType, MessageContext>> retrieveSamlRequest(final WebContext context, final SessionStore sessionStore, final OpenSamlConfigBean openSamlConfigBean, final Class<? extends RequestAbstractType> clazz) {
    LOGGER.trace("Retrieving authentication request from scope");
    val authnContext = sessionStore.get(context, SamlProtocolConstants.PARAMETER_SAML_REQUEST).map(String.class::cast).map(value -> retrieveSamlRequest(openSamlConfigBean, clazz, value)).flatMap(authnRequest -> sessionStore.get(context, MessageContext.class.getName()).map(String.class::cast).map(result -> SamlIdPAuthenticationContext.decode(result).toMessageContext(authnRequest)));
    return authnContext.map(ctx -> Pair.of((AuthnRequest) ctx.getMessage(), ctx));
}
Also used : lombok.val(lombok.val) MessageContext(org.opensaml.messaging.context.MessageContext) SneakyThrows(lombok.SneakyThrows) Inflater(java.util.zip.Inflater) SamlIdPAuthenticationContext(org.apereo.cas.support.saml.authentication.SamlIdPAuthenticationContext) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) StringUtils(org.apache.commons.lang3.StringUtils) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) StatusResponseType(org.opensaml.saml.saml2.core.StatusResponseType) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) SAMLBindingSupport(org.opensaml.saml.common.binding.SAMLBindingSupport) Pair(org.apache.commons.lang3.tuple.Pair) ByteArrayInputStream(java.io.ByteArrayInputStream) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) Unchecked(org.jooq.lambda.Unchecked) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) Base64Support(net.shibboleth.utilities.java.support.codec.Base64Support) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) SessionStore(org.pac4j.core.context.session.SessionStore) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) SAMLObject(org.opensaml.saml.common.SAMLObject) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) SAMLPeerEntityContext(org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext) Optional(java.util.Optional) EncodingUtils(org.apereo.cas.util.EncodingUtils) InflaterInputStream(java.util.zip.InflaterInputStream) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) XMLObjectSupport(org.opensaml.core.xml.util.XMLObjectSupport) UtilityClass(lombok.experimental.UtilityClass) WebContext(org.pac4j.core.context.WebContext) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) Assertion(org.opensaml.saml.saml2.core.Assertion) RoleDescriptorResolver(org.opensaml.saml.metadata.resolver.RoleDescriptorResolver) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) JEEContext(org.pac4j.core.context.JEEContext) ServicesManager(org.apereo.cas.services.ServicesManager) lombok.val(lombok.val) PredicateRoleDescriptorResolver(org.opensaml.saml.metadata.resolver.impl.PredicateRoleDescriptorResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SAMLEndpointContext(org.opensaml.saml.common.messaging.context.SAMLEndpointContext) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest)

Aggregations

SessionStore (org.pac4j.core.context.session.SessionStore)10 WebContext (org.pac4j.core.context.WebContext)5 Slf4j (lombok.extern.slf4j.Slf4j)3 lombok.val (lombok.val)3 Client (org.pac4j.core.client.Client)3 Optional (java.util.Optional)2 SneakyThrows (lombok.SneakyThrows)2 OidcConstants (org.apereo.cas.oidc.OidcConstants)2 ServicesManager (org.apereo.cas.services.ServicesManager)2 Unchecked (org.jooq.lambda.Unchecked)2 CommonProfile (org.pac4j.core.profile.CommonProfile)2 Algorithm (com.nimbusds.jose.Algorithm)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Objects (java.util.Objects)1 Collectors (java.util.stream.Collectors)1