Resolving cookie cross-domain access

Source: Internet
Author: User
Tags in domain to domain lintcode nginx reverse proxy

First, preface

With more and more project modules, many modules are now deployed independently. Communication between modules can sometimes be done through cookies. For example, portals and applications, respectively, deployed in different machines or web containers, if the user logged in after the browser client will write a cookie (the user context information), the application wants to get the cookie under the portal, which creates a cross-domain cookie problem.  

ii. introduction of Cookies Cookie path:

Cookies are generally created as a result of a user's access to a page, but this cookie is not accessible only on the page where the cookie was created. By default, for security reasons, only pages that are in the same directory as the page in which the cookie was created or on a subdirectory of the Create cookie page are accessible. At this point, if you want the parent or the entire page to be able to use cookies, you need to set the path.

Path represents the directory where the cookie resides, and the default is/, the root directory. On the same server, there are directories as follows:/test/,/test/cd/,/test/dd/, a cookie1 path for/test/,cookie2 is now set to/test/cd/, Then all pages under test can be accessed to cookie1, while/test/and/test/dd/'s sub-pages cannot access cookie2. This is because cookies allow pages in their path to be accessed.

The method that allows this set of cookies to be accessed by other directories or by the parent directory:

Document.cookie = "name = value; path=/";
Cookie domain:

Domain is the field that contains the cookie, and the default is the requested address, such as the URL is www.jb51.net/test/test.aspx, then domain defaults to www.jb51.net. and cross-domain access, If domain A is t1.test.com and domain B is t2.test.com, then a cookie that is made available to domain A and domain B is produced in Domain A to set the cookie's domain to. test.com; If you want to produce a cookie in domain A that makes domain a inaccessible and domain B can access the The domain of the cookie is set to t2.test.com.

Three, to solve the cookie cross-domain problem of nginx reverse proxy reverse proxy concept

The reverse proxy method is a proxy server that accepts connection requests on the Internet, then forwards requests to servers on the internal network, and returns the results from the server to the clients that request connections on the Internet, Reverse. At this point the proxy server is represented as a server externally.

The reverse proxy server is like the original server for the client, and the client does not need to make any special settings. The client sends a normal request to the content in the reverse proxy's namespace (name-space), and then the reverse proxy determines where (the originating server) forwards the request and returns the obtained content to the client, as if the content had been its own.

Scene simulation Two engineering Web1, WEB2, deployed on the same machine on different Tomcat, request Web1 Project index.html, as follows: then click on the link Request WEB2 Project index.jsp, the contents are as follows:

Then look at the Nginx configuration, as follows:

Worker_processes 2; events {Worker_connections65535;}    HTTP {include mime.types; Default_type Application/octet-stream;Log_format Main' $remote _addr-$remote _user [$time _local] "$request" ' $status $body _bytes_sent ' $http _referer ' ' "$http _user_agent" "$http _x_forwarded_for" '; Server_names_hash_bucket_size128;    Client_header_buffer_size 32k; Large_client_header_buffers432k;    Client_body_buffer_size 8m;    Server_tokens off;    Ignore_invalid_headers on;    Recursive_error_pages on;    Server_name_in_redirect off;    Sendfile on;    Tcp_nopush on;    Tcp_nodelay on; #keepalive_timeout0; Keepalive_timeout65; Upstream web1{Server127.0.0.1:8089 max_fails=0 Weight=1; } upstream web2 {server127.0.0.1:8080 max_fails=0 Weight=1; }    Server {Listen80; server_name127.0.0.1; CharSet UTF-8;      Index index.html;  Location/web/web1 {Proxy_pass http://Web1/web1;Proxy_set_header Host 127.0.0.1; Proxy_set_header X-real-IP $remote _addr; Proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for;            Proxy_set_header Cookie $http _cookie;        Log_subrequest on; } Location/WEB/WEB2 {Proxy_pass http://web2/web2;Proxy_set_header Host 127.0.0.1; Proxy_set_header X-real-IP $remote _addr; Proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for;            Proxy_set_header Cookie $http _cookie;        Log_subrequest on; }  Location/nginxstatus {stub_status on;        Access_log on; } error_page502 503 504/50x.html; Location =/50x.html {root html; }    }}
This guarantees that the cookie will be in the same domain. The output of the index.jsp in the WEB2 project is as follows: Summing up the use of Nginx direction agent to solve the problem of cross-domain cookie, in fact, through the "cheat" browser to achieve, through nginx, we can put different works of the cookie into the Nginx domain, The Nginx reverse proxy can be used to fetch cookies written by different projects.In fact, in the above scenario $.cookie ("User", "Hjzgg", {path: "/web"}), the path in the above can be written as "/", so the Nginx configuration is much simpler, as follows.
Location/web1 {proxy_pass http://Web1;Proxy_set_header Host 127.0.0.1; Proxy_set_header X-real-IP $remote _addr; Proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for;            Proxy_set_header Cookie $http _cookie;        Log_subrequest on; } Location/web2 {proxy_pass http://web2;Proxy_set_header Host 127.0.0.1; Proxy_set_header X-real-IP $remote _addr; Proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for;            Proxy_set_header Cookie $http _cookie;        Log_subrequest on; } 
Iv. Jsonp Way to solve the cross-domain problem of Cookies request jquery requests cross-domain: jquery There are two types of solutions for cross-domain requests for Ajax, but only the Get method is supported.  The Jquery.ajax Jsonp format and Jquery.getscript method of jquery are respectively. JSONP format: If the obtained data file resides on a remote server (the domain name is different, that is, the data is obtained across domains), you need to use the JSONP type. With this type, a query string parameter callback= is created? , this parameter is appended to the URL of the request. The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request. This means that the remote server needs to do the processing of the returned data, according to the callback parameters submitted by the client, return a callback (JSON) data, and the client will process the return data in script to do the JSON data.  Jquery.getjson also supports JSONP data-mode invocation. Scenario Simulation:

Two engineering web1, WEB2, are deployed on different tomcat on the same machine locally, with ports 8080 and 8089, respectively.

Web2/index.html content is as follows:

  

Web2/cooke.jsp content is as follows:

  

 

Web1/index.html content is as follows:

  

  

Test process, first access to the Http://localhost:8089/web2/index.html,F12,Network view via Google Chrome, view the content as follows:

  

  

Or, you can view the cookie written by using the privacy settings, display advanced settings, browser settings, as follows.

    

Next, open another window to access http://localhost:8080/web1/index.html, which is the cookie that requests the WEB2 project to write (note that if we do not access it by JSONP Way, then the browser will appear Prompts that do not allow cross-domain access ). Similarly F12, the network view, view the returned data as follows.

  

  

  

At this point, through the JSONP request to complete the cookie cross-domain carry, that is, the WEB1 project successfully received the WEB2 project directory of cookies. It can be found that the JSONP will handle the data returned by the server by the callback function, because the returned JS code (that is, the path and domain of the rewrite cookie), and then automatically executes the returned JS code, to achieve the purpose.

Nodejs to solve the problem of cross-domain of cookies superagent

module dependencies in the Package.json:

  

Call the Superagent API request:

  

Six, do not forget to brush the problem after work

Lintcode Simple Topic Analysis Lintcode Medium topic Analysis

Resolve cookie Cross-domain access

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.