Detailed description of how Javascript implements cross-origin background settings interception, javascript

Source: Internet
Author: User
Tags send cookies

Detailed description of how Javascript implements cross-origin background settings interception, javascript

This article mainly introduces you to the content related to the cross-origin backend settings of Javascript, and shares the content for your reference. If you don't have to talk about it, let's take a look at the details.

Cross-Domain

Conclusion:

1. The server must be set to allow cross-Origin

2. The client needs to set withCredentials to contain cookies.

3. Whether or not the server allows cross-origin requests, the request will be fully executed.

4. For options pre-requests, a blank response is required. Otherwise, if requestMapping does not support this method, an error occurs.

Environment Construction

Requirement

First, we need to build two environments. Server A that provides APIs and server B that requires cross-origin API access.

Server A provides an api. The complete request is:

Https://local.corstest.com.net: 8443/contentmain/getDepositsRoomAndRatePlanInfo. json? Htid = 759 & _ = 1490855801818

Server B has a page:

Http://cros.corstest.com.net: 3001/test.html

In addition, this page needs to request the api of server.

However, the request failed due to cross-origin protection:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxxxx' is therefore not allowed access.

Modify host

First, configure two local hosts pointing to 127.0.0.1 to facilitate cross-origin.

127.0.0.1 local.corstest.com.net 127.0.0.1 cros.corstest.com.net

Start Project A to provide APIs conveniently.

For Project B, you only need to write an html static page for cross-origin testing. Write a test.html file and publish it using a tool:

 browser-sync 

Install

npm install -g browser-sync

Start a test.html

browser-sync start --server --files "*.html" --host "cros.corstest.com.net" --port 3001

Cross-origin CORS

In ruanyifeng's article, the browser divides CORS requests into two types: simple request and not simple request ).

The following two criteria are met:

1) The request method is one of the following three methods:

  • HEAD
  • GET
  • POST

2) The HTTP header information does not exceed the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type: limited to three values: application/x-www-form-urlencoded, multipart/form-data, text/plain

In other cases, non-simple requests are requests that have special requirements on the server. For example, the request method is PUT or DELETE, or the Type of the Content-Type field is application/json. For non-simple requests, an HTTP query request (preflight) is added before the formal communication, that is, an options request.

Key

The key to cross-Origin is that the browser obtains the server's approval, and the server's approval is the Access-Control-Allow-Origin in the header. The browser determines whether to cross-origin by comparing whether the response returned by the server contains this field and whether the content containing this field is the current URL. That is to say, cross-origin is not required to bypass the browser.

There is a problem. I haven't pointed out many articles.

First, there is a cookie problem. If withCredentials is set to true in the browser, the cookie is sent to the server. If the value of Access-Control-Allow-Credentials on the server side is set to true, the server receives the message. If the value is false, the server does not accept the message. The key is to decide whether to set response when it comes to the filter. At this time, the cookie already exists in the request. (To be verified)

Verification:The server has indeed accepted the cookie. Even if it is set to false, the server still accepts the cookie. The client can still send cookies.

Second, in simple cross-origin, browser requests are directly sent to the server, and the server returns whether cross-origin is supported (that is, whether the header is added with origin). How many times does a simple cross-origin request come from the server? If it is once, if the server does not support cross-origin, that is, if allow is not set, will it continue? Will it continue to get the request result and put it into response? That is, whether the cross-origin or non-Cross-origin server executes the calculation of this request. Because all the header settings are sent to the browser, they are irrelevant to server restrictions. (To be verified)

Verification:Even if the server does not allow cross-origin, when the client requests, the server still executes the request completely and returns the result, but the client does not receive the request.

The server needs to do some work

For the above two types of cross-origin. Server A needs to write A filter.

<filter> <filter-name>cors</filter-name>  <filter-class>com.test.filter.CorsFilter</filter-class> </filter> <filter-mapping>  <filter-name>cors</filter-name>  <url-pattern>/*</url-pattern> </filter-mapping></filter>

Filter:

public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)   throws ServletException, IOException {  URL requestURL = new URL(request.getRequestURL().toString());  String hostName = requestURL.getHost();  String origin = request.getHeader("Origin");  int index = hostName.indexOf(".");  if(index > -1) {   String domainHost = hostName.substring(index, hostName.length());   if(!StringUtils.isEmpty(origin) && origin.contains(domainHost)) {    response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");    response.addHeader("Access-Control-Allow-Origin", origin);    response.addHeader("Access-Control-Allow-Credentials", "true");    response.setHeader("Access-Control-Max-Age", "3600");    response.addHeader("Access-Control-Allow-Headers", "Content-Type, Cookie, " +      "Accept-Encoding, User-Agent, " +      "Host, Referer, " +      "X-Requested-With, Accept, " +      "Accept-Language, Cache-Control, Connection");    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {     // CORS "pre-flight" request     response.setStatus(200);     return;    }   }  }  filterChain.doFilter(request, response); }}

The filter above aims to allow cross-domain access for different subdomains in the same domain, but not for other domains, because we need to share cookies, therefore, set Access-Control-Allow-Credentials to true. if it is set to false, the cookie is not accepted.

Client, that is, server B. If you want to send a cookie, set withCredentials to true.

// Native var xhr = new XMLHttpRequest (); xhr. withCredentials = true; // jquery $. ajax ({... xhrFields: {withCredentials: true }...});

Note:To send an options request for non-simple cross-origin requests, server A must tell the browser whether cross-origin is supported. Do not go down, otherwise, it will be embarrassing to find that the specified requestMapping does not support this method, so you will return it directly.

The following is a test of simple cross-origin and non-simple cross-origin:

<!DOCTYPE html>

Result:

GET default:

Send only one normal get request.

GET json:

First, send an options as follows:

General:Request URL:https://local.corstest.com.net:8443/contentmain/getDepositsRoomAndRatePlanInfo.json?htid=759Request Method:OPTIONSStatus Code:200 OKRemote Address:127.0.0.1:8443Response Headers:Access-Control-Allow-Credentials:trueAccess-Control-Allow-Headers:Content-Type, Cookie, Accept-Encoding, User-Agent, Host, Referer, X-Requested-With, Accept, Accept-Language, Cache-Control, ConnectionAccess-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONSAccess-Control-Allow-Origin:http://cros.corstest.com.net:3001Content-Length:0Date:Thu, 30 Mar 2017 12:47:44 GMTServer:Apache-Coyote/1.1Request Headers:Accept:*/*Accept-Encoding:gzip, deflate, sdch, brAccept-Language:zh-CN,zh;q=0.8Access-Control-Request-Headers:content-typeAccess-Control-Request-Method:GETConnection:keep-aliveHost:local.corstest.com.net:8443Origin:http://cros.corstest.com.net:3001Referer:http://cros.corstest.com.net:3001/test.htmlUser-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36

Then, send a normal Get request.

Post default:

Send requests normally.

Post json: first sends an options request. Then, send a normal request.

Similarly, in a non-simple cross-origin request, multiple options requests are sent to confirm whether cross-origin is supported. In this case, the server must return the support for cross-origin and directly return the support.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

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.