Search in sources :

Example 76 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class CsrfPreventionFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    ServletResponse wResponse = null;
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        boolean skipNonceCheck = false;
        if (Constants.METHOD_GET.equals(req.getMethod()) && entryPoints.contains(getRequestedPath(req))) {
            skipNonceCheck = true;
        }
        HttpSession session = req.getSession(false);
        @SuppressWarnings("unchecked") LruCache<String> nonceCache = (session == null) ? null : (LruCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
        if (!skipNonceCheck) {
            String previousNonce = req.getParameter(Constants.CSRF_NONCE_REQUEST_PARAM);
            if (nonceCache == null || previousNonce == null || !nonceCache.contains(previousNonce)) {
                res.sendError(getDenyStatus());
                return;
            }
        }
        if (nonceCache == null) {
            nonceCache = new LruCache<>(nonceCacheSize);
            if (session == null) {
                session = req.getSession(true);
            }
            session.setAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME, nonceCache);
        }
        String newNonce = generateNonce();
        nonceCache.add(newNonce);
        wResponse = new CsrfResponseWrapper(res, newNonce);
    } else {
        wResponse = response;
    }
    chain.doFilter(request, wResponse);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 77 with ServletResponse

use of javax.servlet.ServletResponse in project tomcat by apache.

the class TestAsyncContextImpl method testAsyncListenerSupplyRequestResponse.

@Test
public void testAsyncListenerSupplyRequestResponse() {
    final ServletRequest servletRequest = EasyMock.createMock(ServletRequest.class);
    final ServletResponse servletResponse = EasyMock.createMock(ServletResponse.class);
    final AsyncListener listener = new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        private void checkRequestResponse(AsyncEvent event) {
            assertEquals(servletRequest, event.getSuppliedRequest());
            assertEquals(servletResponse, event.getSuppliedResponse());
        }
    };
    final Context context = new TesterContext();
    final Response response = new Response();
    final Request request = new Request(null);
    request.setCoyoteRequest(new org.apache.coyote.Request());
    request.getMappingData().context = context;
    final AsyncContextImpl ac = new AsyncContextImpl(request);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setStarted(context, request, response, true);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setErrorState(new Exception(), true);
    ac.fireOnComplete();
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.apache.catalina.connector.Request) ServletRequest(javax.servlet.ServletRequest) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) ServletResponse(javax.servlet.ServletResponse) AsyncListener(javax.servlet.AsyncListener) TesterContext(org.apache.tomcat.unittest.TesterContext) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 78 with ServletResponse

use of javax.servlet.ServletResponse in project dropwizard by dropwizard.

the class CacheBustingFilterTest method passesThroughNonHttpRequests.

@Test
public void passesThroughNonHttpRequests() throws Exception {
    final ServletRequest req = mock(ServletRequest.class);
    final ServletResponse res = mock(ServletResponse.class);
    filter.doFilter(req, res, chain);
    verify(chain).doFilter(req, res);
    verifyZeroInteractions(res);
}
Also used : ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 79 with ServletResponse

use of javax.servlet.ServletResponse in project jetty.project by eclipse.

the class FormAuthenticator method validateRequest.

