Search in sources :

Example 6 with Response

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

the class JettyHttpContainer method handle.

@Override
public void handle(final String target, final Request request, final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException, ServletException {
    final Response response = Response.getResponse(httpServletResponse);
    final ResponseWriter responseWriter = new ResponseWriter(request, response, configSetStatusOverSendError);
    final URI baseUri = getBaseUri(request);
    final URI requestUri = getRequestUri(request, baseUri);
    try {
        final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, request.getMethod(), getSecurityContext(request), new MapPropertiesDelegate());
        requestContext.setEntityStream(request.getInputStream());
        final Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            requestContext.headers(headerName, headerValue == null ? "" : headerValue);
        }
        requestContext.setWriter(responseWriter);
        requestContext.setRequestScopedInitializer(injectionManager -> {
            injectionManager.<Ref<Request>>getInstance(REQUEST_TYPE).set(request);
            injectionManager.<Ref<Response>>getInstance(RESPONSE_TYPE).set(response);
        });
        // Mark the request as handled before generating the body of the response
        request.setHandled(true);
        appHandler.handle(requestContext);
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) URI(java.net.URI) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) ContainerException(org.glassfish.jersey.server.ContainerException) IOException(java.io.IOException)

Example 7 with Response

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

the class AuthenticatedEncryptedCookieFactory method getExpiredSessionCookie.

/**
   * Produces an expired cookie string, used to update/overwrite an existing cookie.
   *
   * @return serialized expired cookie with matching parameters to authenticating cookie.
   */
public NewCookie getExpiredSessionCookie() {
    HttpCookie cookie = new HttpCookie(config.getName(), "expired", config.getDomain(), config.getPath(), 0, config.isHttpOnly(), config.isSecure());
    Response response = new Response(null, null);
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
Also used : Response(org.eclipse.jetty.server.Response) HttpCookie(org.eclipse.jetty.http.HttpCookie)

Example 8 with Response

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

the class AuthenticatedEncryptedCookieFactory method cookieFor.

/**
   * Produces a cookie string for a given value and expiration.
   *
   * @param value value of new cookie.
   * @param expiration expiration time of cookie.
   * @return serialized cookie with given value and expiration.
   */
public NewCookie cookieFor(String value, ZonedDateTime expiration) {
    long maxAge = Duration.between(ZonedDateTime.now(clock), expiration).getSeconds();
    HttpCookie cookie = new HttpCookie(config.getName(), value, config.getDomain(), config.getPath(), maxAge, config.isHttpOnly(), config.isSecure());
    Response response = new Response(null, null);
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
Also used : Response(org.eclipse.jetty.server.Response) HttpCookie(org.eclipse.jetty.http.HttpCookie)

Example 9 with Response

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

the class XsrfProtection method generate.

public NewCookie generate(String session) {
    checkArgument(!session.isEmpty());
    String cookieValue = SHA512.hashString(session, UTF_8).toString();
    // HttpOnly MUST NOT be present for this cookie.
    HttpCookie cookie = new HttpCookie(config.getName(), cookieValue, config.getDomain(), config.getPath(), -1, config.isHttpOnly(), config.isSecure());
    Response response = new Response(null, null);
    response.addCookie(cookie);
    return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
Also used : Response(org.eclipse.jetty.server.Response) HttpCookie(org.eclipse.jetty.http.HttpCookie)

Example 10 with Response

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

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 = request.getSession(true);
    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 User && _loginService != null && !_loginService.validate(((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) 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)

Aggregations

Response (org.eclipse.jetty.server.Response)16 HttpServletResponse (javax.servlet.http.HttpServletResponse)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 Request (org.eclipse.jetty.server.Request)6 IOException (java.io.IOException)5 ServletException (javax.servlet.ServletException)4 HttpSession (javax.servlet.http.HttpSession)4 Authentication (org.eclipse.jetty.server.Authentication)4 HttpCookie (org.eclipse.jetty.http.HttpCookie)3 Server (org.eclipse.jetty.server.Server)3 URISyntaxException (java.net.URISyntaxException)2 RequestDispatcher (javax.servlet.RequestDispatcher)2 ServletRequest (javax.servlet.ServletRequest)2 ServletResponse (javax.servlet.ServletResponse)2 ServerAuthException (org.eclipse.jetty.security.ServerAuthException)2 UserAuthentication (org.eclipse.jetty.security.UserAuthentication)2 DeferredAuthentication (org.eclipse.jetty.security.authentication.DeferredAuthentication)2 User (org.eclipse.jetty.server.Authentication.User)2 Handler (org.eclipse.jetty.server.Handler)2 UserIdentity (org.eclipse.jetty.server.UserIdentity)2