Example usage for com.google.common.net HttpHeaders REFERER

List of usage examples for com.google.common.net HttpHeaders REFERER

Introduction

In this page you can find the example usage for com.google.common.net HttpHeaders REFERER.

Prototype

String REFERER

To view the source code for com.google.common.net HttpHeaders REFERER.

Click Source Link

Document

The HTTP Referer header field name.

Usage

From source file:com.zimbra.cs.servlet.util.CsrfUtil.java

/**
 *
 * @param req//  w  ww  .j  a  va  2s  . c o  m
 * @param allowedRefHost
 * @return
 * @throws MalformedURLException
 */
public static boolean isCsrfRequestBasedOnReferrer(final HttpServletRequest req, final String[] allowedRefHost)
        throws MalformedURLException {

    List<String> allowedRefHostList = Arrays.asList(allowedRefHost);
    boolean csrfReq = false;

    String method = req.getMethod();
    if (!method.equalsIgnoreCase("POST")) {
        csrfReq = false;
        return csrfReq;
    }

    String host = getRequestHost(req);
    String referrer = req.getHeader(HttpHeaders.REFERER);
    String refHost = null;

    if (!StringUtil.isNullOrEmpty(referrer)) {
        URL refURL = null;
        if (referrer.contains("http") || referrer.contains("https")) {
            refURL = new URL(referrer);
        } else {
            refURL = new URL("http://" + referrer);
        }
        refHost = refURL.getHost().toLowerCase();
    }

    if (refHost == null) {
        csrfReq = false;
    } else if (refHost.equalsIgnoreCase(host)) {
        csrfReq = false;
    } else {
        if (allowedRefHost != null && allowedRefHostList.contains(refHost)) {
            csrfReq = false;
        } else {
            csrfReq = true;
        }
    }

    if (ZimbraLog.soap.isDebugEnabled()) {
        ZimbraLog.soap.debug("Host : %s, Referrer host :%s, Allowed Hosts:[%s] Soap req is %s", host, refHost,
                Joiner.on(',').join(allowedRefHostList), (csrfReq ? " not allowed." : " allowed."));
    }

    return csrfReq;
}

From source file:com.flowlogix.security.PassThruAuthenticationFilter.java

private static Optional<String> getReferer(HttpServletRequest request) {
    String referer = request.getHeader(HttpHeaders.REFERER);
    if (referer != null) {
        // do not switch to https if custom port is specified
        if (!referer.matches("^http:\\/\\/[A-z|.|[0-9]]+:[0-9]+\\/.*")) {
            referer = referer.replaceFirst("^http:", "https:");
        }//  w w w  . j  av  a 2  s.  c o m
    }

    return Optional.fromNullable(referer);
}

From source file:com.cloudera.oryx.als.serving.web.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    OryxRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;//from www.  jav a 2  s  .c om
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;/*from w  ww . j av a 2  s. c o m*/
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}

From source file:com.sector91.wit.http.CsrfInterceptor.java

