use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project tomcat by apache.
the class TestMapperWebapps method testRedirect.
@Test
public void testRedirect() throws Exception {
// Disable the following of redirects for this test only
boolean originalValue = HttpURLConnection.getFollowRedirects();
HttpURLConnection.setFollowRedirects(false);
try {
Tomcat tomcat = getTomcatInstance();
// Use standard test webapp as ROOT
File rootDir = new File("test/webapp");
org.apache.catalina.Context root = tomcat.addWebapp(null, "", rootDir.getAbsolutePath());
// Add a security constraint
SecurityConstraint constraint = new SecurityConstraint();
SecurityCollection collection = new SecurityCollection();
collection.addPatternDecoded("/welcome-files/*");
collection.addPatternDecoded("/welcome-files");
constraint.addCollection(collection);
constraint.addAuthRole("foo");
root.addConstraint(constraint);
// Also make examples available
File examplesDir = new File(getBuildDirectory(), "webapps/examples");
org.apache.catalina.Context examples = tomcat.addWebapp(null, "/examples", examplesDir.getAbsolutePath());
examples.setMapperContextRootRedirectEnabled(false);
// Then block access to the examples to test redirection
RemoteAddrValve rav = new RemoteAddrValve();
rav.setDeny(".*");
rav.setDenyStatus(404);
examples.getPipeline().addValve(rav);
tomcat.start();
// Redirects within a web application
doRedirectTest("/welcome-files", 401);
doRedirectTest("/welcome-files/", 401);
doRedirectTest("/jsp", 302);
doRedirectTest("/jsp/", 404);
doRedirectTest("/WEB-INF", 404);
doRedirectTest("/WEB-INF/", 404);
// Redirects between web applications
doRedirectTest("/examples", 404);
doRedirectTest("/examples/", 404);
} finally {
HttpURLConnection.setFollowRedirects(originalValue);
}
}
use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project jaggery by wso2.
the class TomcatJaggeryWebappsDeployer method handleWebappDeployment.
/**
* Deployment procedure of Jaggery apps
*
* @param webappFile The Jaggery app file to be deployed
* @param contextStr jaggery app context string
* @param webContextParams context-params for this Jaggery app
* @param applicationEventListeners Application event listeners
* @throws CarbonException If a deployment error occurs
*/
protected void handleWebappDeployment(File webappFile, String contextStr, List<WebContextParameter> webContextParams, List<Object> applicationEventListeners) throws CarbonException {
String filename = webappFile.getName();
ArrayList<Object> listeners = new ArrayList<Object>(1);
// listeners.add(new CarbonServletRequestListener());
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setAuthConstraint(true);
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.setName("ConfigDir");
securityCollection.setDescription("Jaggery Configuration Dir");
securityCollection.addPattern("/" + JaggeryCoreConstants.JAGGERY_CONF_FILE);
securityConstraint.addCollection(securityCollection);
WebApplicationsHolder webApplicationsHolder = WebAppUtils.getWebappHolder(webappFile.getAbsolutePath(), configurationContext);
try {
JSONObject jaggeryConfigObj = readJaggeryConfig(webappFile);
Tomcat tomcat = DataHolder.getCarbonTomcatService().getTomcat();
Context context = DataHolder.getCarbonTomcatService().addWebApp(contextStr, webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
//deploying web app for url mapping inside virtual host
if (DataHolder.getHotUpdateService() != null) {
List<String> hostNames = DataHolder.getHotUpdateService().getMappigsPerWebapp(contextStr);
for (String hostName : hostNames) {
Host host = DataHolder.getHotUpdateService().addHost(hostName);
/* ApplicationContext.getCurrentApplicationContext().putUrlMappingForApplication(hostName, contextStr);
*/
Context contextForHost = DataHolder.getCarbonTomcatService().addWebApp(host, "/", webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
log.info("Deployed JaggeryApp on host: " + contextForHost);
}
}
Manager manager = context.getManager();
if (isDistributable(context, jaggeryConfigObj)) {
//Clusterable manager implementation as DeltaManager
context.setDistributable(true);
// Using clusterable manager
CarbonTomcatClusterableSessionManager sessionManager;
if (manager instanceof CarbonTomcatClusterableSessionManager) {
sessionManager = (CarbonTomcatClusterableSessionManager) manager;
sessionManager.setOwnerTenantId(tenantId);
} else {
sessionManager = new CarbonTomcatClusterableSessionManager(tenantId);
context.setManager(sessionManager);
}
Object alreadyinsertedSMMap = configurationContext.getProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP);
if (alreadyinsertedSMMap != null) {
((Map<String, CarbonTomcatClusterableSessionManager>) alreadyinsertedSMMap).put(context.getName(), sessionManager);
} else {
sessionManagerMap.put(context.getName(), sessionManager);
configurationContext.setProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP, sessionManagerMap);
}
} else {
if (manager instanceof CarbonTomcatSessionManager) {
((CarbonTomcatSessionManager) manager).setOwnerTenantId(tenantId);
} else if (manager instanceof CarbonTomcatSessionPersistentManager) {
((CarbonTomcatSessionPersistentManager) manager).setOwnerTenantId(tenantId);
log.debug(manager.getInfo() + " enabled Tomcat HTTP Session Persistent mode using " + ((CarbonTomcatSessionPersistentManager) manager).getStore().getInfo());
} else {
context.setManager(new CarbonTomcatSessionManager(tenantId));
}
}
context.setReloadable(false);
JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
webapp.setServletContextParameters(webContextParams);
webapp.setState("Started");
webApplicationsHolder.getStartedWebapps().put(filename, webapp);
webApplicationsHolder.getFaultyWebapps().remove(filename);
registerApplicationEventListeners(applicationEventListeners, context);
log.info("Deployed webapp: " + webapp);
} catch (Throwable e) {
//catching a Throwable here to avoid web-apps crashing the server during startup
StandardContext context = new StandardContext();
context.setName(webappFile.getName());
context.addParameter(WebappsConstants.FAULTY_WEBAPP, "true");
JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
webapp.setProperty(WebappsConstants.WEBAPP_FILTER, JaggeryConstants.JAGGERY_WEBAPP_FILTER_PROP);
String msg = "Error while deploying webapp: " + webapp;
log.error(msg, e);
webapp.setFaultReason(new Exception(msg, e));
webApplicationsHolder.getFaultyWebapps().put(filename, webapp);
webApplicationsHolder.getStartedWebapps().remove(filename);
throw new CarbonException(msg, e);
}
}
use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project tomee by apache.
the class CdiEventRealm method findSecurityConstraints.
@Override
public SecurityConstraint[] findSecurityConstraints(final Request request, final Context context) {
final SecurityConstraint[] sc = super.findSecurityConstraints(request, context);
if (beanManager() == null) {
return sc;
}
final FindSecurityConstraintsEvent event = new FindSecurityConstraintsEvent(request.getRequest(), context.getPath());
beanManager().fireEvent(event);
if (!event.getRoles().isEmpty()) {
final SecurityConstraint s = new SecurityConstraint();
final SecurityCollection collection = new SecurityCollection();
// only for the current request
collection.addPattern("/*");
collection.addMethod(request.getMethod());
s.addCollection(collection);
if (event.getUserConstraint() != null) {
s.setUserConstraint(event.getUserConstraint());
}
for (final String r : event.getRoles()) {
s.addAuthRole(r);
}
return new SecurityConstraint[] { s };
}
return sc;
}
use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project tomee by apache.
the class TomcatWsRegistry method createNewContext.
private static Context createNewContext(final ClassLoader classLoader, String authMethod, String transportGuarantee, final String realmName, final String name) {
String path = name;
if (path == null) {
path = "/";
}
if (!path.startsWith("/")) {
path = "/" + path;
}
final StandardContext context = new IgnoredStandardContext();
context.setPath(path);
context.setDocBase("");
context.setParentClassLoader(classLoader);
context.setDelegate(true);
context.setName(name);
((TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);
// Configure security
if (authMethod != null) {
authMethod = authMethod.toUpperCase();
}
if (transportGuarantee != null) {
transportGuarantee = transportGuarantee.toUpperCase();
}
if (authMethod == null || "NONE".equals(authMethod)) {
//NOPMD
// ignore none for now as the NonLoginAuthenticator seems to be completely hosed
} else if ("BASIC".equals(authMethod) || "DIGEST".equals(authMethod) || "CLIENT-CERT".equals(authMethod)) {
//Setup a login configuration
final LoginConfig loginConfig = new LoginConfig();
loginConfig.setAuthMethod(authMethod);
loginConfig.setRealmName(realmName);
context.setLoginConfig(loginConfig);
//Setup a default Security Constraint
final String securityRole = SystemInstance.get().getProperty(TOMEE_JAXWS_SECURITY_ROLE_PREFIX + name, "default");
for (final String role : securityRole.split(",")) {
final SecurityCollection collection = new SecurityCollection();
collection.addMethod("GET");
collection.addMethod("POST");
collection.addPattern("/*");
collection.setName(role);
final SecurityConstraint sc = new SecurityConstraint();
sc.addAuthRole("*");
sc.addCollection(collection);
sc.setAuthConstraint(true);
sc.setUserConstraint(transportGuarantee);
context.addConstraint(sc);
context.addSecurityRole(role);
}
//Set the proper authenticator
if ("BASIC".equals(authMethod)) {
context.addValve(new BasicAuthenticator());
} else if ("DIGEST".equals(authMethod)) {
context.addValve(new DigestAuthenticator());
} else if ("CLIENT-CERT".equals(authMethod)) {
context.addValve(new SSLAuthenticator());
} else if ("NONE".equals(authMethod)) {
context.addValve(new NonLoginAuthenticator());
}
context.getPipeline().addValve(new OpenEJBValve());
} else {
throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
}
return context;
}
use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project fru-paqx-parent by dellemc-symphony.
the class ContextConfig method servletContainer.
@Bean
public /**
* This container is required in order to implement the redirect from http 8080 to https 18443 in spring boot.
* This means that http can continue to be used but will automatically redirect to https
* The responses from FRU will be https regardless of the protocol/port used by the cli.
*/
EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
@Override
protected /**
* This is the method where ssl is configured in the tomcat container.
* We want to override this in order to be able to take an encrypted-base64-encoded password from
* application.properties and to decode+decrypt it and provide it to the Ssl object before ssl configuration begins.
*/
void configureSsl(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) {
if (LOG.isDebugEnabled()) {
LOG.debug("ContextConfig: servletContainer: encoded password = " + ssl.getKeyStorePassword());
}
byte[] decodedBytes = Base64.getDecoder().decode(ssl.getKeyStorePassword());
ssl.setKeyStorePassword(new String(decodedBytes));
super.configureSsl(protocol, ssl);
}
};
//Setup the redirection
tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
//Setup the custom realm, which sets the custom redirect code.
//By default the redirect is 302. But if the request to be redirected is a post,
//then the post is converted to a get and therefore the post's body is removed in the redirect. (e.g. using CURL)
//We need to set the redirection with code 307 so that the origin method is used in the redirect
//e.g. get uses get on redirect and post uses post on redirect.
//This conforms to standard RFC 2616
tomcat.addContextCustomizers((TomcatContextCustomizer) context -> {
RealmBase base = new CombinedRealm();
base.setTransportGuaranteeRedirectStatus(307);
context.setRealm(base);
});
return tomcat;
}
Aggregations