1. Phenomenon description
1.1 Problem background
In modern web applications, front-end and back-end separation architecture has become a common development model. The front-end usually uses frameworks such as , while the back-end uses languages such as Java to build API services.
Under this architecture, the front-end and back-end may be deployed on different domain names or ports, which raises the problem of cross-domain requests. Cross-domain requests involve browsers’ homologous policies, especially when it comes to cookies, the problem becomes more complicated.
1.2 Specific phenomena
When the current-end application tries to send a request to the backend API and expects the cookies returned by the backend to be able to be used normally in the frontend, it may encounter the following problems:
- After the front-end sends the request, the back-end handles it normally and returns a response, which contains the Set-Cookie header.
- The browser received a response, but due to cross-domain issues, the Set-Cookie header was ignored, causing the cookie to be not set correctly.
- Subsequent requests may fail to maintain the user session or authentication fails due to the lack of necessary cookies.
1.3 Common tips
In this case, the front-end developer may see the following prompt in the console or in the network request panel:
- HTTP status code 400: Requests are denied, usually due to the lack of necessary authentication information (such as cookies).
CORS Error: Cross-domain resource sharing (CORS)-related error messages may appear in the browser console, such as:
Access to XMLHttpRequest at '/resource' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- Cookie Lost: When viewing the response header in the Network Request Panel, you may find that the Set-Cookie header exists, but the browser does not store it.
These phenomena show that although the backend service responds normally, the frontend fails to correctly receive or store cookies due to cross-domain issues, resulting in the failure of subsequent requests.
2. The principle of cross-domain cookies
2.1 What are Cookies
A cookie is a small data file sent by a server and stored on the client, which is used to save the user's status information. They are commonly used for several purposes:
- Session Management: Such as user login status, shopping cart content, etc.
- Personalized settings: Such as user preferences, theme selection, etc.
- track: Used to analyze user behavior and advertising delivery.
A cookie consists of key-value pairs and usually contains the following properties:
- name: The name of the cookie.
- value: The value of the cookie.
- domain: The domain to which the cookie belongs.
- path: The valid path to the cookie.
- expires/max-age: The validity period of a cookie.
- secure: Indicates that cookies can only be transmitted over HTTPS.
- HttpOnly: Indicates that cookies cannot be accessed through JavaScript.
- SameSite: Restrict the sending of cookies when cross-site requests.
2.2 Scope of cookies
The scope of cookies defines the circumstances under which they are sent to the server. It mainly includes the following aspects:
-
Domain: Cookies will only be sent within their domain and subdomain. For example, set as
The cookies will be in
It works too.
-
Path: Cookies are sent only within the specified path and their subpaths. For example, the path is
/app
The cookies will only be in/app
and/app/*
Valid below. -
Security (Secure): Marked as
Secure
The cookies are only sent in an HTTPS connection. -
HttpOnly: Marked as
HttpOnly
The cookies cannot be accessed through JavaScript, which increases security.
2.3 SameSite Properties
The SameSite attribute is used to prevent cross-site request forgery (CSRF) attacks and control the sending behavior of cookies in cross-site requests. This property has three values:
- Strict: Cross-site requests for sending cookies are completely prohibited. Cookies are sent only in requests that are exactly consistent with the site to which the cookie belongs.
- Lax: In cross-site requests, only GET requests navigating to the target site will send cookies. This is an option to balance security and availability.
-
None: Allow cross-site requests to send cookies, but must be set at the same time
Secure
property. In this case, cookies can be sent in all cross-site requests.
In actual applications, if the SameSite property is set improperly, it may cause cookies in cross-domain requests to be invalid, which will affect the user's session management and state retention.
3. Solution
3.1 Java backend solution
3.1.1 Configuring the SameSite property
To ensure that cookies can be correctly sent and received in cross-domain requests, the SameSite attribute of the cookie can be configured. The SameSite property has three values:
- Strict: Cookies are sent only in requests on the same site.
- Lax: Cookies are sent in the same site request and in some cross-site requests (such as GET requests).
- None: Cookies are sent in all cross-site requests, but the Secure property must be set at the same time.
Sample code:
import ; import ; public void setCookie(HttpServletResponse response) { Cookie cookie = new Cookie("key", "value"); ("/"); (true); (true); (7 * 24 * 60 * 60); // 1 week ("None"); // SameSite=None (cookie); }
3.1.2 Set Cookie Properties with Spring Boot
In Spring Boot, you can set the cookie attribute by configuring the class.
Sample code:
import ; import ; import ; @Configuration public class CookieConfig { @Bean public ServletWebServerFactory servletWebServerFactory() { TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); (context -> { (sessionCookieConfig -> { (()); (true); }); }); return factory; } }
3.1.3 Configuring CORS to solve cross-domain problems
In Spring Boot, cross-domain requests can be allowed by configuring CORS.
Sample code:
import ; import ; import ; import ; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { ("/**") .allowedOrigins("") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true) .allowedHeaders("*") .maxAge(3600); } }
3.2 Front-end solution
3.2.1 Vue Configuring Cross-Domain Requests
In Vue projects, you can configure itFile to set up proxy to solve cross-domain problems in development environments.
Sample code:
= { devServer: { proxy: { '/api': { target: '', changeOrigin: true, secure: false, pathRewrite: { '^/api': '' } } } } };
3.2.2 Send cross-domain requests using Axios
In Vue projects, Axios is usually used to send HTTP requests. Axios can be configured globally to support cross-domain requests.
Sample code:
import axios from 'axios'; = ''; = true; // Cookies allowed export default axios;
3.2.3 Setting the withCredentials property
When sending a specific request, it can also be set separatelywithCredentials
property.
Sample code:
('/api/some-endpoint', { withCredentials: true }).then(response => { (); });
3.3 Nginx Solution
3.3.1 Configuring Nginx to handle cross-domain
In an Nginx configuration file, cross-domain requests can be allowed by setting response headers.
Sample code:
server { listen 80; server_name ; location / { add_header 'Access-Control-Allow-Origin' ''; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization'; if ($request_method = 'OPTIONS') { return 204; } proxy_pass http://backend_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
3.3.2 Set Cookie Attributes
In Nginx, it can be passedproxy_cookie_path
Directive to set the SameSite property of the cookie.
Sample code:
server { listen 80; server_name ; location / { proxy_pass http://backend_server; proxy_cookie_path / "/; SameSite=None; Secure"; } }
3.4 Using and storing data
It is a mechanism for storing data in a browser, which has the following advantages:
- Persistence: The data is stored in the browser and remains after closing the browser until it is explicitly deleted.
-
Large capacity: Compared with the 4KB limit of cookies,
localStorage
The storage capacity is usually 5MB or more. - Simple and easy to use: Provides a simple API interface that can easily store and read data.
3.4.1 Code example: Store data
In the page where data is required, we can useMethod to store data to
localStorage
middle. Suppose we have a JSON objectjsonData
, need to includeredirectData
Store it.
// Suppose jsonData is the data object we need to storeconst jsonData = { redirectData: "exampleData" }; //Storage data in localStorage('redirectData', ()); // Verify that the data is stored successfully('Data stored in localStorage:', ('redirectData'));
3.4.2 Code Example: Getting Data
In the target page, we can useMethod from
localStorage
Read data in.
// Get data from localStorageconst storedData = ('redirectData'); // Check whether the data existsif (storedData) { const redirectData = (storedData); ('Data retrieved from localStorage:', redirectData); } else { ('No data found in localStorage.'); }
3.4.3 How the solution works
useThe working principle of solving cross-domain cookie failure problems is as follows:
Data storage:
- On pages where data needs to be passed, use
Method to store data to
localStorage
middle.localStorage
It is a storage mechanism based on the domain name (origin), so the stored data is accessible on all pages under the same domain name.
Data acquisition:
- In the target page, use
Method from
localStorage
Read data in. becauselocalStorage
It is a persistent storage, and the data remains after the browser is closed until it is explicitly deleted.
Data delivery:
- By sharing between different pages under the same domain name
localStorage
Data, we can realize cross-page data transmission, thereby solving the problem of cross-domain cookies invalidation.
3.4.4 Usage scenarios and limitations
Use scenarios
- Single Page Application (SPA):
- In a single page application, page switching usually does not cause page reloading, so
localStorage
Can be used to share data between different views. - Data delivery across subpages:
- Pass data between different subpages under the same domain name, for example, passing user information from a login page to the main page.
- Temporary storage:
- Used to temporarily store user operation data, such as form data, user preference settings, etc.
limit
- Domain name restrictions:
-
localStorage
Data can only be shared between pages under the same domain name (origin), and pages with cross-domain names (different origins) cannot be shared directly.localStorage
data. - Data security:
-
localStorage
The data stored in it is plain text and can be read by any script with access rights. Therefore, sensitive information, such as user passwords, credit card information, etc., should not be stored. - Storage capacity limit:
- Each browser pair
localStorage
The capacity limit is usually 5MB, and data beyond this limit will not be stored. - Browser compatibility:
- Although modern browsers generally support it
localStorage
, but the compatibility issues of older browsers still need to be considered.
4. Practical cases
4.1 Java backend code example
In the Java backend, we can use Spring Boot to set cookie attributes and handle cross-domain requests. Here is a simple example:
Set SameSite properties and cross-domain configuration
import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("/api") public class CookieController { @PostMapping("/set-cookie") @CrossOrigin(origins = "", allowCredentials = "true") public String setCookie(HttpServletResponse response) { Cookie cookie = new Cookie("key", "value"); ("/"); (true); (true); (3600); // 1 hour (""); ("SameSite=None; Secure"); // For SameSite=None (cookie); return "Cookie set"; } }
Configure CORS
In Spring Boot applications, CORS can be configured globally through configuration classes:
import ; import ; import ; import ; @Configuration public class WebConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { ("/api/**") .allowedOrigins("") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true); } }; } }
4.2 Vue front-end code example
In Vue projects, we usually use Axios for HTTP requests. Here is an example showing how to configure Axios to support cross-domain requests and carry cookies:
Install Axios
npm install axios
Configure Axios
In the Vue projectConfigure Axios in the file:
import Vue from 'vue'; import App from './'; import axios from 'axios'; = true; = ''; .$axios = axios; new Vue({ render: h => h(App), }).$mount('#app');
Send cross-domain requests
Send requests using Axios in Vue components:
<template> <div> <button @click="setCookie">Set Cookie</button> </div> </template> <script> export default { methods: { setCookie() { this.$('/api/set-cookie') .then(response => { (); }) .catch(error => { (error); }); } } } </script>
4.3 Comprehensive example: Front- and back-end joint debugging
The following is a comprehensive example showing how to deal with cross-domain cookies in front-end joint debugging.
Backend code
import ; import ; import ; import ; import ; import ; @RestController @RequestMapping("/api") public class CookieController { @PostMapping("/set-cookie") @CrossOrigin(origins = "", allowCredentials = "true") public String setCookie(HttpServletResponse response) { Cookie cookie = new Cookie("key", "value"); ("/"); (true); (true); (3600); // 1 hour (""); ("SameSite=None; Secure"); // For SameSite=None (cookie); return "Cookie set"; } }
Front-end code
<template> <div> <button @click="setCookie">Set Cookie</button> </div> </template> <script> export default { methods: { setCookie() { this.$('/api/set-cookie') .then(response => { (); }) .catch(error => { (error); }); } } } </script> <script> import Vue from 'vue'; import App from './'; import axios from 'axios'; = true; = ''; .$axios = axios; new Vue({ render: h => h(App), }).$mount('#app'); </script>
Through the above configuration, the front-end will carry cookies when sending requests, and the back-end will also set and return cookies correctly, thereby realizing cookies in cross-domain requests.
5. Frequently Asked Questions and Troubleshooting
5.1 Cookies are not set correctly
Problem description: Cookies are not saved or sent by the browser.
Troubleshooting steps:
- Confirm that the SameSite property of the cookie is set to
None
andSecure
The property is set totrue
。 - Check that the cookie's path and domain are correct.
- Confirm that the server response header contains
Set-Cookie
Field.
5.2 Browser Limitations
Problem description: Some browsers may have additional restrictions on cross-domain cookies.
Troubleshooting steps:
- Confirm whether the browser version supports it
SameSite=None
。 - Check your browser's privacy settings to make sure that third-party cookies are not blocked.
- Use the browser developer tools to view network requests and responses to confirm that cookies are set and sent correctly.
5.3 Server configuration issues
Problem description: The server configuration error causes cross-domain request to fail.
Troubleshooting steps:
- Verify that the server's CORS configuration is correct and allows required cross-domain requests.
- Check the server logs to confirm that there are no other errors that affect cross-domain requests.
- Verify that the server response header contains the correct CORS header information.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.