Search in sources :

Example 11 with Response

use of org.eclipse.jetty.server.Response in project cxf by apache.

the class JettyHTTPDestinationTest method setUpDoService.

private void setUpDoService(boolean setRedirectURL, boolean sendResponse, boolean decoupled, String method, String query, int status) throws Exception {
    is = EasyMock.createMock(ServletInputStream.class);
    os = EasyMock.createMock(ServletOutputStream.class);
    request = EasyMock.createMock(Request.class);
    response = EasyMock.createMock(Response.class);
    request.getMethod();
    EasyMock.expectLastCall().andReturn(method).atLeastOnce();
    // request.getConnection();
    // EasyMock.expectLastCall().andReturn(null).anyTimes();
    request.getUserPrincipal();
    EasyMock.expectLastCall().andReturn(null).anyTimes();
    if (setRedirectURL) {
        policy.setRedirectURL(NOWHERE + "foo/bar");
        response.sendRedirect(EasyMock.eq(NOWHERE + "foo/bar"));
        EasyMock.expectLastCall();
        response.flushBuffer();
        EasyMock.expectLastCall();
        request.setHandled(true);
        EasyMock.expectLastCall();
    } else {
        // getQueryString for if statement
        request.getQueryString();
        EasyMock.expectLastCall().andReturn(query);
        if ("GET".equals(method) && "?wsdl".equals(query)) {
            verifyGetWSDLQuery();
        } else {
            // test for the post
            EasyMock.expect(request.getAttribute(AbstractHTTPDestination.CXF_CONTINUATION_MESSAGE)).andReturn(null);
            // EasyMock.expect(request.getMethod()).andReturn(method);
            EasyMock.expect(request.getInputStream()).andReturn(is);
            EasyMock.expect(request.getContextPath()).andReturn("/bar");
            EasyMock.expect(request.getServletPath()).andReturn("");
            EasyMock.expect(request.getPathInfo()).andReturn("/foo");
            EasyMock.expect(request.getRequestURI()).andReturn("/foo");
            EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer("http://localhost/foo")).anyTimes();
            EasyMock.expect(request.getCharacterEncoding()).andReturn(StandardCharsets.UTF_8.name());
            EasyMock.expect(request.getQueryString()).andReturn(query);
            EasyMock.expect(request.getHeader("Accept")).andReturn("*/*");
            EasyMock.expect(request.getContentType()).andReturn("text/xml charset=utf8").times(2);
            EasyMock.expect(request.getAttribute("org.eclipse.jetty.ajax.Continuation")).andReturn(null);
            EasyMock.expect(request.getAttribute("http.service.redirection")).andReturn(null).anyTimes();
            HttpFields httpFields = new HttpFields();
            httpFields.add("content-type", "text/xml");
            httpFields.add("content-type", "charset=utf8");
            httpFields.put(JettyHTTPDestinationTest.AUTH_HEADER, JettyHTTPDestinationTest.BASIC_AUTH);
            EasyMock.expect(request.getHeaderNames()).andReturn(httpFields.getFieldNames());
            request.getHeaders("content-type");
            EasyMock.expectLastCall().andReturn(httpFields.getValues("content-type"));
            request.getHeaders(JettyHTTPDestinationTest.AUTH_HEADER);
            EasyMock.expectLastCall().andReturn(httpFields.getValues(JettyHTTPDestinationTest.AUTH_HEADER));
            EasyMock.expect(request.getInputStream()).andReturn(is);
            request.setHandled(true);
            EasyMock.expectLastCall();
            response.flushBuffer();
            EasyMock.expectLastCall();
            if (sendResponse) {
                response.setStatus(status);
                EasyMock.expectLastCall();
                response.setContentType("text/xml charset=utf8");
                EasyMock.expectLastCall();
                response.addHeader(EasyMock.isA(String.class), EasyMock.isA(String.class));
                EasyMock.expectLastCall().anyTimes();
                response.setContentLength(0);
                EasyMock.expectLastCall().anyTimes();
                response.getOutputStream();
                EasyMock.expectLastCall().andReturn(os);
                response.getStatus();
                EasyMock.expectLastCall().andReturn(status).anyTimes();
                response.flushBuffer();
                EasyMock.expectLastCall();
            }
            request.getAttribute("javax.servlet.request.cipher_suite");
            EasyMock.expectLastCall().andReturn("anythingwilldoreally");
            request.getAttribute("javax.net.ssl.session");
            EasyMock.expectLastCall().andReturn(null);
            request.getAttribute("javax.servlet.request.X509Certificate");
            EasyMock.expectLastCall().andReturn(null);
        }
    }
    if (decoupled) {
        setupDecoupledBackChannel();
    }
    EasyMock.replay(response);
    EasyMock.replay(request);
}
Also used : Response(org.eclipse.jetty.server.Response) ServletInputStream(javax.servlet.ServletInputStream) ServletOutputStream(javax.servlet.ServletOutputStream) HttpFields(org.eclipse.jetty.http.HttpFields) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 12 with Response

