0

I am using the following code to set CORS for Java/Jersey based web application.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
//      resp.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        resp.addHeader("Access-Control-Allow-Origin", "*");
//      resp.addHeader("Access-Control-Allow-Origin", "http://digitran-virtualtestengineer.tk");
        resp.addHeader("Access-Control-Allow-Headers", "*");
        resp.addHeader("Access-Control-Allow-Methods", "*");
        chain.doFilter(request, response);
    }

My client code is ReactJS based and the API call is made as follows:

axios.post("http://localhost:9900/upload/file", data, config )

Problem: Every time I have to switch between localhost and domain by using the following lines of code:

resp.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
resp.addHeader("Access-Control-Allow-Origin", "http://digitran-virtualtestengineer.tk");

or I have to allow all domains as follows:

resp.addHeader("Access-Control-Allow-Origin", "*");

Question:

Is there any way to add both localhost and domain in the same line like the following code?

resp.addHeader("Access-Control-Allow-Origin", ["http://digitran-virtualtestengineer.tk", "http://localhost:3000"]);
Anbunathan
  • 37
  • 6
  • 1
    Why not externalise that configuration, so you can set it from an env var in different environments? This simplifies your code and makes it more flexible to deploy to a new environment, too. – jonrsharpe Oct 14 '20 at 14:31
  • Does this answer your question? [Access-Control-Allow-Origin Multiple Origin Domains?](https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains) – Norbert Bicsi Oct 14 '20 at 14:44
  • Do you really need `http://digitran-virtualtestengineer.tk` in `Access-Control-Allow-Origin` at all? You only need it if the live site HTML comes from a different domain than where the live API is hosted. – Christian Oct 14 '20 at 15:26
  • Thanks for every one. I will try and come back – Anbunathan Oct 15 '20 at 18:22

2 Answers2

1

A CORS request will have an Origin header. This header is what asks the server "is that origin allowed?" The server responds back with Access-Control-Allow-Origin: <origin>. You can use a * signifying that all origins are allowed, or you can use a single origin, generally the origin requested with the Origin header or only a single origin that you allow.

So what you should do is get the Origin header from the HttpServletRequest. Then keeps a list of origins you want to allow. Then check the origin against the list making sure the origin is in the list. If it is, then add that origin as the value for the Access-Control-Allow-Origin header. Something like

// class member
final List<String> allowedOrigins
        = Arrays.asList("http://localhost:3000",
                        "http://digitran-virtualtestengineer.tk");

// in filter method
String origin = request.getHeader("ORIGIN");
if (origin != null) {
    if (allowedOrigins.contains(origin)) {
        response.addHeader("Access-Control-Allow-Origin", origin);
    } else {
        // end request and send 403 Forbidden response
    }
}

Also, as mentioned by @jonrsharpe, you should consider adding these allowed origins to a configuration file. You can construct the list from this file. This is a common practice in a production project.

Paul Samsotha
  • 188,774
  • 31
  • 430
  • 651
  • In addition to this, the following link provides additional info. https://stackoverflow.com/questions/4389596/how-can-i-get-the-request-url-from-a-java-filter – Anbunathan Oct 17 '20 at 20:08
-1

The final code is as given below:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String url = null;
            String clientOrigin = null;
            if (request instanceof HttpServletRequest) {
                 url = ((HttpServletRequest)request).getRequestURL().toString();             
                 clientOrigin = ((HttpServletRequest)request).getHeader("origin");
                 System.out.println("url inside doFilter = "+url);
                 System.out.println("clientOrigin inside doFilter = "+clientOrigin);
                }
            HttpServletResponse resp = (HttpServletResponse) response;
            if (clientOrigin != null) {
                if (allowedOrigins.contains(clientOrigin)) {
                    resp.addHeader("Access-Control-Allow-Origin", clientOrigin);
                } 
            }       
    
            resp.addHeader("Access-Control-Allow-Headers", "*");
            resp.addHeader("Access-Control-Allow-Methods", "*");
            chain.doFilter(request, response);
        }
Anbunathan
  • 37
  • 6