use of io.undertow.security.api.NotificationReceiver in project indy by Commonjava.
the class DeploymentInfoUtils method merge.
public static void merge(final DeploymentInfo into, final DeploymentInfo from) {
final Map<String, AuthenticationMechanismFactory> authMechs = from.getAuthenticationMechanisms();
if (authMechs != null) {
for (final Map.Entry<String, AuthenticationMechanismFactory> entry : authMechs.entrySet()) {
logger.debug("Found authentication mechanism: {}", entry.getKey());
into.addAuthenticationMechanism(entry.getKey(), entry.getValue());
}
}
if (from.getAuthorizationManager() != null) {
logger.debug("Found authorization manager: {}", from.getAuthorizationManager());
into.setAuthorizationManager(from.getAuthorizationManager());
}
if (from.getConfidentialPortManager() != null) {
logger.debug("Found confidential port manager: {}", from.getConfidentialPortManager());
into.setConfidentialPortManager(from.getConfidentialPortManager());
}
final List<ErrorPage> errorPages = from.getErrorPages();
if (errorPages != null) {
logger.debug("Found error pages: {}", errorPages);
into.addErrorPages(errorPages);
}
if (from.getExceptionHandler() != null) {
logger.debug("Found exception handler: {}", from.getExceptionHandler());
into.setExceptionHandler(from.getExceptionHandler());
}
final List<FilterMappingInfo> filterMappings = from.getFilterMappings();
if (filterMappings != null) {
for (final FilterMappingInfo fmi : filterMappings) {
switch(fmi.getMappingType()) {
case SERVLET:
{
logger.debug("Found servlet-name filter mapping: {} -> {}({})", fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
into.addFilterServletNameMapping(fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
break;
}
default:
{
logger.debug("Found URL filter mapping: {} -> {}({})", fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
into.addFilterUrlMapping(fmi.getFilterName(), fmi.getMapping(), fmi.getDispatcher());
}
}
}
}
final Map<String, FilterInfo> filterInfos = from.getFilters();
if (filterInfos != null) {
logger.debug("Found filters: {}", filterInfos.keySet());
into.addFilters(filterInfos.values());
}
if (from.getIdentityManager() != null) {
logger.debug("Found identity manager: {}", from.getIdentityManager());
into.setIdentityManager(from.getIdentityManager());
}
final Map<String, String> initParameters = from.getInitParameters();
if (initParameters != null) {
for (final Map.Entry<String, String> entry : initParameters.entrySet()) {
logger.debug("Init-Param: {} = {} from: {}", entry.getKey(), entry.getValue(), from);
into.addInitParameter(entry.getKey(), entry.getValue());
}
}
final List<LifecycleInterceptor> lifecycleInterceptors = from.getLifecycleInterceptors();
if (lifecycleInterceptors != null) {
for (final LifecycleInterceptor lifecycleInterceptor : lifecycleInterceptors) {
logger.debug("Found lifecycle interceptor: {}", lifecycleInterceptor);
into.addLifecycleInterceptor(lifecycleInterceptor);
}
}
final List<ListenerInfo> listeners = from.getListeners();
if (listeners != null) {
logger.debug("Found listeners: {}", listeners.stream().map(li -> li.getListenerClass().getName()).collect(Collectors.toList()));
into.addListeners(listeners);
}
if (from.getMetricsCollector() != null) {
logger.debug("Found metrics collector: {}", from.getMetricsCollector());
into.setMetricsCollector(from.getMetricsCollector());
}
final List<MimeMapping> mimeMappings = from.getMimeMappings();
if (mimeMappings != null) {
logger.debug("Found mime mappings: {}", mimeMappings.stream().map(mm -> mm.getMimeType() + " -> " + mm.getExtension()).collect(Collectors.toList()));
into.addMimeMappings(mimeMappings);
}
final List<NotificationReceiver> notificationReceivers = from.getNotificationReceivers();
if (notificationReceivers != null) {
logger.debug("Found notification receivers: {}", notificationReceivers);
into.addNotificationReceivers(notificationReceivers);
}
final Map<String, Set<String>> principalVersusRolesMap = from.getPrincipalVersusRolesMap();
if (principalVersusRolesMap != null) {
for (final Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) {
logger.debug("Found principle-roles mapping: {} -> {}", entry.getKey(), entry.getValue());
into.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue());
}
}
final List<SecurityConstraint> securityConstraints = from.getSecurityConstraints();
if (securityConstraints != null) {
if (logger.isDebugEnabled()) {
for (final SecurityConstraint sc : securityConstraints) {
logger.debug("Security Constraint: {} from: {}", sc, from);
}
}
into.addSecurityConstraints(securityConstraints);
}
final LoginConfig loginConfig = from.getLoginConfig();
if (loginConfig != null) {
logger.debug("Login Config with realm: {} and mechanism: {} from: {}", loginConfig.getRealmName(), loginConfig.getAuthMethods(), from);
if (into.getLoginConfig() != null) {
throw new IllegalStateException("Two or more deployment providers are attempting to provide login configurations! Enable debug logging to see more.");
}
into.setLoginConfig(loginConfig);
}
if (from.getSecurityContextFactory() != null) {
logger.debug("Found security context factory: {}", from.getSecurityContextFactory());
into.setSecurityContextFactory(from.getSecurityContextFactory());
}
final Set<String> securityRoles = from.getSecurityRoles();
if (securityRoles != null) {
logger.debug("Found security roles: {}", securityRoles);
into.addSecurityRoles(securityRoles);
}
final List<ServletContainerInitializerInfo> servletContainerInitializers = from.getServletContainerInitializers();
if (servletContainerInitializers != null) {
logger.debug("Found servlet container initializers: {}", servletContainerInitializers.stream().map(sci -> sci.getServletContainerInitializerClass().getName()).collect(Collectors.toList()));
into.addServletContainerInitalizers(servletContainerInitializers);
}
final Map<String, Object> servletContextAttributes = from.getServletContextAttributes();
if (servletContextAttributes != null) {
for (final Map.Entry<String, Object> entry : servletContextAttributes.entrySet()) {
logger.debug("Found servlet context attribute: {} -> {}", entry.getKey(), entry.getValue());
into.addServletContextAttribute(entry.getKey(), entry.getValue());
}
}
final List<ServletExtension> servletExtensions = from.getServletExtensions();
if (servletExtensions != null) {
for (final ServletExtension servletExtension : servletExtensions) {
logger.debug("Found servlet extension: {}", servletExtension);
into.addServletExtension(servletExtension);
}
}
final Map<String, ServletInfo> servletInfos = from.getServlets();
if (servletInfos != null) {
logger.debug("Found servlets: {}", servletInfos.values().stream().map(si -> si.getName() + " => " + si.getMappings()).collect(Collectors.toList()));
into.addServlets(servletInfos.values());
}
final List<SessionListener> sessionListeners = from.getSessionListeners();
if (sessionListeners != null) {
for (final SessionListener sessionListener : sessionListeners) {
logger.debug("Found session listener: {}", sessionListener);
into.addSessionListener(sessionListener);
}
}
if (from.getSessionManagerFactory() != null) {
logger.debug("Found session manager factory: {}", from.getSessionManagerFactory());
into.setSessionManagerFactory(from.getSessionManagerFactory());
}
if (from.getSessionPersistenceManager() != null) {
logger.debug("Found session persistence manager: {}", from.getSessionPersistenceManager());
into.setSessionPersistenceManager(from.getSessionPersistenceManager());
}
if (from.getTempDir() != null) {
logger.debug("Found temp dir: {}", from.getTempDir());
into.setTempDir(from.getTempDir());
}
final List<String> welcomePages = from.getWelcomePages();
if (welcomePages != null) {
logger.debug("Found welcome pages: {}", welcomePages);
into.addWelcomePages(welcomePages);
}
final List<HandlerWrapper> initWrappers = from.getInitialHandlerChainWrappers();
if (initWrappers != null) {
for (final HandlerWrapper wrapper : initWrappers) {
logger.debug("Found initial handler chain wrapper: {}", wrapper);
into.addInitialHandlerChainWrapper(wrapper);
}
}
final List<HandlerWrapper> outerWrappers = from.getOuterHandlerChainWrappers();
if (outerWrappers != null) {
for (final HandlerWrapper wrapper : outerWrappers) {
logger.debug("Found outer handler chain wrapper: {}", wrapper);
into.addOuterHandlerChainWrapper(wrapper);
}
}
final List<HandlerWrapper> innerWrappers = from.getInnerHandlerChainWrappers();
if (innerWrappers != null) {
for (final HandlerWrapper wrapper : innerWrappers) {
logger.debug("Found inner handler chain wrapper: {}", wrapper);
into.addInnerHandlerChainWrapper(wrapper);
}
}
}
use of io.undertow.security.api.NotificationReceiver in project undertow by undertow-io.
the class SingleSignOnAuthenticationMechanism method authenticate.
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
Cookie cookie = null;
for (Cookie c : exchange.requestCookies()) {
if (cookieName.equals(c.getName())) {
cookie = c;
}
}
if (cookie != null) {
final String ssoId = cookie.getValue();
log.tracef("Found SSO cookie %s", ssoId);
try (SingleSignOn sso = this.singleSignOnManager.findSingleSignOn(ssoId)) {
if (sso != null) {
if (log.isTraceEnabled()) {
log.tracef("SSO session with ID: %s found.", ssoId);
}
Account verified = getIdentityManager(securityContext).verify(sso.getAccount());
if (verified == null) {
if (log.isTraceEnabled()) {
log.tracef("Account not found. Returning 'not attempted' here.");
}
// we return not attempted here to allow other mechanisms to proceed as normal
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
final Session session = getSession(exchange);
registerSessionIfRequired(sso, session);
securityContext.authenticationComplete(verified, sso.getMechanismName(), false);
securityContext.registerNotificationReceiver(new NotificationReceiver() {
@Override
public void handleNotification(SecurityNotification notification) {
if (notification.getEventType() == SecurityNotification.EventType.LOGGED_OUT) {
singleSignOnManager.removeSingleSignOn(sso);
}
}
});
log.tracef("Authenticated account %s using SSO", verified.getPrincipal().getName());
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
}
clearSsoCookie(exchange);
}
exchange.addResponseWrapper(responseListener);
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
use of io.undertow.security.api.NotificationReceiver in project undertow by undertow-io.
the class AuthenticationTestBase method setAuthenticationChain.
@Before
public void setAuthenticationChain() {
List<AuthenticationMechanism> testMechanisms = getTestMechanisms();
if (testMechanisms == null) {
return;
}
HttpHandler current = new ResponseHandler();
current = new AuthenticationCallHandler(current);
current = new AuthenticationConstraintHandler(current);
current = new AuthenticationMechanismsHandler(current, testMechanisms);
// Ensure empty on initialisation.
auditReceiver.takeNotifications();
current = new NotificationReceiverHandler(current, Collections.<NotificationReceiver>singleton(auditReceiver));
if (cachingRequired()) {
current = new CachedAuthenticatedSessionHandler(current);
}
current = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, current);
setRootHandler(current);
}
use of io.undertow.security.api.NotificationReceiver in project undertow by undertow-io.
the class SsoTestCase method setup.
@BeforeClass
public static void setup() {
final SingleSignOnAuthenticationMechanism sso = new SingleSignOnAuthenticationMechanism(new InMemorySingleSignOnManager());
final PathHandler path = new PathHandler();
HttpHandler current = new ResponseHandler();
current = new AuthenticationCallHandler(current);
current = new AuthenticationConstraintHandler(current);
List<AuthenticationMechanism> mechs = new ArrayList<>();
mechs.add(sso);
mechs.add(new BasicAuthenticationMechanism("Test Realm"));
current = new AuthenticationMechanismsHandler(current, mechs);
current = new NotificationReceiverHandler(current, Collections.<NotificationReceiver>singleton(auditReceiver));
current = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, current);
path.addPrefixPath("/test1", current);
current = new ResponseHandler();
current = new AuthenticationCallHandler(current);
current = new AuthenticationConstraintHandler(current);
mechs = new ArrayList<>();
mechs.add(sso);
mechs.add(new FormAuthenticationMechanism("form", "/login", "/error"));
current = new AuthenticationMechanismsHandler(current, mechs);
current = new NotificationReceiverHandler(current, Collections.<NotificationReceiver>singleton(auditReceiver));
current = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, current);
path.addPrefixPath("/test2", current);
path.addPrefixPath("/login", new ResponseCodeHandler(StatusCodes.UNAUTHORIZED));
DefaultServer.setRootHandler(new SessionAttachmentHandler(path, new InMemorySessionManager(""), new SessionCookieConfig()));
}
use of io.undertow.security.api.NotificationReceiver in project undertow by undertow-io.
the class DeploymentManagerImpl method setupSecurityHandlers.
/**
* sets up the outer security handlers.
* <p>
* the handler that actually performs the access check happens later in the chain, it is not setup here
*
* @param initialHandler The handler to wrap with security handlers
*/
private HttpHandler setupSecurityHandlers(HttpHandler initialHandler) {
final DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
final LoginConfig loginConfig = deploymentInfo.getLoginConfig();
HttpHandler current = initialHandler;
current = new SSLInformationAssociationHandler(current);
final SecurityPathMatches securityPathMatches = buildSecurityConstraints();
securityPathMatches.logWarningsAboutUncoveredMethods();
current = new ServletAuthenticationCallHandler(current);
for (HandlerWrapper wrapper : deploymentInfo.getSecurityWrappers()) {
current = wrapper.wrap(current);
}
if (deploymentInfo.isDisableCachingForSecuredPages()) {
current = Handlers.predicate(Predicates.authRequired(), Handlers.disableCache(current), current);
}
if (!securityPathMatches.isEmpty()) {
current = new ServletAuthenticationConstraintHandler(current);
}
current = new ServletConfidentialityConstraintHandler(deploymentInfo.getConfidentialPortManager(), current);
if (!securityPathMatches.isEmpty()) {
current = new ServletSecurityConstraintHandler(securityPathMatches, current);
}
HandlerWrapper initialSecurityWrapper = deploymentInfo.getInitialSecurityWrapper();
String mechName = null;
if (initialSecurityWrapper == null) {
final Map<String, AuthenticationMechanismFactory> factoryMap = new HashMap<>(deploymentInfo.getAuthenticationMechanisms());
final IdentityManager identityManager = deploymentInfo.getIdentityManager();
if (!factoryMap.containsKey(BASIC_AUTH)) {
factoryMap.put(BASIC_AUTH, BasicAuthenticationMechanism.FACTORY);
}
if (!factoryMap.containsKey(FORM_AUTH)) {
factoryMap.put(FORM_AUTH, ServletFormAuthenticationMechanism.FACTORY);
}
if (!factoryMap.containsKey(DIGEST_AUTH)) {
factoryMap.put(DIGEST_AUTH, DigestAuthenticationMechanism.FACTORY);
}
if (!factoryMap.containsKey(CLIENT_CERT_AUTH)) {
factoryMap.put(CLIENT_CERT_AUTH, ClientCertAuthenticationMechanism.FACTORY);
}
if (!factoryMap.containsKey(ExternalAuthenticationMechanism.NAME)) {
factoryMap.put(ExternalAuthenticationMechanism.NAME, ExternalAuthenticationMechanism.FACTORY);
}
if (!factoryMap.containsKey(GenericHeaderAuthenticationMechanism.NAME)) {
factoryMap.put(GenericHeaderAuthenticationMechanism.NAME, GenericHeaderAuthenticationMechanism.FACTORY);
}
List<AuthenticationMechanism> authenticationMechanisms = new LinkedList<>();
if (deploymentInfo.isUseCachedAuthenticationMechanism()) {
authenticationMechanisms.add(new CachedAuthenticatedSessionMechanism(identityManager));
}
if (loginConfig != null || deploymentInfo.getJaspiAuthenticationMechanism() != null) {
// we don't allow multipart requests, and use the default encoding when it's set
FormEncodedDataDefinition formEncodedDataDefinition = new FormEncodedDataDefinition();
String reqEncoding = deploymentInfo.getDefaultRequestEncoding();
if (reqEncoding == null) {
reqEncoding = deploymentInfo.getDefaultEncoding();
}
if (reqEncoding != null) {
formEncodedDataDefinition.setDefaultEncoding(reqEncoding);
}
FormParserFactory parser = FormParserFactory.builder(false).addParser(formEncodedDataDefinition).build();
List<AuthMethodConfig> authMethods = Collections.<AuthMethodConfig>emptyList();
if (loginConfig != null) {
authMethods = loginConfig.getAuthMethods();
}
for (AuthMethodConfig method : authMethods) {
AuthenticationMechanismFactory factory = factoryMap.get(method.getName());
if (factory == null) {
throw UndertowServletMessages.MESSAGES.unknownAuthenticationMechanism(method.getName());
}
if (mechName == null) {
mechName = method.getName();
}
final Map<String, String> properties = new HashMap<>();
properties.put(AuthenticationMechanismFactory.CONTEXT_PATH, deploymentInfo.getContextPath());
properties.put(AuthenticationMechanismFactory.REALM, loginConfig.getRealmName());
properties.put(AuthenticationMechanismFactory.ERROR_PAGE, loginConfig.getErrorPage());
properties.put(AuthenticationMechanismFactory.LOGIN_PAGE, loginConfig.getLoginPage());
properties.putAll(method.getProperties());
String name = method.getName().toUpperCase(Locale.US);
// The mechanism name is passed in from the HttpServletRequest interface as the name reported needs to be
// comparable using '=='
name = name.equals(FORM_AUTH) ? FORM_AUTH : name;
name = name.equals(BASIC_AUTH) ? BASIC_AUTH : name;
name = name.equals(DIGEST_AUTH) ? DIGEST_AUTH : name;
name = name.equals(CLIENT_CERT_AUTH) ? CLIENT_CERT_AUTH : name;
authenticationMechanisms.add(factory.create(name, identityManager, parser, properties));
}
}
deployment.setAuthenticationMechanisms(authenticationMechanisms);
// if the JASPI auth mechanism is set then it takes over
if (deploymentInfo.getJaspiAuthenticationMechanism() == null) {
current = new AuthenticationMechanismsHandler(current, authenticationMechanisms);
} else {
current = new AuthenticationMechanismsHandler(current, Collections.<AuthenticationMechanism>singletonList(deploymentInfo.getJaspiAuthenticationMechanism()));
}
current = new CachedAuthenticatedSessionHandler(current, this.deployment.getServletContext());
}
List<NotificationReceiver> notificationReceivers = deploymentInfo.getNotificationReceivers();
if (!notificationReceivers.isEmpty()) {
current = new NotificationReceiverHandler(current, notificationReceivers);
}
if (initialSecurityWrapper == null) {
// TODO - A switch to constraint driven could be configurable, however before we can support that with servlets we would
// need additional tracking within sessions if a servlet has specifically requested that authentication occurs.
SecurityContextFactory contextFactory = deploymentInfo.getSecurityContextFactory();
if (contextFactory == null) {
contextFactory = SecurityContextFactoryImpl.INSTANCE;
}
current = new SecurityInitialHandler(deploymentInfo.getAuthenticationMode(), deploymentInfo.getIdentityManager(), mechName, contextFactory, current);
} else {
current = initialSecurityWrapper.wrap(current);
}
return current;
}
Aggregations