use of org.eclipse.jetty.server.Response in project jetty.project by eclipse.

the class GzipHttpOutputInterceptor method commit.

protected void commit(ByteBuffer content, boolean complete, Callback callback) {
    // Are we excluding because of status?
    Response response = _channel.getResponse();
    int sc = response.getStatus();
    if (sc > 0 && (sc < 200 || sc == 204 || sc == 205 || sc >= 300)) {
        LOG.debug("{} exclude by status {}", this, sc);
        noCompression();
        if (sc == 304) {
            String request_etags = (String) _channel.getRequest().getAttribute("o.e.j.s.h.gzip.GzipHandler.etag");
            String response_etag = response.getHttpFields().get(HttpHeader.ETAG);
            if (request_etags != null && response_etag != null) {
                String response_etag_gzip = etagGzip(response_etag);
                if (request_etags.contains(response_etag_gzip))
                    response.getHttpFields().put(HttpHeader.ETAG, response_etag_gzip);
            }
        }
        _interceptor.write(content, complete, callback);
        return;
    }
    // Are we excluding because of mime-type?
    String ct = response.getContentType();
    if (ct != null) {
        ct = MimeTypes.getContentTypeWithoutCharset(ct);
        if (!_factory.isMimeTypeGzipable(StringUtil.asciiToLowerCase(ct))) {
            LOG.debug("{} exclude by mimeType {}", this, ct);
            noCompression();
            _interceptor.write(content, complete, callback);
            return;
        }
    }
    // Has the Content-Encoding header already been set?
    HttpFields fields = response.getHttpFields();
    String ce = fields.get(HttpHeader.CONTENT_ENCODING);
    if (ce != null) {
        LOG.debug("{} exclude by content-encoding {}", this, ce);
        noCompression();
        _interceptor.write(content, complete, callback);
        return;
    }
    // Are we the thread that commits?
    if (_state.compareAndSet(GZState.MIGHT_COMPRESS, GZState.COMMITTING)) {
        // We are varying the response due to accept encoding header.
        if (_vary != null) {
            if (fields.contains(HttpHeader.VARY))
                fields.addCSV(HttpHeader.VARY, _vary.getValues());
            else
                fields.add(_vary);
        }
        long content_length = response.getContentLength();
        if (content_length < 0 && complete)
            content_length = content.remaining();
        _deflater = _factory.getDeflater(_channel.getRequest(), content_length);
        if (_deflater == null) {
            LOG.debug("{} exclude no deflater", this);
            _state.set(GZState.NOT_COMPRESSING);
            _interceptor.write(content, complete, callback);
            return;
        }
        fields.put(GZIP._contentEncoding);
        _crc.reset();
        _buffer = _channel.getByteBufferPool().acquire(_bufferSize, false);
        BufferUtil.fill(_buffer, GZIP_HEADER, 0, GZIP_HEADER.length);
        // Adjust headers
        response.setContentLength(-1);
        String etag = fields.get(HttpHeader.ETAG);
        if (etag != null)
            fields.put(HttpHeader.ETAG, etagGzip(etag));
        LOG.debug("{} compressing {}", this, _deflater);
        _state.set(GZState.COMPRESSING);
        gzip(content, complete, callback);
    } else
        callback.failed(new WritePendingException());
}
Also used : Response(org.eclipse.jetty.server.Response) HttpFields(org.eclipse.jetty.http.HttpFields) WritePendingException(java.nio.channels.WritePendingException)

Example 13 with Response

use of org.eclipse.jetty.server.Response 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 14 with Response

use of org.eclipse.jetty.server.Response in project jetty.project by eclipse.

the class LoginAuthenticator method renewSession.

/* ------------------------------------------------------------ */
/** Change the session id.
     * The session is changed to a new instance with a new ID if and only if:<ul>
     * <li>A session exists.
     * <li>The {@link org.eclipse.jetty.security.Authenticator.AuthConfiguration#isSessionRenewedOnAuthentication()} returns true.
     * <li>The session ID has been given to unauthenticated responses
     * </ul>
     * @param request the request
     * @param response the response
     * @return The new session.
     */
protected HttpSession renewSession(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession(false);
    if (_renewSession && httpSession != null) {
        synchronized (httpSession) {
            //(indicated by SESSION_SECURED not being set on the session) then we should change id
            if (httpSession.getAttribute(Session.SESSION_CREATED_SECURE) != Boolean.TRUE) {
                if (httpSession instanceof Session) {
                    Session s = (Session) httpSession;
                    String oldId = s.getId();
                    s.renewId(request);
                    s.setAttribute(Session.SESSION_CREATED_SECURE, Boolean.TRUE);
                    if (s.isIdChanged() && response != null && (response instanceof Response))
                        ((Response) response).addCookie(s.getSessionHandler().getSessionCookie(s, request.getContextPath(), request.isSecure()));
                    LOG.debug("renew {}->{}", oldId, s.getId());
                } else
                    LOG.warn("Unable to renew session " + httpSession);
                return httpSession;
            }
        }
    }
    return httpSession;
}
Also used : Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpSession(javax.servlet.http.HttpSession) HttpSession(javax.servlet.http.HttpSession) Session(org.eclipse.jetty.server.session.Session)