/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    Request base_request = Request.getBaseRequest(request);
    Response base_response = base_request.getResponse();
    String uri = request.getRequestURI();
    if (uri == null)
        uri = URIUtil.SLASH;
    mandatory |= isJSecurityCheck(uri);
    if (!mandatory)
        return new DeferredAuthentication(this);
    if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
        return new DeferredAuthentication(this);
    HttpSession session = null;
    try {
        session = request.getSession(true);
    } catch (Exception e) {
        if (LOG.isDebugEnabled())
            LOG.debug(e);
    }
    //unauthenticated
    if (session == null)
        return Authentication.UNAUTHENTICATED;
    try {
        // Handle a request for authentication.
        if (isJSecurityCheck(uri)) {
            final String username = request.getParameter(__J_USERNAME);
            final String password = request.getParameter(__J_PASSWORD);
            UserIdentity user = login(username, password, request);
            LOG.debug("jsecuritycheck {} {}", username, user);
            session = request.getSession(true);
            if (user != null) {
                // Redirect to original request
                String nuri;
                FormAuthentication form_auth;
                synchronized (session) {
                    nuri = (String) session.getAttribute(__J_URI);
                    if (nuri == null || nuri.length() == 0) {
                        nuri = request.getContextPath();
                        if (nuri.length() == 0)
                            nuri = URIUtil.SLASH;
                    }
                    form_auth = new FormAuthentication(getAuthMethod(), user);
                }
                LOG.debug("authenticated {}->{}", form_auth, nuri);
                response.setContentLength(0);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
                return form_auth;
            }
            // not authenticated
            if (LOG.isDebugEnabled())
                LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
            if (_formErrorPage == null) {
                LOG.debug("auth failed {}->403", username);
                if (response != null)
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else if (_dispatch) {
                LOG.debug("auth failed {}=={}", username, _formErrorPage);
                RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
                response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
                response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
                dispatcher.forward(new FormRequest(request), new FormResponse(response));
            } else {
                LOG.debug("auth failed {}->{}", username, _formErrorPage);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
            }
            return Authentication.SEND_FAILURE;
        }
        // Look for cached authentication
        Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (authentication != null) {
            // Has authentication been revoked?
            if (authentication instanceof Authentication.User && _loginService != null && !_loginService.validate(((Authentication.User) authentication).getUserIdentity())) {
                LOG.debug("auth revoked {}", authentication);
                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            } else {
                synchronized (session) {
                    String j_uri = (String) session.getAttribute(__J_URI);
                    if (j_uri != null) {
                        //check if the request is for the same url as the original and restore
                        //params if it was a post
                        LOG.debug("auth retry {}->{}", authentication, j_uri);
                        StringBuffer buf = request.getRequestURL();
                        if (request.getQueryString() != null)
                            buf.append("?").append(request.getQueryString());
                        if (j_uri.equals(buf.toString())) {
                            MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
                            if (j_post != null) {
                                LOG.debug("auth rePOST {}->{}", authentication, j_uri);
                                base_request.setContentParameters(j_post);
                            }
                            session.removeAttribute(__J_URI);
                            session.removeAttribute(__J_METHOD);
                            session.removeAttribute(__J_POST);
                        }
                    }
                }
                LOG.debug("auth {}", authentication);
                return authentication;
            }
        }
        // if we can't send challenge
        if (DeferredAuthentication.isDeferred(response)) {
            LOG.debug("auth deferred {}", session.getId());
            return Authentication.UNAUTHENTICATED;
        }
        // remember the current URI
        synchronized (session) {
            // But only if it is not set already, or we save every uri that leads to a login form redirect
            if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null)
                    buf.append("?").append(request.getQueryString());
                session.setAttribute(__J_URI, buf.toString());
                session.setAttribute(__J_METHOD, request.getMethod());
                if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
                    MultiMap<String> formParameters = new MultiMap<>();
                    base_request.extractFormParameters(formParameters);
                    session.setAttribute(__J_POST, formParameters);
                }
            }
        }
        // send the the challenge
        if (_dispatch) {
            LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
            RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
            response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
            dispatcher.forward(new FormRequest(request), new FormResponse(response));
        } else {
            LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
            int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
            base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
        }
        return Authentication.SEND_CONTINUE;
    } catch (IOException | ServletException e) {
        throw new ServerAuthException(e);
    }
}
Also used : User(org.eclipse.jetty.server.Authentication.User) HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) Constraint(org.eclipse.jetty.util.security.Constraint) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) MultiMap(org.eclipse.jetty.util.MultiMap) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Example 80 with ServletResponse

use of javax.servlet.ServletResponse in project jetty.project by eclipse.

the class FilterHolderTest method testInitialize.

@Test
public void testInitialize() throws Exception {
    ServletHandler handler = new ServletHandler();
    final AtomicInteger counter = new AtomicInteger(0);
    Filter filter = new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            counter.incrementAndGet();
        }

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

        @Override
        public void destroy() {
        }
    };
    FilterHolder fh = new FilterHolder();
    fh.setServletHandler(handler);
    fh.setName("xx");
    fh.setFilter(filter);
    try (StacklessLogging stackless = new StacklessLogging(FilterHolder.class)) {
        fh.initialize();
        fail("Not started");
    } catch (Exception e) {
    //expected
    }
    fh.start();
    fh.initialize();
    assertEquals(1, counter.get());
    fh.initialize();
    assertEquals(1, counter.get());
    fh.stop();
    assertEquals(1, counter.get());
    fh.start();
    assertEquals(1, counter.get());
    fh.initialize();
    assertEquals(2, counter.get());
}
Also used : ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Filter(javax.servlet.Filter) FilterChain(javax.servlet.FilterChain) FilterConfig(javax.servlet.FilterConfig) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

ServletResponse (javax.servlet.ServletResponse)155 ServletRequest (javax.servlet.ServletRequest)129 HttpServletResponse (javax.servlet.http.HttpServletResponse)104 HttpServletRequest (javax.servlet.http.HttpServletRequest)90 FilterChain (javax.servlet.FilterChain)81 Test (org.junit.Test)76 ServletException (javax.servlet.ServletException)59 IOException (java.io.IOException)57 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)35 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)35 MockFilterChain (org.springframework.mock.web.MockFilterChain)32 Filter (javax.servlet.Filter)28 HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)26 Injector (com.google.inject.Injector)25 NestedServletException (org.springframework.web.util.NestedServletException)19 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)18 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)18 FilterConfig (javax.servlet.FilterConfig)15 ErrorPage (org.springframework.boot.web.server.ErrorPage)15 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)14