Spring Boot2 series of tutorials (xiv) CORS solve cross-domain problems Spring Boot2 series of tutorials (xiv) CORS solve cross-domain problems

Excerpt: https://www.cnblogs.com/lenve/p/11724463.html

 

Spring Boot2 series of tutorials (xiv) CORS solve cross-domain problems

 

Today, chat and small partners to solve cross-domain problem by CORS.

Same Origin Policy

Many people have a misconception of cross-domain, thought it was the front end of things, and the back end does not matter, in fact, not the case when it comes to cross-domain, you have to talk about the browser's same-origin policy.

Origin policy is a well-known security policy proposed by Netscape, the browser it is also the most basic core security functions, now all JavaScript-enabled browsers will use this strategy. The so-called homology means the agreement, as well as the port to the same domain name. Homologous proposed strategy is based on security considerations come, the strategy itself is no problem, but we are in the actual development, due to various reasons, they often have cross-domain needs, the traditional cross-domain solution is JSONP, JSONP can be solved. but there is a lot of cross-domain limitations, that only supports GET requests, does not support other types of requests, and today we are talking about CORS (cross-domain-origin resource sharing) (CORS, Cross-origin resource sharing) is a W3C standard, which is a standardized browser technology, provides a Web service method from a different domain came sandbox scripts to avoid the browser's same-origin policy, which is the modern version of JSONP mode.

In the Spring framework, for CORS also provides corresponding solutions, today we take a look at how to achieve SpringBoot CORS.

practice

Next we take a look at how to achieve this Spring Boot thing.

First, create two ordinary Spring Boot project, this would not have me say, first named to serve provider, the second named consumer consumer services, first configure ports for 8080, the second configuration is a 8081 , then provided on two hello provider interfaces, a get, a POST, as follows:

@RestController
public class HelloController { @GetMapping("/hello") public String hello() { return "hello"; } @PostMapping("/hello") public String hello2() { return "post hello"; } }

Created under resources / static directory of a consumer html file, send a simple ajax request, as follows:

<div id="app"></div> <input type="button" onclick="btnClick()" value="get_button"> <input type="button" onclick="btnClick2()" value="post_button"> <script> function btnClick() { $.get('http://localhost:8080/hello', function (msg) { $("#app").html(msg); }); } function btnClick2() { $.post('http://localhost:8080/hello', function (msg) { $("#app").html(msg); }); } </script>

Then two projects were started, the button sends a request to observe the browser console as follows:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It can be seen, due to the same origin policy, the request can not be sent successfully.

CORS can not use the front-end code without any modification, to achieve cross-domain, so let's look at how to configure the provider. First, by @CrossOriginthe configuration method of one annotation accept requests a certain domain, as follows:

@RestController
public class HelloController { @CrossOrigin(value = "http://localhost:8081") @GetMapping("/hello") public String hello() { return "hello"; } @CrossOrigin(value = "http://localhost:8081") @PostMapping("/hello") public String hello2() { return "post hello"; } }

This annotation represents two interface accepts from http://localhost:8081the request address, the configuration is complete, restart the provider, send the request again, the browser console would not be incorrect report, consumer can get the data.

Observed at this time the browser requests the network console, you can be seen more response header the following information:

This indicates that the service from the end willing to accept http://localhost:8081the request, and get this information, the browser will not go this request to limit the cross-domain.

The provider, on every method to add comment would be too much trouble, I thought I could speak some small partners annotations directly added to the Controller, but each Controller will be added or trouble in the Spring Boot, you can also configure via global disposable solve this problem, only you need to override the global configuration method to addCorsMappings in SpringMVC configuration class as follows:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8081") .allowedMethods("*") .allowedHeaders("*"); } }

