“This is the 9th day of my participation in the November Gwen Challenge.The final text challenge in 2021”.

preface

First, understanding cross domain

Cross-domain is a browser same-origin security policy, that is, the browser unilaterally restricts the cross-domain access of scripts.

How can cross-domains be created?

A difference between the current page URL and the requested URL header can cause cross-domain. Colloquially speaking, it is two URLS, the part before the port, as long as there is a little difference that occurs across domains.

  • inhttp://a.baidu.comThe accesshttps://a.baidu.comResources will formAgreement cross-domain.
  • ina.baidu.comThe accessb.baidu.comResources will formThe host cross-domain.
  • ina.baidu.com:80The accessa.baidu.com:8080Resources will formPort cross-domain.

2. Common ways to solve cross-domain problems

1. JSONP

Because browsers allow some tags with SRC attributes to cross domains, such as iframe, script, img, etc., JSONP can use script tags to cross domains.

Implementation approach

  • The front end requests through the Script tag and specifies in the callback the name of the returned wrapper entity as JSONP (customizable)
<script src="http://aaa.com/getusers?callback=jsonp"></script>
Copy the code
  • The back end wraps the returned results in the desired data format
jsonp({
    "error":200."message":"Request successful"."data": [{"username":"Zhang"."age":20}]})Copy the code

Summary: JSONP is simple to implement, but it only supports GET requests across domains, which has major limitations

2.CORS

Cross-origin Resource Sharing (CORS) specification has a new set of HTTP header fields that allow servers to declare which sites are allowed to use the resources they provide across domains.

Note: CORS does not support browsers below IE8.

In most browsers, even if the request is cross-domain, the request is still sent to the server, the server receives and processes it, but the information returned to the browser is blocked by the browser. This will cause unnecessary waste of resources on the server.

This problem is avoided in the CORS specification:

  • When making a request, the browser sends a pre-check request with the request method OPTIONS to confirm whether cross-domain is allowed. The actual request is sent only when the server allows cross-domain.
  • Precheck requests allow the server to notify the browser to carry credentials (such as cookies) across domains

Common header field

HTTP header fields added by CORS are controlled by the server. Here are some common header fields:

  • Access-Control-Allow-Origin
    • Set which sites are allowed to make cross-domain requests, using the URL header matching principle.
    • Set to * to allow all web site requests

    Note:

    • When the browser requests credentials, do not set this parameter to *****
    • With site-specific information set, Vary needs to carry the Origin attribute because the server returns different things for different domains:
    Access-Control-Allow-Origin: http://aaa.com
    Vary: Accept-Encoding,Origin
    Copy the code
  • Access-Control-Allow-Methods
    • Valid only in response to a precheck request
    • An HTTP method that indicates that the server allows the request
    • Separate multiple entries with commas
  • Access-Control-Allow-Headers
    • Valid only in response to a precheck request
    • Indicates the header field that the server is allowed to carry
    • Separate multiple entries with commas
  • Access-Control-Max-Age
    • Specifies the validity period of this precheck request
    • You do not need to initiate another request within the validity period
  • Access-Control-Allow-Credentials
    • If the value is true, the browser is notified of the following formal request with the user’s credentials (such as cookies). The server can also use set-cookie to write a new cookie to the user’s browser.
    • Access-control-allow-origin cannot be set to *

Summary: There are two common access control scenarios when using CORS

A simple request

  • GET and HEAD requests that do not carry custom request headers
  • Content-type POST requests for Application/X-www-form-urlencoded, multipart/form-data, or Text /plain

When a request is made, an Origin attribute is automatically added to the request header with the value of the current page URL header. The server receives the request and returns the message. If cross-domain access control attributes exist in the returned information, the browser determines whether cross-domain access control is allowed based on these attribute values. If yes, the cross-domain access control succeeds. So just add the access-Control-Allow-Origin field to the returned response header and fill in the sites that Allow cross-domain Access.

Precheck requests (non-simple requests)

A precheck request is different from a simple request. It sends an OPTIONS request to the target site to find out if the request is secure and prevent the request from damaging the data at the target site.

Spring Security enables CORS support

Spring Security provides excellent support for CORS, simply by enabling CORS support in the configurator and writing a CORS configuration source.

@Override
protected void configure(HttpSecurity http) throws Exception {
    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
    jdbcTokenRepository.setDataSource(dataSource);
    http.authorizeRequests()
        .antMatchers("/admin/api/**").hasRole("ADMIN")
        .antMatchers("/user/api/**").hasRole("USER")
        .antMatchers("/app/api/**"."/captcha.jpg").permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin()
        .loginPage("/myLogin.html")
        // Specify the path to process the login request. Modify the path of the request. The default path is /login
        .loginProcessingUrl("/mylogin").permitAll()
        .csrf().disable()
        .cors();
}

@Bean
CorsConfigurationSource corsConfigurationSource(a){
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    // Allow cross-domain from Baidu site
    corsConfiguration.setAllowedOrigins(Arrays.asList("https://www.baidu.com"));
    // Allow GET and POST methods
    corsConfiguration.setAllowedMethods(Arrays.asList("GET"."POST"));
    // You are allowed to carry credentials
    corsConfiguration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // Applies to all urls
    source.registerCorsConfiguration("/ * *",corsConfiguration);
    return source;
}
Copy the code

Note: CorsConfigurationSource for this package under the import org. Springframework. Web. Cors. CorsConfigurationSource;