users@glassfish.java.net

Re: Problem with Request Header Referer

From: <glassfish_at_javadesktop.org>
Date: Thu, 20 Nov 2008 13:31:40 PST

Here is the servlet filter code

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jacques Belissent
 */
public class RequireRefererFilter implements Filter {

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

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

                HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        
                String referer = httpRequest.getHeader("Referer");
                if (referer == null) {
            httpResponse.setStatus(401);
                } else {
                        chain.doFilter(request, response);
                }
        }
}

Add this to an application that makes an xhr call from a web page. Something like this will do:

<html>
        <head>
                <title></title>
                <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        </head>
        <body>
                <script>
                        var URL = "http://localhost:8080";

                        // Get the XHR object
                        var request = new XMLHttpRequest();
                        request.onreadystatechange = function(){
                                if (request.readyState == 4) {
                                        var success = ((!request.status) || (request.status >= 200 && request.status < 300));
                                        if (success) {
                                                alert("success");
                                        } else {
                                                alert("fail with status: " + request.status);
                                        }
                                }
                        }
                        
                        request.open("POST", URL, true);
                        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded" + "; charset=" + "UTF-8");
                        request.send("someparam=somevalue");

                </script>
        </body>
</html>
[Message sent by forum member 'jbelis' (jbelis)]

http://forums.java.net/jive/thread.jspa?messageID=317950