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);
}
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);
}
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);
}
}
}
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);
})));
}
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));
}
Aggregations