Spring Boot: How to Solve Cross-domain Problems

Related Tags:1.What Is Domain Resolution and How It Works
2. Alibaba Cloud DNS

Spring Boot cross-domain problems introduction

The reason for the cross-domain problem: The browser restricts access to the resources that this site thinks for security reasons.

Spring Boot cross-domain problems.Cross-domain problem phenomenon


been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
The above means that you are accessing a resource whose address is blocked by the CORS protocol and the parameter of Access-Control-Allow-Origin is not found in Hearder

Cross-domain problem analysis

The reason for the cross-domain problem: The browser restricts access to the resources that this site thinks for security reasons .
For example, if you have a website 127.0.0.1:8080/, and a page is hung on it, then in this page, you will not be restricted to access the resources of this site, but if you visit other sites, such as 127.0.0.1: 8081 resources will be limited.
Note: For the time being, the protocol, domain name, and port are the same as the same site.

Spring Boot cross-domain problems.But tags with src attribute can not have this restriction, such as img , script and so on.
Talking about history, the front and back ends of the previous programs were not separated, and the page and the request interface were under the same domain name and the same port. All browsers think that the page originating from this site requests the interface of the same site, and it will be allowed for a long time.

Spring Boot cross-domain problems.example, 127.0.0.1:8080/index.html, request 127.0.0.1:8080/a/b/c/ userLit interface, this is possible
Speaking of now, the front and back points are separated, and the page and the interface are generally not the same program, so this is not allowed, and this exception will be thrown .

Spring Boot cross-domain problems.What is origin and cross domain





The origin is the protocol, domain name and port number.

A URL consists of a protocol, a domain name, a port, and a path. If the protocol, domain name, and port of two URLs are all the same, they are of the same origin . Otherwise, as long as the protocol, domain name, and port are different in any one, it is cross-domain.
Cross-domain comparison for https://www.baidu.com/index.html :

What is the Same Origin Policy?
Same origin policy is a convention. It is the core and most basic security function of the browser. If the same origin policy is missing, the normal functions of the browser may be affected. It can be said that the Web is built on the basis of the same-origin policy, and the browser is only an implementation of the same-origin policy.
The same-origin policy is further divided into the following two types:
1.DOM same-origin policy: It is forbidden to operate on the DOM of different origin pages. The main scenario here is the case of iframe cross-domain, iframes of different domain names are restricted from accessing each other.
2.XMLHttpRequest Same Origin Policy: It is forbidden to use XHR objects to initiate HTTP requests to server addresses of different origins.
Spring Boot: Cross-domain problem solving

1. Spring Boot cross-domain problems.Create a filter to solve cross-domain

of the project are deployed separately , so cross-domain problems need to be solved. We use cookies to store user login information, and control permissions in the spring interceptor. When the permissions do not match, we directly return the fixed json result to the user. When the user logs in, it is used normally; when the user logs out or the token expires, the cross-domain phenomenon occurs due to the problem of the order of the interceptor and the cross-domain . We know that an http request goes to the filter first, and then the interceptor is processed after reaching the servlet. If we put cors in the filter, it can be executed in priority to the permission interceptor .
@Configuration

public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);

UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}

2. Cross-domain joining Cors based on WebMvcConfigurerAdapter configuration

Cross-domain can be solved by JSONP on the front end , but JSONP can only send GET requests and cannot send other types of requests, which is very tasteless in RESTful style applications, so we recommend passing (CORS, Cross-origin) on the back end resource sharing) to solve cross-domain problems . This solution is not unique to Spring Boot. In the traditional SSM framework, CORS can be used to solve cross-domain problems, but we used to configure CORS in XML files. Now we can implement the WebMvcConfigurer interface and then rewrite the addCorsMappings method. Solve cross-domain problems .
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
3. controller配置CORS
CORS configuration for the controller method, you can add a @CrossOrigin annotation to the @RequestMapping annotation handler method in order to enable CORS (by default @CrossOrigin allows all origins and HTTP methods specified in the @RequestMapping annotation) :
@RestController _
@RequestMapping ( " / account" )
public class AccountController {
@CrossOrigin _
@ GetMapping ( "/ {id}" )
public Account retrieve ( @ PathVariable) Long id )
// ...
A
@ DeleteMapping ( "/ {id}" )
public void remove ( @PathVariable _ Long id ) {
// ...
}
}

where the parameters in @CrossOrigin :
@CrossOrigin indicates that all URLs can access this resource @CrossOrigin ( origins = " http://127.0.0.1:8080")//Indicates that only this url is allowed to access this controller across domains Code description: @CrossOrigin this annotation is used It's very convenient, this can be used on methods, and can also be used on classes. If you do not set his value attribute, or origins attribute, the default is to allow all URL/domain access.
1.The value attribute can set multiple URLs.
2.The origins property can also set multiple URLs.
3.The maxAge property specifies the maximum amount of time the cache will last before preparing a response. It is the validity period of the probe request.
4.The allowCredentials attribute indicates whether the user can send and handle cookies. Default is false
5.The allowedHeaders property indicates which request headers are allowed.
6.The methods attribute indicates the methods allowed for the request, default get, post, head.
The reason why @CrossOrigin does n't work
1. The version of springMVC must be 4.2 or above to support @CrossOrigin

2. Non-@ CrossOrigin did not solve the cross-domain request problem, but an incorrect request resulted in the inability to get the expected response, causing the browser to prompt the cross-domain problem.
@CrossOrigin annotation above the Controller annotation , the cross-domain problem still occurs. One of the solutions is:
Get and Post methods are not specified in the @RequestMapping annotation. After specifying them, the problem is solved.
Similar code is as follows:
@CrossOrigin _
@RestController _
public class person {

@RequestMapping ( method _ = RequestMethod.GET ) _ _
public String add ( ) {
// some code
}
}

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us