Search in sources :

Example 1 with SecurityCollection

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;
}
Also used : Context(org.apache.catalina.Context) CombinedRealm(org.apache.catalina.realm.CombinedRealm) Logger(org.slf4j.Logger) TomcatContextCustomizer(org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) LoggerFactory(org.slf4j.LoggerFactory) Connector(org.apache.catalina.connector.Connector) Context(org.apache.catalina.Context) EmbeddedServletContainerFactory(org.springframework.boot.context.embedded.EmbeddedServletContainerFactory) RealmBase(org.apache.catalina.realm.RealmBase) Configuration(org.springframework.context.annotation.Configuration) Ssl(org.springframework.boot.context.embedded.Ssl) TomcatEmbeddedServletContainerFactory(org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory) Base64(java.util.Base64) ConsumerContextConfig(com.dell.cpsd.service.common.client.context.ConsumerContextConfig) AbstractHttp11JsseProtocol(org.apache.coyote.http11.AbstractHttp11JsseProtocol) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) Bean(org.springframework.context.annotation.Bean) AbstractHttp11JsseProtocol(org.apache.coyote.http11.AbstractHttp11JsseProtocol) CombinedRealm(org.apache.catalina.realm.CombinedRealm) TomcatEmbeddedServletContainerFactory(org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory) RealmBase(org.apache.catalina.realm.RealmBase) Ssl(org.springframework.boot.context.embedded.Ssl) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) Bean(org.springframework.context.annotation.Bean)

Example 2 with SecurityCollection

use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project danyuan-application by 514840279.

the class App method servletContainer.

// @Bean
public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint constraint = new SecurityConstraint();
            constraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            constraint.addCollection(collection);
            context.addConstraint(constraint);
        }
    };
    tomcat.addAdditionalTomcatConnectors(httpConnector());
    return tomcat;
}
Also used : Context(org.apache.catalina.Context) TomcatEmbeddedServletContainerFactory(org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 3 with SecurityCollection

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);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) ArrayList(java.util.ArrayList) CarbonException(org.wso2.carbon.CarbonException) Host(org.apache.catalina.Host) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) Manager(org.apache.catalina.Manager) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) CarbonException(org.wso2.carbon.CarbonException) JSONObject(org.json.simple.JSONObject) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) StandardContext(org.apache.catalina.core.StandardContext) JSONObject(org.json.simple.JSONObject) Map(java.util.Map) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 4 with SecurityCollection

use of org.apache.tomcat.util.descriptor.web.SecurityCollection in project tomee by apache.

the class TomcatSecurityConstaintsToJaccPermissionsTransformer method analyzeSecurityConstraints.

private void analyzeSecurityConstraints() {
    for (SecurityConstraint securityConstraint : constraints) {
        Map<String, URLPattern> currentPatterns = null;
        Set<String> roleNames = null;
        if (securityConstraint.getAuthConstraint()) {
            if (securityConstraint.findAuthRoles().length == 0) {
                currentPatterns = excludedPatterns;
            } else {
                roleNames = new HashSet<String>(Arrays.asList(securityConstraint.findAuthRoles()));
                if (roleNames.remove("*")) {
                    roleNames.addAll(securityRoles);
                }
            }
        } else {
            currentPatterns = uncheckedPatterns;
        }
        String transport = securityConstraint.getUserConstraint() == null ? "NONE" : securityConstraint.getUserConstraint();
        boolean isRoleBasedPattern = (currentPatterns == null);
        if (securityConstraint.findCollections() != null) {
            for (SecurityCollection webResourceCollection : securityConstraint.findCollections()) {
                // Calculate HTTP methods list
                for (String urlPattern : webResourceCollection.findPatterns()) {
                    if (isRoleBasedPattern) {
                        for (String roleName : roleNames) {
                            Map<String, URLPattern> currentRolePatterns = rolesPatterns.get(roleName);
                            if (currentRolePatterns == null) {
                                currentRolePatterns = new HashMap<>();
                                rolesPatterns.put(roleName, currentRolePatterns);
                            }
                            boolean omission = false;
                            String[] httpMethods = webResourceCollection.findMethods();
                            if (httpMethods.length == 0) {
                                omission = true;
                                httpMethods = webResourceCollection.findOmittedMethods();
                            }
                            analyzeURLPattern(urlPattern, new HashSet<>(Arrays.asList(httpMethods)), omission, transport, currentRolePatterns);
                        }
                    } else {
                        boolean omission = false;
                        String[] httpMethods = webResourceCollection.findMethods();
                        if (httpMethods.length == 0) {
                            omission = true;
                            httpMethods = webResourceCollection.findOmittedMethods();
                        }
                        analyzeURLPattern(urlPattern, new HashSet<>(Arrays.asList(httpMethods)), omission, transport, currentPatterns);
                    }
                    URLPattern allPattern = allMap.get(urlPattern);
                    if (allPattern == null) {
                        boolean omission = false;
                        String[] httpMethods = webResourceCollection.findMethods();
                        if (httpMethods.length == 0) {
                            omission = true;
                            httpMethods = webResourceCollection.findOmittedMethods();
                        }
                        allPattern = new URLPattern(urlPattern, new HashSet<>(Arrays.asList(httpMethods)), omission);
                        allSet.add(allPattern);
                        allMap.put(urlPattern, allPattern);
                    } else {
                        boolean omission = false;
                        String[] httpMethods = webResourceCollection.findMethods();
                        if (httpMethods.length == 0) {
                            omission = true;
                            httpMethods = webResourceCollection.findOmittedMethods();
                        }
                        allPattern.addMethods(new HashSet<>(Arrays.asList(httpMethods)), omission);
                    }
                }
            }
        }
    }
}
Also used : SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) HashSet(java.util.HashSet)

Example 5 with SecurityCollection

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;
}
Also used : FindSecurityConstraintsEvent(org.apache.tomee.catalina.realm.event.FindSecurityConstraintsEvent) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Aggregations

SecurityCollection (org.apache.tomcat.util.descriptor.web.SecurityCollection)32 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)31 LoginConfig (org.apache.tomcat.util.descriptor.web.LoginConfig)17 Context (org.apache.catalina.Context)16 Tomcat (org.apache.catalina.startup.Tomcat)8 TesterServlet (org.apache.catalina.startup.TesterServlet)6 Test (org.junit.Test)6 BasicAuthenticator (org.apache.catalina.authenticator.BasicAuthenticator)5 ArrayList (java.util.ArrayList)4 TesterMapRealm (org.apache.catalina.startup.TesterMapRealm)4 AuthenticatorBase (org.apache.catalina.authenticator.AuthenticatorBase)3 SSLAuthenticator (org.apache.catalina.authenticator.SSLAuthenticator)3 StandardContext (org.apache.catalina.core.StandardContext)3 DefaultServlet (org.apache.catalina.servlets.DefaultServlet)3 TomcatEmbeddedServletContainerFactory (org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory)3 ClientEndpointConfig (jakarta.websocket.ClientEndpointConfig)2 File (java.io.File)2 HashSet (java.util.HashSet)2 lombok.val (lombok.val)2 DigestAuthenticator (org.apache.catalina.authenticator.DigestAuthenticator)2