跨域资源共享(CORS)用于本地主机和域名

huangapple go评论74阅读模式
英文:

CORS for localhost and domain

问题

我正在使用以下代码为基于Java/Jersey的Web应用程序设置CORS。

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);
}

我的客户端代码是基于ReactJS的,API调用如下:

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

问题:
每次我需要在本地主机和域之间切换时,我都要使用以下代码行:

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

或者我必须允许所有域,如下所示:

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

问题:
是否有任何方法可以在同一行中添加本地主机和域,就像以下代码一样?

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

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"]);

答案1

得分: 1

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

// 在过滤器方法中
String origin = request.getHeader("ORIGIN");
if (origin != null) {
    if (allowedOrigins.contains(origin)) {
        response.addHeader("Access-Control-Allow-Origin", origin);
    } else {
        // 结束请求并发送 403 禁止访问响应
    }
}
英文:

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: &lt;origin&gt;. 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&lt;String&gt; allowedOrigins
        = Arrays.asList(&quot;http://localhost:3000&quot;,
                        &quot;http://digitran-virtualtestengineer.tk&quot;);

// in filter method
String origin = request.getHeader(&quot;ORIGIN&quot;);
if (origin != null) {
    if (allowedOrigins.contains(origin)) {
        response.addHeader(&quot;Access-Control-Allow-Origin&quot;, 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.

答案2

得分: -1

最终的代码如下所示:

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);
}
英文:

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(&quot;origin&quot;);
    			 System.out.println(&quot;url inside doFilter = &quot;+url);
    			 System.out.println(&quot;clientOrigin inside doFilter = &quot;+clientOrigin);
    			}
    		HttpServletResponse resp = (HttpServletResponse) response;
    		if (clientOrigin != null) {
    		    if (allowedOrigins.contains(clientOrigin)) {
    		    	resp.addHeader(&quot;Access-Control-Allow-Origin&quot;, clientOrigin);
    		    } 
    		}		
    
    		resp.addHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;*&quot;);
    		resp.addHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;*&quot;);
    		chain.doFilter(request, response);
    	}

huangapple
  • 本文由 发表于 2020年10月14日 22:27:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64355485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定