Example usage for javax.servlet FilterChain FilterChain

List of usage examples for javax.servlet FilterChain FilterChain

Introduction

In this page you can find the example usage for javax.servlet FilterChain FilterChain.

Prototype

FilterChain

Source Link

Usage

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithContainsMatching() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    context.addInitParameter("ignorePattern", "=valueToIgnore");
    context.addInitParameter("ignoreUrlPatternType", "CONTAINS");
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
    request.setRequestURI(URL);/*from   w  w w  . j  av  a2 s.c om*/

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    assertNull(response.getRedirectedUrl());
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithExactMatching() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    final URL url = new URL(CAS_SERVICE_URL + "?param=valueToIgnore");

    context.addInitParameter("ignorePattern", url.toExternalForm());
    context.addInitParameter("ignoreUrlPatternType", "EXACT");
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme(url.getProtocol());
    request.setServerName(url.getHost());
    request.setServerPort(url.getPort());
    request.setQueryString(url.getQuery());
    request.setRequestURI(url.getPath());

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);/*  w  w  w  . j a v  a 2 s  . c  o m*/

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    assertNull(response.getRedirectedUrl());
}

From source file:org.primeframework.mvc.test.RequestBuilder.java

void run() throws IOException, ServletException {
    // Remove the web objects if this instance is being used across multiple invocations
    ServletObjectsHolder.clearServletRequest();
    ServletObjectsHolder.clearServletResponse();

    // Build the request and response for this pass
    filter.doFilter(this.request, this.response, new FilterChain() {
        @Override/* ww  w . j a  v  a  2 s  .  c  o  m*/
        public void doFilter(ServletRequest request, ServletResponse response) {
            throw new UnsupportedOperationException("The RequestSimulator class doesn't support testing "
                    + "URIs that don't map to Prime resources");
        }
    });

    // Add these back so that anything that needs them can be retrieved from the Injector after
    // the run has completed (i.e. MessageStore for the MVC and such)
    ServletObjectsHolder.setServletRequest(new HttpServletRequestWrapper(this.request));
    ServletObjectsHolder.setServletResponse(this.response);
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithExactClassname() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    context.addInitParameter("ignorePattern", "=valueToIgnore");
    context.addInitParameter("ignoreUrlPatternType", ContainsPatternUrlPatternMatcherStrategy.class.getName());
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
    request.setRequestURI(URL);/*from  w  w  w.ja  v  a  2  s .c o  m*/

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    assertNull(response.getRedirectedUrl());
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithInvalidClassname() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    context.addInitParameter("ignorePattern", "=valueToIgnore");
    context.addInitParameter("ignoreUrlPatternType", "unknown.class.name");
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    final String URL = CAS_SERVICE_URL + "?param=valueToIgnore";
    request.setRequestURI(URL);//  www.  j  av  a2s .c om

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    System.out.println(response.getRedirectedUrl());
}

From source file:com.ge.predix.web.cors.test.CORSFilterTest.java

private static FilterChain newMockFilterChain() {
    FilterChain filterChain = new FilterChain() {

        @Override//from ww  w  . ja va  2s  . co m
        public void doFilter(final ServletRequest request, final ServletResponse response)
                throws IOException, ServletException {
            // Do nothing.
        }
    };
    return filterChain;
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    FilterChain filterChainWrapper = new FilterChain() {
        @Override/*from  www.  j  a v  a 2 s .c  om*/
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            if (isKerberos) {
                Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                String userName = readUserFromCookie(httpResponse);

                if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                    userName = httpRequest.getRemoteUser();
                }

                if ((existingAuth == null || !existingAuth.isAuthenticated())
                        && (!StringUtils.isEmpty(userName))) {

                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider
                            .getAuthoritiesFromUGI(userName);

                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                            principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

                    request.setAttribute("atlas.http.authentication.type", true);
                    LOG.info("Logged into Atlas as = {}", userName);
                }
            }
            // OPTIONS method is sent from quick start jersey atlas client
            if (httpRequest.getMethod().equals("OPTIONS")) {
                optionsServlet.service(request, response);
            } else {
                try {
                    String requestUser = httpRequest.getRemoteUser();
                    NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                    RequestContext requestContext = RequestContext.get();
                    if (requestContext != null) {
                        requestContext.setUser(requestUser);
                    }
                    LOG.info("Request from authenticated user: {}, URL={}", requestUser,
                            Servlets.getRequestURI(httpRequest));

                    filterChain.doFilter(servletRequest, servletResponse);
                } finally {
                    NDC.pop();
                }
            }
        }
    };

    try {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
        responseWrapper.setHeader("X-Frame-Options", "DENY");

        if (existingAuth == null) {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper, filterChain);
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    } catch (NullPointerException e) {
        LOG.error("Exception in AtlasAuthenticationFilter ", e);
        //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
        ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "Authentication is enabled and user is not specified. Specify user.name parameter");
    }
}

