Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve Cross-domain problems with Java

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Java to solve cross-domain problems", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use Java to solve cross-domain problems.

Cross-domain problem

At present, the projects of most companies are separated from the front and rear ends, and the front and rear ends are bound to encounter cross-domain problems after the separation. The figure below is as follows

Continue debug discovery, reponse is undefined, prompt message is Network Error.

Therefore, when you interconnect with the frontend, the request always fails and a network error is reported. Generally speaking, the backend does not make cross-domain configuration.

Note that at this time, it is not that the back end did not receive the request, but received the request and returned the result, but the browser intercepted the result and reported an error.

Homologous strategy

So why does the browser report an error?

Cognate policy introduced by browsers based on security considerations

When the protocol, domain name and port are all the same, the cross-domain problem will not occur, that is, the same origin. At this point, the response of the server can be read.

For the current url request, whether the url is cross-domain https://www.javashitang.comhttp://www.javashitang.com is different, different protocol https://www.javashitang.comhttp://book.javashitang.com is, different domain name is https://www.javashitang.comhttp://www.javashitang.com:8000, and port is different.

Why should there be a homologous strategy?

To be on the safe side, of course, take a bank transfer as an example, to see how you don't have any money.

This is the famous CSRF attack (cross-site request forgery, of course, there are many other ways), and if step 5 does not verify the source of the request, then your money has been transferred

The following three tags on the html page allow resources to be loaded across domains

How to solve cross-domain

Although the same origin policy ensures security, some reasonable uses will also be affected. There are many ways to solve cross-domain problems, two of which are briefly introduced

JSONP

JSONP mainly uses tags to send requests to achieve data loading, but this method has a disadvantage, that is, it can only support GET requests, other requests can not support, because JSONP this method has been rarely used, so do not do too much introduction

CROS

Non-simple request

Before a formal cross-domain request, send an OPTIONS request to ask the server whether to accept the next cross-domain request, with the following header

Origin: the original domain that initiated the request

Access-Control-Request-Method: the cross-domain request method to be initiated (GET/POST/ … )

Access-Control-Request-Headers: the request header field included in the cross-domain request to be initiated

The server adds the following header to the return to indicate whether the cross-domain request is allowed. After receiving it, the browser will check that if it does not meet the requirements, it will not initiate a subsequent request.

Access-Control-Allow-Origin: which domains are allowed to access (* requests for all domains are allowed)

Access-Control-Allow-Methods: which request methods are allowed

Access-Control-Allow-Headers: which request header fields are allowed

Access-Control-Allow-Credentials: whether Cookie is allowed

Simple request

Isn't it troublesome to send a second request every time? So it was optimized.

When the request method is HEAD, GET, POST

And when the request header is only the following, it is defined as a simple request

Accept Accept-Language Content-Language Last-Event-ID Content-Type: (application/x-www-form-urlencoded, multipart/form-data, text/plain)

A simple request will add an Origin header to the request and initiate the request directly without asking for it first. The backend can return the corresponding header.

Spring supports cross-domain

After understanding the nature of cross-domain, we can see that various configurations actually add header to the reponse according to the request.

Using Filter

The following configuration Filter,CrossDomainFilter is an encapsulation of javax.servlet.Filter, which is essentially a Filter.

You can see that I have returned an extra header,Access-Control-Max-Age, which indicates the validity period of the query result, that is, the browser does not have to ask again within 3600 seconds.

@ Component @ WebFilter (filterName = "crossDomain", urlPatterns = "/ *") public class CrossDomainFilter extends OncePerRequestFilter {@ Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {/ whitelist detection if (CorsUtils.isCorsRequest (request)) {response.setHeader ("Access-Control-Allow-Origin", request.getHeader ("Origin")) Response.setHeader ("Access-Control-Allow-Credentials", "true"); response.setHeader ("Access-Control-Allow-Headers", request.getHeader ("Access-Control-Request-Headers")); response.setHeader ("Access-Control-Allow-Methods", request.getHeader ("Access-Control-Request-Method")); response.setHeader ("Access-Control-Max-Age", "3600") } / / is an OPTIONS request. The header has been set, and there is no need to execute subsequent logic. Directly return if (CorsUtils.isPreFlightRequest (request)) {return;} filterChain.doFilter (request, response);}}

Take a look at the tool classes used

Public abstract class CorsUtils {/ / the header of origin in the request will return true public static boolean isCorsRequest (HttpServletRequest request) {return (request.getHeader (HttpHeaders.ORIGIN)! = null);} public static boolean isPreFlightRequest (HttpServletRequest request) {return (isCorsRequest (request) & & HttpMethod.OPTIONS.matches (request.getMethod ()) & & request.getHeader (HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD)! = null)) }}

Using CorsRegistry

@ Configuration public class GlobalCorsConfig {@ Bean public WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurer () {@ Override public void addCorsMappings (CorsRegistry registry) {/ / add the mapping path registry.addMapping ("/ * *") / / allowed domains .allowedOrigins ("*") / / allowed to carry cookie .allowCredentials (true) / / allowed request method. AllowedMethods ("GET") "POST", "PUT", "DELETE") / / allowed request headers. AllowedHeaders ("*") }}

Using @ CrossOrigin annotations

Support for finer-grained configuration, either on usage methods or classes

RestController @ RequestMapping ("resource") @ CrossOrigin ({"http://127.0.0.1:8080"}) public class ResourceController")

Other ways to support cross-domain

Seeing this, you may wonder, how can we support cross-domain configuration without cross-domain configuration in our project? That probably left the work of setting up header to the gateway layer to do.

At this point, I believe you have a deeper understanding of "how to use Java to solve cross-domain problems". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report