Java Code Examples for javax.servlet.ServletRequest#isSecure()

The following examples show how to use javax.servlet.ServletRequest#isSecure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpHeaderSecurityFilter.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response.isCommitted()) {
        throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
    }

    // HSTS
    if (hstsEnabled && request.isSecure() && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
    }

    // anti click-jacking
    if (antiClickJackingEnabled && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(
                ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
    }

    // Block content type sniffing
    if (blockContentTypeSniffingEnabled && response instanceof HttpServletResponse) {
        ((HttpServletResponse) response).setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
    }
    chain.doFilter(request, response);
}
 
Example 2
Source File: X509AuthenticationFilter.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
private void authenticateIfPossible(ServletRequest request) {
    if (!request.isSecure()) {
        return;
    }

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if (certs == null || certs.length == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to get certificates in request from " + HttpRequestUtil.getClientString(request));
        }
        return;
    }

    Authentication authentication = authenticationManager.authenticate(new X509AuthenticationToken(certs));
    if (authentication.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
 
Example 3
Source File: HttpHeaderSecurityFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
        }

        // HSTS
        if (hstsEnabled && request.isSecure()) {
            httpResponse.setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
        }

        // anti click-jacking
        if (antiClickJackingEnabled) {
            httpResponse.setHeader(ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
        }

        // Block content type sniffing
        if (blockContentTypeSniffingEnabled) {
            httpResponse.setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                    BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
        }

        // cross-site scripting filter protection
        if (xssProtectionEnabled) {
            httpResponse.setHeader(XSS_PROTECTION_HEADER_NAME, XSS_PROTECTION_HEADER_VALUE);
        }
    }

    chain.doFilter(request, response);
}
 
Example 4
Source File: SecurityHeadersFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  final HttpServletResponse response = (HttpServletResponse) servletResponse;

  response.setHeader("x-content-type-options", "nosniff");
  response.setHeader("x-frame-options", "SAMEORIGIN");
  response.setHeader("x-xss-protection", "1; mode=block");

  if (servletRequest.isSecure()) {
    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
    response.setHeader("strict-transport-security", "max-age=" + STS_MAX_AGE);
  }

  filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 5
Source File: HttpHeaderSecurityFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (response.isCommitted()) {
            throw new ServletException(sm.getString("httpHeaderSecurityFilter.committed"));
        }

        // HSTS
        if (hstsEnabled && request.isSecure()) {
            httpResponse.setHeader(HSTS_HEADER_NAME, hstsHeaderValue);
        }

        // anti click-jacking
        if (antiClickJackingEnabled) {
            httpResponse.setHeader(ANTI_CLICK_JACKING_HEADER_NAME, antiClickJackingHeaderValue);
        }

        // Block content type sniffing
        if (blockContentTypeSniffingEnabled) {
            httpResponse.setHeader(BLOCK_CONTENT_TYPE_SNIFFING_HEADER_NAME,
                    BLOCK_CONTENT_TYPE_SNIFFING_HEADER_VALUE);
        }

        // cross-site scripting filter protection
        if (xssProtectionEnabled) {
            httpResponse.setHeader(XSS_PROTECTION_HEADER_NAME, XSS_PROTECTION_HEADER_VALUE);
        }
    }

    chain.doFilter(request, response);
}
 
Example 6
Source File: STSPortFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

    Assert.isTrue(applicationContext != null, "Application context must not be null");
    STSAuthenticationProvider authProvider = authenticationProvider;
    if (authProvider == null) {
        authProvider = applicationContext.getBean(STSAuthenticationProvider.class);
    }
    Assert.isTrue(authProvider != null, "STSAuthenticationProvider must be configured");

    //Only update the port if HTTPS is used, otherwise ignored (like retrieving the WADL over HTTP)
    if (!isPortSet && request.isSecure()) {
        try {
            URL url = new URL(authProvider.getWsdlLocation());
            if (url.getPort() == 0) {
                URL updatedUrl = new URL(url.getProtocol(), url.getHost(), request.getLocalPort(), url.getFile());
                setSTSWsdlUrl(authProvider, updatedUrl.toString());
                LOG.info("STSAuthenticationProvider.wsdlLocation set to " + updatedUrl.toString());
            } else {
                setSTSWsdlUrl(authProvider, url.toString());
            }
        } catch (MalformedURLException e) {
            LOG.error("Invalid Url '" + authProvider.getWsdlLocation() + "': "  + e.getMessage());
        }
    }

    chain.doFilter(request, response);
}
 
