How to handle cross-domain requests in Springboot
1. What is cross domain?
We know the general format of Url: protocol + domain name (subdomain name + main domain name) + port number + resource address
for example:
https://www.itquanmingxing.cn:8080/users is composed of https + www + itquanmingxing.cn + 8080 + users.
As long as one of the four components of the protocol, subdomain name, main domain name, and port number is different, it can be considered as a different domain, and different domains access resources with each other, which is called cross-domain.
Our browsers do not allow cross-domain requests by default, because they all use the same-origin policy. The same-origin policy is a well-known security policy proposed by Netscape. It is the core and most basic security function of browsers. All browsers that support JavaScript now use this strategy.
However, in our actual development, due to various reasons, we often have cross-domain requirements. For example: the current front-end development is a development model where the front and back ends are separated, and the data acquisition is not from the same source; or A website is an e-commerce management order , Website B captures the order information for invoicing and delivers the goods; another example is single sign-on, after logging in on website A, you don’t need to enter the user name and password when jumping to website B.
So how do we solve this cross-domain access problem?
Two what is CORS
To solve cross-domain requests, there are mainly JSONP, iframe, window.name, CORS and other methods. Among them, the CORS method is the most commonly used cross-domain implementation method, and it perfectly supports various request methods and various data request types.
Cross-origin resource sharing (CORS, Cross-origin resource sharing) is a mechanism that uses additional HTTP headers to tell the browser that a web application running on one origin (domain) is allowed to access specified resources from different origin servers. H. A resource initiates a cross-origin HTTP request when a resource is requested from a different domain, protocol, or port than the server on which the resource itself resides.
Principle: Set the request header that allows cross-domain on the server side, so as to realize cross-domain. After the server is set, the front end can pass normal ajax requests.
The use of CORS in three Springboot
CORS is more convenient in terms of specific code implementation, and the front-end can support it almost without writing any code. It is mainly configured on the server side.
CORS requires both browser and server support. All browsers currently support this function, and the IE browser cannot be lower than IE10.
The entire CORS communication process is automatically completed by the browser without user participation. For developers, there is no difference between CORS communication and same-origin AJAX communication, and the code is exactly the same. Once the browser discovers that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes there will be an additional request, but the user will not feel it.
Therefore, the key to realizing CORS communication is the server. As long as the server implements the CORS interface, cross-domain communication is possible.
3.1 Create two springboot projects
For convenience, create an empty project, and then create two modules in the empty project to represent two different source projects.
Create an empty project first:
Create two more modules:
One is named provider (the project being accessed), and web dependencies are added, and the other is named consumer (the project that initiates the visit), and web and thymeleaf dependencies are added.
…
The result of the created project is as follows:
3.2 Add test code
Add to the provider project:
Control layer method:
Add to the consumer project:
Ajax requests in control layer methods and view pages
Modify the consumer access port to 8080:
3.3 Start the project test
Start the two projects separately
It will be found that due to the restriction of the same-origin policy, the request cannot be sent successfully.
3.4 Using CORS
Ok, then we will now use CORS to achieve cross-domain without any modification of the front-end code.
Add to the method provided by the provider project
@CrossOrigin(value = "http://localhost:8088")
Restart project access: found that it can be accessed successfully.
Press F12 to view the request header information and find that there is an additional domain that allows access.
3.5 Configure CORS globally
This annotation can be used on the method or on the Controller, but if it is troublesome to add annotations to each method, including adding annotations to each Controller, we can solve this problem at one time through global configuration.
Global configuration only needs to rewrite the addCorsMappings method in the configuration class of SpringMVC, and there is no need to add the method. The code is as follows:
package com.example.provider.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ProviderMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")// 项目中的所有接口都支持跨域
.allowedOrigins("http://localhost:8088") //允许哪些域能访问我们的跨域资源
.allowedMethods("*")//允许的访问方法"POST", "GET", "PUT", "OPTIONS", "DELETE"等
.allowedHeaders("*");//允许所有的请求header访问,可以自定义设置任意请求头信息
}
}
这里我们的ProviderMvcConfig配置类实现了WebMvcConfigurer接口并且重写了addCorsMappings方法,我们来简单介绍下我们的配置信息
addMapping:配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。
allowedOrigins:允许哪些域名可以访问我们的跨域资源,可以固定单条或者多条内容。
如:allowedOrigins("http://www.baidu.com")只有百度可以访问我们的跨域资源。
allowedOrigins("*")代表允许任意路径
allowedMethods:设置允许的请求方法类型访问该跨域资源服务器,如:POST、GET、PUT、OPTIONS、DELETE等。
allowedHeaders:允许所有的请求header访问,可以自定义设置任意请求头信息,如:"X-YYYY-TOKEN"
allowCredentials: 是否允许请求带有验证信息,用户是否可以发送、处理 cookie
maxAge(3600) 设置允许访问的时间
3.5 Potential safety hazards.
Set any request header information, such as: "X-YYYY-TOKEN"
allowCredentials: Whether to allow requests with authentication information, whether users can send and process cookies
maxAge(3600) Set the time allowed to access``
3.5 Potential safety hazards.
The working process of CORS is to send cross-domain requests through Ajax, which also has potential threats. The common one is CSRF (Cross-site request forgery) cross-site request forgery. Cross-site request forgery, also known as one-click attack or session riding, usually abbreviated as CSRF or XSRF, is an attack method that coerces users to perform unintended operations on the currently logged-in web application. Regarding the specific introduction and defense methods of CSRF attacks, we will explain in detail after learning Spring Security (spring security framework).