saurav
saurav

Reputation: 5926

Handle CORS in java server side

We have some protected resources which we need to CORS enable. These resources can be fetched/created by get and post.

To handle CORS we have put the handling for preflighted options request in server side. We have a special header to be sent from clients which enables it to be a preflighted request as per https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

On receiving the options request with an origin header we allow the origin using "Access-Control-Allow-Origin" and make Access-Control-Allow-Credentials", "true".

My question is there anything else i need to do or can be there cases where browser does not send the preflighted options request ?

Best Regards,

Saurav

Upvotes: 1

Views: 898

Answers (1)

R. Karlus
R. Karlus

Reputation: 2256

Source: https://howtodoinjava.com/servlets/java-cors-filter-example/

public class CORSFilter implements Filter {

    public CORSFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("CORSFilter HTTP Request: " + request.getMethod());

        // Authorize (allow) all domains to consume the content
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // For HTTP OPTIONS verb/method reply with ACCEPTED status code -- per CORS handshake
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // pass the request along the filter chain
        chain.doFilter(request, servletResponse);
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

}

Upvotes: 1

Related Questions