@Override
public void intercept(Request request, Response response) throws HttpException {
    // Include information on the CSRF token cookie in the request metadata, so
    // that the csrfToken() method knows what parameters to set on the cookie.
    final Map<Object, Object> requestAttrs = request.getAttributes();
    requestAttrs.put(CookieParams.class, cookieParams);

    final String method = request.getMethod();
    // For "safe" requests (according to RFC 2616), assume no action is
    // performed and therefore no CSRF protection is needed.
    if ("GET".equals(method) || "HEAD".equals(method) || "OPTIONS".equals(method) || "TRACE".equals(method)) {
        return;/*from   w  w w  .  ja  va 2  s  . c  o m*/
    }
    // For POST, PUT, DELETE, etc. requests, check that a CSRF token was
    // received, either in a form field or in an X-CSRFToken header, and
    // throw an HTTP 403 Forbidden if it was not.
    final Cookie cookie = request.getCookie(cookieParams.name);
    if (cookie == null) {
        Log.debug(TAG, "CSRF check failed: Request does not contain CSRF token cookie.");
        throw new HttpException(Status.FORBIDDEN);
    }
    final String token = cookie.getValue();

    if (token.equals(request.getValue(CSRF_HEADER)) || token.equals(request.getParameter(FORM_KEY))) {
        if (request.isSecure()) {
            // If we're using HTTPS, an extra check is required to prevent
            // "man-in-the-middle" attacks. HTTPS requests reliably set the
            // Referer header, so check that this header is present and that
            // the request came from this domain.
            final String referer = request.getValue(HttpHeaders.REFERER);
            if (referer == null) {
                Log.debug(TAG, "CSRF check failed: HTTPS request has no referer.");
                throw new HttpException(Status.FORBIDDEN);
            }
            final String safeHost = "https://" + request.getValue(HttpHeaders.HOST);
            if (!referer.startsWith(safeHost)) {
                Log.debug(TAG, "CSRF check failed: Referer '" + referer + "' is not in HTTPS domain '"
                        + safeHost + "'.");
                throw new HttpException(Status.FORBIDDEN);
            }
        }
    } else {
        Log.debug(TAG, "CSRF check failed: Missing or invalid token.");
        throw new HttpException(Status.FORBIDDEN);
    }
}

From source file:com.tinspx.util.net.RefreshRedirect.java

private @Nullable Request doApply(Response cause, Request request, Refresh refresh) {
    if (Strings.isNullOrEmpty(refresh.location)) {
        request.uri(cause.uri());/*  w ww.j  a  v  a  2  s. co m*/
    } else {
        final URI uri;
        try {
            uri = new URI(refresh.location.trim());
        } catch (URISyntaxException ex) {
            request.onError(Errors.create(this, ex, "invalid refresh uri: %s", refresh.location));
            return null;
        }
        request.uri(cause.uri().resolve(uri));
    }
    boolean refererSet = false;
    if (preserveReferer && cause.request().headers().contains(HttpHeaders.REFERER)) {
        refererSet = true;
        request.headers().set(HttpHeaders.REFERER, cause.request().headers().last(HttpHeaders.REFERER));
    }
    if (!refererSet) {
        if (includeReferer) {
            request.headers().set(HttpHeaders.REFERER, cause.uri().toASCIIString());
        } else {
            request.headers().removeAll(HttpHeaders.REFERER);
        }
    }
    if (honorDelay && refresh.delay > 0) {
        long millis = (long) (refresh.delay * 1000);
        if (millis > 0) {
            request.properties().put(Request.REDIRECT_DELAY_MILLIS, millis);
        }
    }
    return request;
}

From source file:de.hybris.platform.secureportaladdon.interceptors.SecurePortalBeforeControllerHandler.java

/**
 * Method to handle the case that the referer of the request is empty. The execution of this method could be switched
 * off from project.properties./*from  w  ww  . j a  v a 2s. c o m*/
 */
protected HttpServletRequest hackRefererHeader(final HttpServletRequest request) {
    // Since the WebHttpSessionRequestCache of hybris uses the referer header, we need to make sure there is one.
    // If we access the site directly using something like powertools.local:9001/yb2bacceleratorstorefront/ we don't get a referer
    // header sent by the browser! Using the referer header is NOT recommended as it can be removed by firewalls, spoofed etc.
    return new HttpServletRequestWrapper(request) {
        @Override
        public String getHeader(final String name) {
            if (StringUtils.equalsIgnoreCase(name, HttpHeaders.REFERER)) {
                final String headerValue = super.getHeader(name);

                if (StringUtils.isNotBlank(headerValue)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("Referer header is present! The saved request will use '%s'.",
                                headerValue));
                    }
                    return headerValue;
                } else {
                    final String url = request.getRequestURL().toString();

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format(
                                "Referer header is empty! Creating a the URL '%s' for the SavedRequest.", url));
                    }

                    return url;
                }
            }
            return super.getHeader(name);
        }
    };
}