Example 15 with Response

use of org.eclipse.jetty.server.Response in project jetty.project by eclipse.

the class SecurityHandler method handle.

/* ------------------------------------------------------------ */
/*
     * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, int)
     */
@Override
public void handle(String pathInContext, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final Response base_response = baseRequest.getResponse();
    final Handler handler = getHandler();
    if (handler == null)
        return;
    final Authenticator authenticator = _authenticator;
    if (checkSecurity(baseRequest)) {
        //See Servlet Spec 3.1 sec 13.6.3
        if (authenticator != null)
            authenticator.prepareRequest(baseRequest);
        RoleInfo roleInfo = prepareConstraintInfo(pathInContext, baseRequest);
        // Check data constraints
        if (!checkUserDataPermissions(pathInContext, baseRequest, base_response, roleInfo)) {
            if (!baseRequest.isHandled()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                baseRequest.setHandled(true);
            }
            return;
        }
        // is Auth mandatory?
        boolean isAuthMandatory = isAuthMandatory(baseRequest, base_response, roleInfo);
        if (isAuthMandatory && authenticator == null) {
            LOG.warn("No authenticator for: " + roleInfo);
            if (!baseRequest.isHandled()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                baseRequest.setHandled(true);
            }
            return;
        }
        // check authentication
        Object previousIdentity = null;
        try {
            Authentication authentication = baseRequest.getAuthentication();
            if (authentication == null || authentication == Authentication.NOT_CHECKED)
                authentication = authenticator == null ? Authentication.UNAUTHENTICATED : authenticator.validateRequest(request, response, isAuthMandatory);
            if (authentication instanceof Authentication.Wrapped) {
                request = ((Authentication.Wrapped) authentication).getHttpServletRequest();
                response = ((Authentication.Wrapped) authentication).getHttpServletResponse();
            }
            if (authentication instanceof Authentication.ResponseSent) {
                baseRequest.setHandled(true);
            } else if (authentication instanceof Authentication.User) {
                Authentication.User userAuth = (Authentication.User) authentication;
                baseRequest.setAuthentication(authentication);
                if (_identityService != null)
                    previousIdentity = _identityService.associate(userAuth.getUserIdentity());
                if (isAuthMandatory) {
                    boolean authorized = checkWebResourcePermissions(pathInContext, baseRequest, base_response, roleInfo, userAuth.getUserIdentity());
                    if (!authorized) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN, "!role");
                        baseRequest.setHandled(true);
                        return;
                    }
                }
                handler.handle(pathInContext, baseRequest, request, response);
                if (authenticator != null)
                    authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
            } else if (authentication instanceof Authentication.Deferred) {
                DeferredAuthentication deferred = (DeferredAuthentication) authentication;
                baseRequest.setAuthentication(authentication);
                try {
                    handler.handle(pathInContext, baseRequest, request, response);
                } finally {
                    previousIdentity = deferred.getPreviousAssociation();
                }
                if (authenticator != null) {
                    Authentication auth = baseRequest.getAuthentication();
                    if (auth instanceof Authentication.User) {
                        Authentication.User userAuth = (Authentication.User) auth;
                        authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
                    } else
                        authenticator.secureResponse(request, response, isAuthMandatory, null);
                }
            } else {
                baseRequest.setAuthentication(authentication);
                if (_identityService != null)
                    previousIdentity = _identityService.associate(null);
                handler.handle(pathInContext, baseRequest, request, response);
                if (authenticator != null)
                    authenticator.secureResponse(request, response, isAuthMandatory, null);
            }
        } catch (ServerAuthException e) {
            // jaspi 3.8.3 send HTTP 500 internal server error, with message
            // from AuthException
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } finally {
            if (_identityService != null)
                _identityService.disassociate(previousIdentity);
        }
    } else
        handler.handle(pathInContext, baseRequest, request, response);
}
Also used : Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Aggregations

Response (org.eclipse.jetty.server.Response)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 Request (org.eclipse.jetty.server.Request)8 IOException (java.io.IOException)6 ServletException (javax.servlet.ServletException)4 HttpSession (javax.servlet.http.HttpSession)4 Authentication (org.eclipse.jetty.server.Authentication)4 Server (org.eclipse.jetty.server.Server)4 HttpCookie (org.eclipse.jetty.http.HttpCookie)3 Writer (java.io.Writer)2 URISyntaxException (java.net.URISyntaxException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 RequestDispatcher (javax.servlet.RequestDispatcher)2 ServletRequest (javax.servlet.ServletRequest)2 ServletResponse (javax.servlet.ServletResponse)2 HttpFields (org.eclipse.jetty.http.HttpFields)2 ServerAuthException (org.eclipse.jetty.security.ServerAuthException)2 UserAuthentication (org.eclipse.jetty.security.UserAuthentication)2 DeferredAuthentication (org.eclipse.jetty.security.authentication.DeferredAuthentication)2