/**Represents all of the methods of the present application to handle cross-domain request, allowedMethods represents the number of requests allowed to pass, allowedHeaders said allowed request header. After such a configuration, it is not necessary to individually disposed on each of the cross-domain method.

Problems

After understanding the entire working process CORS, we send cross-domain requests by Ajax, although improving the user experience, but also a potential threat exists, is common CSRF (Cross-site request forgery) cross-site request forgery. CSRF also called one-click attack or session riding, or commonly abbreviated as CSRF XSRF, hijack a user performs an operation unintended attack on the Web applications that are currently logged in, for example:

If the URL address of a bank transfer to run the operation as follows: http://icbc.com/aa?bb=ccthen, a malicious attacker could place the following code on another site: <img src="http://icbc.com/aa?bb=cc">if a user visited a malicious site, and she had just visited the bank shortly before the login information yet expired, then she will suffer.

Based on this, the browser in practice, the request will be classified into simple request, request in advance, such as a request with credentials, it will first send a pre-request options probe request, and the browser negotiate whether to accept the request. By default, cross-domain requests certificate is not required, but the server can be configured to require clients to provide credentials, so that you can effectively avoid csrf attack.

Well, so much for this problem, CORS on the Spring Boot, Song Ge there is a small video tutorial

Public concern number [south] a little rain, focused on Spring Boot + Micro service and front and rear ends of separation full stack technology, video tutorials on a regular basis to share concerns reply after Java, Java dry Song Ge receive carefully prepared for you!

Blue sky Road, Sunshine House.
 
Category: the Java

Today, chat and small partners to solve cross-domain problem by CORS.

Same Origin Policy

Many people have a misconception of cross-domain, thought it was the front end of things, and the back end does not matter, in fact, not the case when it comes to cross-domain, you have to talk about the browser's same-origin policy.

Origin policy is a well-known security policy proposed by Netscape, the browser it is also the most basic core security functions, now all JavaScript-enabled browsers will use this strategy. The so-called homology means the agreement, as well as the port to the same domain name. Homologous proposed strategy is based on security considerations come, the strategy itself is no problem, but we are in the actual development, due to various reasons, they often have cross-domain needs, the traditional cross-domain solution is JSONP, JSONP can be solved. but there is a lot of cross-domain limitations, that only supports GET requests, does not support other types of requests, and today we are talking about CORS (cross-domain-origin resource sharing) (CORS, Cross-origin resource sharing) is a W3C standard, which is a standardized browser technology, provides a Web service method from a different domain came sandbox scripts to avoid the browser's same-origin policy, which is the modern version of JSONP mode.

In the Spring framework, for CORS also provides corresponding solutions, today we take a look at how to achieve SpringBoot CORS.

practice

Next we take a look at how to achieve this Spring Boot thing.

First, create two ordinary Spring Boot project, this would not have me say, first named to serve provider, the second named consumer consumer services, first configure ports for 8080, the second configuration is a 8081 , then provided on two hello provider interfaces, a get, a POST, as follows:

@RestController
public class HelloController { @GetMapping("/hello") public String hello() { return "hello"; } @PostMapping("/hello") public String hello2() { return "post hello"; } }

Created under resources / static directory of a consumer html file, send a simple ajax request, as follows:

<div id="app"></div> <input type="button" onclick="btnClick()" value="get_button"> <input type="button" onclick="btnClick2()" value="post_button"> <script> function btnClick() { $.get('http://localhost:8080/hello', function (msg) { $("#app").html(msg); }); } function btnClick2() { $.post('http://localhost:8080/hello', function (msg) { $("#app").html(msg); }); } </script>

Then two projects were started, the button sends a request to observe the browser console as follows:

Access to XMLHttpRequest at 'http://localhost:8080/hello' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It can be seen, due to the same origin policy, the request can not be sent successfully.

CORS can not use the front-end code without any modification, to achieve cross-domain, so let's look at how to configure the provider. First, by @CrossOriginthe configuration method of one annotation accept requests a certain domain, as follows:

@RestController
public class HelloController { @CrossOrigin(value = "http://localhost:8081") @GetMapping("/hello") public String hello() { return "hello"; } @CrossOrigin(value = "http://localhost:8081") @PostMapping("/hello") public String hello2() { return "post hello"; } }

This annotation represents two interface accepts from http://localhost:8081the request address, the configuration is complete, restart the provider, send the request again, the browser console would not be incorrect report, consumer can get the data.

Observed at this time the browser requests the network console, you can be seen more response header the following information:

This indicates that the service from the end willing to accept http://localhost:8081the request, and get this information, the browser will not go this request to limit the cross-domain.

The provider, on every method to add comment would be too much trouble, I thought I could speak some small partners annotations directly added to the Controller, but each Controller will be added or trouble in the Spring Boot, you can also configure via global disposable solve this problem, only you need to override the global configuration method to addCorsMappings in SpringMVC configuration class as follows:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8081") .allowedMethods("*") .allowedHeaders("*"); } }

/**Represents all of the methods of the present application to handle cross-domain request, allowedMethods represents the number of requests allowed to pass, allowedHeaders said allowed request header. After such a configuration, it is not necessary to individually disposed on each of the cross-domain method.

Problems

After understanding the entire working process CORS, we send cross-domain requests by Ajax, although improving the user experience, but also a potential threat exists, is common CSRF (Cross-site request forgery) cross-site request forgery. CSRF also called one-click attack or session riding, or commonly abbreviated as CSRF XSRF, hijack a user performs an operation unintended attack on the Web applications that are currently logged in, for example:

If the URL address of a bank transfer to run the operation as follows: http://icbc.com/aa?bb=ccthen, a malicious attacker could place the following code on another site: <img src="http://icbc.com/aa?bb=cc">if a user visited a malicious site, and she had just visited the bank shortly before the login information yet expired, then she will suffer.

Based on this, the browser in practice, the request will be classified into simple request, request in advance, such as a request with credentials, it will first send a pre-request options probe request, and the browser negotiate whether to accept the request. By default, cross-domain requests certificate is not required, but the server can be configured to require clients to provide credentials, so that you can effectively avoid csrf attack.

Well, so much for this problem, CORS on the Spring Boot, Song Ge there is a small video tutorial

Public concern number [south] a little rain, focused on Spring Boot + Micro service and front and rear ends of separation full stack technology, video tutorials on a regular basis to share concerns reply after Java, Java dry Song Ge receive carefully prepared for you!

Guess you like

Origin www.cnblogs.com/xichji/p/11725922.html