Home > php教程 > PHP开发 > cros cross-domain configuration

cros cross-domain configuration

高洛峰
Release: 2016-12-14 13:14:30
Original
1295 people have browsed it

The front-end application is a static site and is deployed under the http://web.xxx.com domain. The back-end application publishes REST API and is deployed under the http://api.xxx.com domain. How to make the front-end application cross-domain through AJAX What about accessing backend applications? This requires the use of CORS technology, which is currently the best solution.

[CORS stands for Cross Origin Resource Sharing (cross-domain resource sharing). The server only needs to add relevant response header information to enable the client to issue AJAX cross-domain requests. ]

CORS technology is very simple and easy to implement. At present, most browsers already support this technology (IE8 browser also supports it). The server can be implemented through any programming language, as long as the CORS response header can be written into the response in the object.

Next we continue to extend the REST framework and implement AJAX cross-domain access through CORS technology.

First, we need to write a Filter to filter all HTTP requests and write the CORS response header into the response object. The code is as follows:

public class CorsFilter implements Filter {  
  
    private String allowOrigin;  
    private String allowMethods;  
    private String allowCredentials;  
    private String allowHeaders;  
    private String exposeHeaders;  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
        allowOrigin = filterConfig.getInitParameter("allowOrigin");  
        allowMethods = filterConfig.getInitParameter("allowMethods");  
        allowCredentials = filterConfig.getInitParameter("allowCredentials");  
        allowHeaders = filterConfig.getInitParameter("allowHeaders");  
        exposeHeaders = filterConfig.getInitParameter("exposeHeaders");  
    }  
  
    @Override  
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest request = (HttpServletRequest) req;  
        HttpServletResponse response = (HttpServletResponse) res;  
        if (StringUtil.isNotEmpty(allowOrigin)) {  
            List<String> allowOriginList = Arrays.asList(allowOrigin.split(","));  
            if (CollectionUtil.isNotEmpty(allowOriginList)) {  
                String currentOrigin = request.getHeader("Origin");  
                if (allowOriginList.contains(currentOrigin)) {  
                    response.setHeader("Access-Control-Allow-Origin", currentOrigin);  
                }  
            }  
        }  
        if (StringUtil.isNotEmpty(allowMethods)) {  
            response.setHeader("Access-Control-Allow-Methods", allowMethods);  
        }  
        if (StringUtil.isNotEmpty(allowCredentials)) {  
            response.setHeader("Access-Control-Allow-Credentials", allowCredentials);  
        }  
        if (StringUtil.isNotEmpty(allowHeaders)) {  
            response.setHeader("Access-Control-Allow-Headers", allowHeaders);  
        }  
        if (StringUtil.isNotEmpty(exposeHeaders)) {  
            response.setHeader("Access-Control-Expose-Headers", exposeHeaders);  
        }  
        chain.doFilter(req, res);  
    }  
  
    @Override  
    public void destroy() {  
    }  
}
Copy after login

The above CorsFilter will read the relevant Filter initialization parameters from web.xml, And these parameters will be written into the corresponding CORS response headers when processing HTTP requests. The following is a rough description of the meaning of these CORS response headers:


Access-Control-Allow-Origin: the client domain name that is allowed to access, For example: http://web.xxx.com, if it is *, it means it can be accessed from any domain, that is, there is no restriction.

Access-Control-Allow-Methods: Method names that allow access. Multiple method names are separated by commas, such as: GET, POST, PUT, DELETE, OPTIONS.

Access-Control-Allow-Credentials: Whether to allow requests with verification information. If you want to obtain cookies under the client domain, you need to set it to true.

Access-Control-Allow-Headers: Client request headers that allow server access. Multiple request headers are separated by commas, for example: Content-Type.

Access-Control-Expose-Headers: Server response headers that allow client access. Multiple response headers are separated by commas.

It should be noted that the CORS specification defines that Access-Control-Allow-Origin only allows two values, either * or a specific domain name. In other words, configuring multiple domain names at the same time is not supported. In order to solve the problem across multiple domains, some processing needs to be done in the code. Here, the Filter initialization parameter is used as a collection of domain names (separated by commas). Just get the Origin request header from the current request to know which domain it is from. If the request is in the above allowed domain name set, it will be put into the Access-Control-Allow-Origin response header, so that the problem of crossing multiple domains can be easily solved.

The following is how to configure CorsFilter in web. It can be called arbitrarily when the user is not logged in. This is obviously unsafe. How to solve this problem? We need to provide security mechanism for REST requests.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template