use of org.pac4j.core.client.IndirectClient in project cas by apereo.
the class DelegatedClientAuthenticationAction method prepareForLoginPage.
/**
* Prepare the data for the login page.
*
* @param context The current webflow context
* @throws HttpAction the http action
*/
protected void prepareForLoginPage(final RequestContext context) throws HttpAction {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
final HttpSession session = request.getSession();
// web context
final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
// save parameters in web session
final WebApplicationService service = WebUtils.getService(context);
LOGGER.debug("save service: [{}]", service);
session.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service);
saveRequestParameter(request, session, this.themeParamName);
saveRequestParameter(request, session, this.localParamName);
saveRequestParameter(request, session, CasProtocolConstants.PARAMETER_METHOD);
final Set<ProviderLoginPageConfiguration> urls = new LinkedHashSet<>();
this.clients.findAllClients().forEach(client -> {
try {
final IndirectClient indirectClient = (IndirectClient) client;
final String name = client.getName().replaceAll("Client\\d*", "");
final String redirectionUrl = indirectClient.getRedirectAction(webContext).getLocation();
LOGGER.debug("[{}] -> [{}]", name, redirectionUrl);
urls.add(new ProviderLoginPageConfiguration(name, redirectionUrl, name.toLowerCase()));
} catch (final HttpAction e) {
if (e.getCode() == HttpStatus.UNAUTHORIZED.value()) {
LOGGER.debug("Authentication request was denied from the provider [{}]", client.getName());
} else {
LOGGER.warn(e.getMessage(), e);
}
} catch (final Exception e) {
LOGGER.error("Cannot process client [{}]", client, e);
}
});
if (!urls.isEmpty()) {
context.getFlowScope().put(PAC4J_URLS, urls);
} else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) {
LOGGER.warn("No clients could be determined based on the provided configuration");
}
}
use of org.pac4j.core.client.IndirectClient in project pac4j by pac4j.
the class DefaultCallbackLogicTests method testCallbackNoRenew.
@Test
public void testCallbackNoRenew() {
final String originalSessionId = request.getSession().getId();
request.setParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
final CommonProfile profile = new CommonProfile();
final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), profile);
config.setClients(new Clients(CALLBACK_URL, indirectClient));
renewSession = false;
config.getClients().init();
call();
final HttpSession session = request.getSession();
final String newSessionId = session.getId();
final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) session.getAttribute(Pac4jConstants.USER_PROFILES);
assertTrue(profiles.containsValue(profile));
assertEquals(1, profiles.size());
assertEquals(newSessionId, originalSessionId);
assertEquals(302, response.getStatus());
assertEquals(Pac4jConstants.DEFAULT_URL_VALUE, response.getRedirectedUrl());
}
use of org.pac4j.core.client.IndirectClient in project cas by apereo.
the class DefaultDelegatedClientFactory method configureSamlClient.
/**
* Configure saml client.
*
* @param properties the properties
*/
protected void configureSamlClient(final Collection<IndirectClient> properties) {
val pac4jProperties = casProperties.getAuthn().getPac4j();
val index = new AtomicInteger();
pac4jProperties.getSaml().stream().filter(saml -> saml.isEnabled() && StringUtils.isNotBlank(saml.getKeystorePath()) && StringUtils.isNotBlank(saml.getIdentityProviderMetadataPath()) && StringUtils.isNotBlank(saml.getServiceProviderEntityId()) && StringUtils.isNotBlank(saml.getServiceProviderMetadataPath())).forEach(saml -> {
val cfg = new SAML2Configuration(saml.getKeystorePath(), saml.getKeystorePassword(), saml.getPrivateKeyPassword(), saml.getIdentityProviderMetadataPath());
cfg.setForceKeystoreGeneration(saml.isForceKeystoreGeneration());
if (saml.getCertificateExpirationDays() > 0) {
cfg.setCertificateExpirationPeriod(Period.ofDays(saml.getCertificateExpirationDays()));
}
FunctionUtils.doIfNotNull(saml.getCertificateSignatureAlg(), cfg::setCertificateSignatureAlg);
cfg.setCertificateNameToAppend(StringUtils.defaultIfBlank(saml.getCertificateNameToAppend(), saml.getClientName()));
cfg.setMaximumAuthenticationLifetime(Beans.newDuration(saml.getMaximumAuthenticationLifetime()).toSeconds());
cfg.setServiceProviderEntityId(saml.getServiceProviderEntityId());
cfg.setServiceProviderMetadataPath(saml.getServiceProviderMetadataPath());
cfg.setAuthnRequestBindingType(saml.getDestinationBinding());
cfg.setForceAuth(saml.isForceAuth());
cfg.setPassive(saml.isPassive());
cfg.setSignMetadata(saml.isSignServiceProviderMetadata());
cfg.setMetadataSigner(new XMLSecSAML2MetadataSigner(cfg));
cfg.setAuthnRequestSigned(saml.isSignAuthnRequest());
cfg.setSpLogoutRequestSigned(saml.isSignServiceProviderLogoutRequest());
cfg.setAcceptedSkew(Beans.newDuration(saml.getAcceptedSkew()).toSeconds());
cfg.setSslSocketFactory(casSSLContext.getSslContext().getSocketFactory());
cfg.setHostnameVerifier(casSSLContext.getHostnameVerifier());
if (StringUtils.isNotBlank(saml.getPrincipalIdAttribute())) {
cfg.setAttributeAsId(saml.getPrincipalIdAttribute());
}
cfg.setWantsAssertionsSigned(saml.isWantsAssertionsSigned());
cfg.setWantsResponsesSigned(saml.isWantsResponsesSigned());
cfg.setAllSignatureValidationDisabled(saml.isAllSignatureValidationDisabled());
cfg.setUseNameQualifier(saml.isUseNameQualifier());
cfg.setAttributeConsumingServiceIndex(saml.getAttributeConsumingServiceIndex());
if (applicationContext.containsBean(DelegatedClientFactory.BEAN_NAME_SAML2_CLIENT_MESSAGE_FACTORY)) {
val factory = applicationContext.getBean(DelegatedClientFactory.BEAN_NAME_SAML2_CLIENT_MESSAGE_FACTORY, SAMLMessageStoreFactory.class);
cfg.setSamlMessageStoreFactory(factory);
} else {
FunctionUtils.doIf(saml.getMessageStoreFactory().equalsIgnoreCase("EMPTY"), ig -> cfg.setSamlMessageStoreFactory(new EmptyStoreFactory())).accept(saml);
FunctionUtils.doIf(saml.getMessageStoreFactory().equalsIgnoreCase("SESSION"), ig -> cfg.setSamlMessageStoreFactory(new HttpSessionStoreFactory())).accept(saml);
if (saml.getMessageStoreFactory().contains(".")) {
Unchecked.consumer(ig -> {
val clazz = ClassUtils.getClass(DefaultDelegatedClientFactory.class.getClassLoader(), saml.getMessageStoreFactory());
val factory = SAMLMessageStoreFactory.class.cast(clazz.getDeclaredConstructor().newInstance());
cfg.setSamlMessageStoreFactory(factory);
}).accept(saml);
}
}
if (saml.getAssertionConsumerServiceIndex() >= 0) {
cfg.setAssertionConsumerServiceIndex(saml.getAssertionConsumerServiceIndex());
}
if (!saml.getAuthnContextClassRef().isEmpty()) {
cfg.setComparisonType(saml.getAuthnContextComparisonType().toUpperCase());
cfg.setAuthnContextClassRefs(saml.getAuthnContextClassRef());
}
if (StringUtils.isNotBlank(saml.getKeystoreAlias())) {
cfg.setKeystoreAlias(saml.getKeystoreAlias());
}
if (StringUtils.isNotBlank(saml.getNameIdPolicyFormat())) {
cfg.setNameIdPolicyFormat(saml.getNameIdPolicyFormat());
}
if (!saml.getRequestedAttributes().isEmpty()) {
saml.getRequestedAttributes().stream().map(attribute -> new SAML2ServiceProviderRequestedAttribute(attribute.getName(), attribute.getFriendlyName(), attribute.getNameFormat(), attribute.isRequired())).forEach(attribute -> cfg.getRequestedServiceProviderAttributes().add(attribute));
}
if (!saml.getBlockedSignatureSigningAlgorithms().isEmpty()) {
cfg.setBlackListedSignatureSigningAlgorithms(saml.getBlockedSignatureSigningAlgorithms());
}
if (!saml.getSignatureAlgorithms().isEmpty()) {
cfg.setSignatureAlgorithms(saml.getSignatureAlgorithms());
}
if (!saml.getSignatureReferenceDigestMethods().isEmpty()) {
cfg.setSignatureReferenceDigestMethods(saml.getSignatureReferenceDigestMethods());
}
if (!StringUtils.isNotBlank(saml.getSignatureCanonicalizationAlgorithm())) {
cfg.setSignatureCanonicalizationAlgorithm(saml.getSignatureCanonicalizationAlgorithm());
}
cfg.setProviderName(saml.getProviderName());
cfg.setNameIdPolicyAllowCreate(saml.getNameIdPolicyAllowCreate().toBoolean());
val mappedAttributes = saml.getMappedAttributes();
if (!mappedAttributes.isEmpty()) {
cfg.setMappedAttributes(CollectionUtils.convertDirectedListToMap(mappedAttributes));
}
val client = new SAML2Client(cfg);
if (StringUtils.isBlank(saml.getClientName())) {
val count = index.intValue();
client.setName(client.getClass().getSimpleName() + count);
}
configureClient(client, saml);
index.incrementAndGet();
LOGGER.debug("Created delegated client [{}]", client);
properties.add(client);
});
}
use of org.pac4j.core.client.IndirectClient in project cas by apereo.
the class DefaultDelegatedClientFactory method configureOAuth20Client.
/**
* Configure OAuth client.
*
* @param properties the properties
*/
protected void configureOAuth20Client(final Collection<IndirectClient> properties) {
val pac4jProperties = casProperties.getAuthn().getPac4j();
val index = new AtomicInteger();
pac4jProperties.getOauth2().stream().filter(oauth -> oauth.isEnabled() && StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret())).forEach(oauth -> {
val client = new GenericOAuth20Client();
client.setProfileId(StringUtils.defaultIfBlank(oauth.getPrincipalAttributeId(), pac4jProperties.getCore().getPrincipalAttributeId()));
client.setKey(oauth.getId());
client.setSecret(oauth.getSecret());
client.setProfileAttrs(oauth.getProfileAttrs());
client.setProfileNodePath(oauth.getProfilePath());
client.setProfileUrl(oauth.getProfileUrl());
client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase()));
client.setTokenUrl(oauth.getTokenUrl());
client.setAuthUrl(oauth.getAuthUrl());
client.setScope(oauth.getScope());
client.setCustomParams(oauth.getCustomParams());
client.getConfiguration().setResponseType(oauth.getResponseType());
if (StringUtils.isBlank(oauth.getClientName())) {
val count = index.intValue();
client.setName(client.getClass().getSimpleName() + count);
}
configureClient(client, oauth);
index.incrementAndGet();
LOGGER.debug("Created client [{}]", client);
properties.add(client);
});
}
use of org.pac4j.core.client.IndirectClient in project cas by apereo.
the class DefaultDelegatedClientIdentityProviderConfigurationProducer method produce.
@Override
public Optional<DelegatedClientIdentityProviderConfiguration> produce(final RequestContext requestContext, final IndirectClient client) {
val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);
val webContext = new JEEContext(request, response);
val currentService = WebUtils.getService(requestContext);
LOGGER.debug("Initializing client [{}] with request parameters [{}] and service [{}]", client, requestContext.getRequestParameters(), currentService);
client.init();
if (delegatedClientAuthenticationRequestCustomizers.isEmpty() || delegatedClientAuthenticationRequestCustomizers.stream().anyMatch(c -> c.isAuthorized(webContext, client, currentService))) {
return DelegatedClientIdentityProviderConfigurationFactory.builder().client(client).webContext(webContext).service(currentService).casProperties(casProperties).build().resolve();
}
return Optional.empty();
}
Aggregations