From source file:org.apache.falcon.security.BasicAuthFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    FilterChain filterChainWrapper = new FilterChain() {

        @Override/*from   w  w  w  .  j av  a 2  s  .c  o m*/
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

            if (httpRequest.getMethod().equals("OPTIONS")) { // option request meant only for authentication
                optionsServlet.service(request, response);
            } else {
                final String user = getUserFromRequest(httpRequest);
                if (StringUtils.isEmpty(user)) {
                    ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                            "User can't be empty");
                } else if (blackListedUsers.contains(user)) {
                    ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                            "User can't be a superuser:" + BLACK_LISTED_USERS_KEY);
                } else {
                    try {
                        String requestId = UUID.randomUUID().toString();
                        NDC.push(user + ":" + httpRequest.getMethod() + "/" + httpRequest.getPathInfo());
                        NDC.push(requestId);
                        CurrentUser.authenticate(user);
                        LOG.info("Request from user: {}, URL={}", user, getRequestUrl(httpRequest));

                        filterChain.doFilter(servletRequest, servletResponse);
                    } finally {
                        NDC.pop();
                        NDC.pop();
                    }
                }
            }
        }

        private String getUserFromRequest(HttpServletRequest httpRequest) {
            String user = httpRequest.getRemoteUser(); // this is available from wrapper in super class
            if (!StringUtils.isEmpty(user)) {
                return user;
            }

            user = httpRequest.getParameter("user.name"); // available in query-param
            if (!StringUtils.isEmpty(user)) {
                return user;
            }

            user = httpRequest.getHeader("Remote-User"); // backwards-compatibility
            if (!StringUtils.isEmpty(user)) {
                return user;
            }

            return null;
        }

        private String getRequestUrl(HttpServletRequest request) {
            StringBuffer url = request.getRequestURL();
            if (request.getQueryString() != null) {
                url.append("?").append(request.getQueryString());
            }

            return url.toString();
        }
    };

    super.doFilter(request, response, filterChainWrapper);
}

From source file:org.apache.falcon.security.FalconAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    FilterChain filterChainWrapper = new FilterChain() {

        @Override//from  w  ww .  j  a  v  a  2s.  c  om
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

            if (httpRequest.getMethod().equals("OPTIONS")) { // option request meant only for authentication
                optionsServlet.service(request, response);
            } else {
                final String user = Servlets.getUserFromRequest(httpRequest);
                if (StringUtils.isEmpty(user)) {
                    ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                            "Param user.name can't be empty");
                } else if (blackListedUsers.contains(user)) {
                    ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                            "User can't be a superuser:" + BLACK_LISTED_USERS_KEY);
                } else {
                    try {
                        NDC.push(user + ":" + httpRequest.getMethod() + "/" + httpRequest.getPathInfo());
                        String doAsUser = httpRequest.getParameter(DO_AS_PARAM);
                        CurrentUser.authenticate(user);
                        CurrentUser.proxyDoAsUser(doAsUser, HostnameFilter.get());
                        LOG.info("Request from authenticated user: {}, URL={}, doAs user: {}", user,
                                Servlets.getRequestURI(httpRequest), doAsUser);

                        filterChain.doFilter(servletRequest, servletResponse);
                    } finally {
                        NDC.pop();
                    }
                }
            }
        }
    };

    super.doFilter(request, response, filterChainWrapper);
}

From source file:org.opendaylight.controller.filtervalve.cors.FilterValve.java

public void invoke(final Request request, final Response response) throws IOException, ServletException {
    if (filterProcessor == null) {
        throw new IllegalStateException("Initialization error");
    }/*w  w w.j  a v  a  2 s.  c om*/

    FilterChain nextValveFilterChain = new FilterChain() {
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
            boolean reqEquals = Objects.equals(request, req);
            boolean respEquals = Objects.equals(response, resp);
            if (reqEquals == false || respEquals == false) {
                logger.error(
                        "Illegal change was detected by valve - request {} or "
                                + "response {} was replaced by a filter. This is not supported by this valve",
                        reqEquals, respEquals);
                throw new IllegalStateException("Request or response was replaced in a filter");
            }
            getNext().invoke(request, response);
        }
    };
    filterProcessor.process(request, response, nextValveFilterChain);
}