Example 7
Source File: IdentityFilter.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    // Only require authentication from an identity provider if the NiFi registry is running securely.
    if (!servletRequest.isSecure()) {
        // Otherwise, requests will be "authenticated" by the AnonymousIdentityFilter
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (identityProvider == null) {
        logger.warn("Identity Filter configured with NULL identity provider. Credentials will not be extracted.");
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (credentialsAlreadyPresent()) {
        logger.debug("Credentials already extracted for [{}], skipping credentials extraction filter using {}",
                SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(),
                identityProvider.getClass().getSimpleName());
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    logger.debug("Attempting to extract user credentials using {}", identityProvider.getClass().getSimpleName());

    try {
        AuthenticationRequest authenticationRequest = identityProvider.extractCredentials((HttpServletRequest)servletRequest);
        if (authenticationRequest != null) {
            Authentication authentication = new AuthenticationRequestToken(authenticationRequest, identityProvider.getClass(), servletRequest.getRemoteAddr());
            logger.debug("Adding credentials claim to SecurityContext to be authenticated. Credentials extracted by {}: {}",
                    identityProvider.getClass().getSimpleName(),
                    authenticationRequest);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // This filter's job, which is merely to search for and extract an identity claim, is done.
            // The actual authentication of the identity claim will be handled by a corresponding IdentityAuthenticationProvider
        }
    } catch (Exception e) {
        logger.debug("Exception occurred while extracting credentials:", e);
    }

    filterChain.doFilter(servletRequest, servletResponse);
}
 
Example 8
Source File: ResourceAuthorizationFilter.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

    boolean authorizationCheckIsRequired = false;
    String resourcePath = null;
    RequestAction action = null;

    // Only require authorization if the NiFi Registry is running securely.
    if (servletRequest.isSecure()) {

        // Only require authorization for resources for which this filter has been configured
        resourcePath = httpServletRequest.getServletPath();
        if (resourcePath != null) {
            final ResourceType resourceType = ResourceType.mapFullResourcePathToResourceType(resourcePath);
            final HttpMethodAuthorizationRules authorizationRules = resourceTypeAuthorizationRules.get(resourceType);
            if (authorizationRules != null) {
                final String httpMethodStr = httpServletRequest.getMethod().toUpperCase();
                HttpMethod httpMethod = HttpMethod.resolve(httpMethodStr);

                // Only require authorization for HTTP methods included in this resource type's rule set
                if (httpMethod != null && authorizationRules.requiresAuthorization(httpMethod)) {
                    authorizationCheckIsRequired = true;
                    action = authorizationRules.mapHttpMethodToAction(httpMethod);
                }
            }
        }
    }

    if (!authorizationCheckIsRequired) {
        forwardRequestWithoutAuthorizationCheck(httpServletRequest, httpServletResponse, filterChain);
        return;
    }

    // Perform authorization check
    try {
        authorizeAccess(resourcePath, action);
        successfulAuthorization(httpServletRequest, httpServletResponse, filterChain);
    } catch (Exception e) {
        logger.debug("Exception occurred while performing authorization check.", e);
        failedAuthorization(httpServletRequest, httpServletResponse, filterChain, e);
    }
}
 
Example 9
Source File: CookieFilter.java    From nexus-public with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Perform filtering on cookie headers.
 *
 * If the request is secure, examine response for cookies and adds the Secure flag if not already present in the
 * cookie value.
 */
protected void filterCookies(final ServletRequest request, final ServletResponse response) {
  if (request.isSecure() && response instanceof HttpServletResponse) {
    secureCookies((HttpServletResponse) response);
  }
}
 
Example 10
Source File: SslFilter.java    From tapestry-security with Apache License 2.0 2 votes vote down vote up
/**
 * Retains the parent method's port-matching behavior but additionally guarantees that the
 * {@code ServletRequest.}{@link javax.servlet.ServletRequest#isSecure() isSecure()}.  If the port does not match or
 * the request is not secure, access is denied.
 *
 * @param request     the incoming {@code ServletRequest}
 * @param response    the outgoing {@code ServletResponse} - ignored in this implementation
 * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings - ignored by this implementation.
 * @return {@code true} if the request is received on an expected SSL port and the
 *         {@code request.}{@link javax.servlet.ServletRequest#isSecure() isSecure()}, {@code false} otherwise.
 * @throws Exception if the call to {@code super.isAccessAllowed} throws an exception.
 * @since 0.4.1
 */
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
	return super.isAccessAllowed(request, response, mappedValue) && request.isSecure();
}