java - Cors filter for localhost and staging url -


we developing java-spring mvc project. in order client team able connect our services created corsfilter:

  @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception,     ioexception {  // populating header required cors  string responseurl = this.corsmap.get(request.getservername().tostring()); response.addheader(            "access-control-allow-origin",            (responseurl == null ? "https://default.ourcompany.com" : responseurl));  response.addheader(            "access-control-allow-credentials",            "true");  if (request.getheader("access-control-request-method") != null && "options".equals(request.getmethod())) {     // cors "pre-flight" request     response.addheader(                "access-control-allow-methods",                "get, post, put, delete");     response.addheader(                "access-control-allow-headers",                "x-requested-with,origin,content-type, accept"); }  filterchain.dofilter(              request,              response); } 

things note:

1) allow options incoming request.

2) allow specific ip "access-control-allow-headers" (since "access-control-allow-credentials"=true requires so)

3) map called corsmap contains client urls , mapping server urls, so:

10.110.0.55->http://localhost 10.110.0.66->https://some.other.url 

now have problem:

we use clients "http://localhost" , "http://some.other.url". how can achieve that? (the problem here single client url allowed, , if clients request can received multiple url - wont able determine allow).

for cross domain requests, request having "origin" header, later matched "access-control-allow-origin" response header (that provide in above filter).

so, think, coding dofilterinternal below should work:

@override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception,     ioexception {      string clienturl = request.getheader("origin");     response.addheader(            "access-control-allow-origin",            isinwhilelist(clienturl) ? clienturl : "https://default.ourcompany.com";     ... 

note:

the latest version of spring has a new way configure cors, has allowedorigins method, can take array of whitelisted urls.

you can refer spring lemon's source code concrete example.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -