Java Tour-cross-domain (CORS) __cors

Source: Internet
Author: User


What is cross-domain


Cors Full Name: Cross-origin Resource Sharing

In the application development of the former background separation, Cross-domain is the scene that needs to be handled frequently. Refers to access to different domain names of resources, access to static resources, such as CSS, GIF, form request, there is no cross-domain problem, generally speaking cross-domain problem, refers to the JavaScript cross-domain problem and the problem of cross-domain use of cookies (is used, not read content).

The root cause of cross-domain problems is the security restrictions of browsers, which prohibit dynamic resource requests across domains by default.

Reference Articles:

Http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html

AJAX post& Cross-domain solution-CORS

https://www.zhihu.com/question/26379635


Java server-side cross-domain resolution


A Java application that, in order to support Cross-domain, allows JavaScript scripts for other domain names to access resources for this application, typically configuring a cross-domain processing filter inside the web.xml.

<!--allow cross-domain-->
<filter>
    <filter-name>crossDomainFilter</filter-name>
    < Filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class>
    <init-param >
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</ param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name> crossdomainfilter</filter-name>
    <url-pattern>/*</url-pattern><!-- Configure Url-pattern--> that allow Cross-domain access
</filter-mapping>

The general wording of cross-domain filter is as follows:

@Component ("Crossdomainfilter") public class Crossdomainfilter implements Filter {private static Logger Errorlogger

    = Loggerfactory.getlogger (Logconstants.error); @Override public void init (Filterconfig filterconfig) throws servletexception {} @Override public void do Filter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, S
            ervletexception {try {httpservletrequest HttpRequest = (httpservletrequest) request;

            HttpServletResponse HttpResponse = (httpservletresponse) response;
            Cross-domain String origin = Httprequest.getheader ("origin");
            if (origin = = null) {Httpresponse.addheader ("Access-control-allow-origin", "*");
            else {httpresponse.addheader ("Access-control-allow-origin", Origin); } httpresponse.addheader ("Access-control-allow-headers", "Origin, X-requested-with, Content-type, Accept,x-cookie ");
            Httpresponse.addheader ("Access-control-allow-credentials", "true");
            Httpresponse.addheader ("Access-control-allow-methods", "Get,post,put,options,delete");
                if (Httprequest.getmethod (). Equals ("Options")) {httpresponse.setstatus (HTTPSERVLETRESPONSE.SC_OK);
            Return
        Chain.dofilter (request, response);
            catch (Exception e) {errorlogger.error ("Exception in Crossdomainfilter.dofilter", e);
        Throw e; @Override public void Destroy () {}}}


The principle of cross-domain solution


Https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS


1. When Cross-domain, the browser will first send the options request: Application of the Options method in Cross-domain request (CORS)

2, Access-control-allow-origin and cross-domain: http://www.tuicool.com/articles/7FVnMz

3, access-control-allow-credentials in cookie:http://zawa.iteye.com/blog/1868108, which is useful in SSO, The caller (a.com) brings the application (B.Com) cookie to SSO, which achieves the purpose of login authentication.


a case where a cookie can't be taken


In a real project, a cookie is not brought across the domain, and the backend has: Servletresponse.setheader ("Access-control-allow-methods", "Post,get,put,patch, DELETE ");

The front-end also has: Withcredentials:true configuration.

Problem-solving article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Since the browser sends a pre-check request, that is, the options, and the backend access-control-allow-methods does not have options, subsequent Cross-domain requests are terminated, and there is no subsequent cookie-carrying thing.


Two solutions for cross-domain time separation system of front and rear units


Scenario: The front end is a.com, and the back end is B.Com, the following two scenarios are resolved across domains:

1. Configurable to allow Cross-domain related configuration, A.com request B.Com, each time through a cross-domain configuration, the cookie or custom HTTP header content to b.com,b.com to get the relevant data for authentication; This approach is actually under a.com for user identity cookies; this way requires front-end processing login, write Co Okie and other operations;

2. Allow cross domain related configuration, A.com request B.Com, found no permissions, then request a login to the B.Com page, B.Com login, the user identity information species under the B.Com cookie; this way, the front-end is pure display layer, do not need to deal with login, write cookies and other operations.


Summary


Understand the browser behavior, and the HTTP protocol, you can have a more profound understanding of the cross-domain. Looks like this is more relevant to the front end. In actual work, it is also felt that the front end is more thorough to these understandings, the latter end of RD is more focus on performance, compared to care these technologies.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.