CORS solve cross-domain problems (403 problems)

1. What is cross-domain problem?

  Cross-domain issue is a browser security restrictions for ajax request: ajax request initiated by a page, only with the current page path with the domain name with the port , which can effectively prevent cross-site attacks.

 

2, provided cross-domain problems:

  1, the cross-domain problem is ajax request specific issues.

     2, front and rear end of the domain name, port inconsistent.

3, CORS cross-domain analysis to solve simple principle:

  CORS need a browser and the server supports.

 

  The browser ( browser auto-complete ):

    Sending two requests, the first transmission request option - server can ask whether a cross-domain;

    The second was to send a formal request.

 

  Service-Terminal:

    By / filter interceptor achieve unity, filters all requests matching the corresponding ip + port, if eligible, the first cross-domain access permission information added in the response .

4, CORS cross-domain solutions:

  1, a CORS configuration in the gateway cross-domain filter: SpringMVC has helped us to write a cross-domain filter CORS, and can be used directly.

  2,  create a configuration file in the gateway tells filters allow domain name and port can be adopted.

 

  Add the following to the configuration file in the gateway ( lower springMVC Environment)

Import org.springframework.context.annotation.Bean;
 Import org.springframework.context.annotation.Configuration;
 Import org.springframework.web.cors.CorsConfiguration;
 Import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
 Import org.springframework.web .filter.CorsFilter; 

@Configuration 
public  class GlobalCorsConfig { 
    @Bean 
    public corsFilter corsFilter () {
         // 1. Add CORS configuration information 
        CorsConfiguration config = new new CorsConfiguration ();
         // 1) allows domain through, do not write *, otherwise the cookie I can not use
        config.addAllowedOrigin("http://127.0.0.1:7001");
        config.addAllowedOrigin("http://localhost:7001");
        //2) 是否发送Cookie信息
        config.setAllowCredentials(true);
        //3) 允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod ( "the PATCH" );
         // . 4) allows the header information 
        config.addAllowedHeader ( "*" );
         // 2. Add map path, we intercept all requests 
        UrlBasedCorsConfigurationSource the configSource = new new 
                UrlBasedCorsConfigurationSource (); 
        configSource.registerCorsConfiguration ( "/ **" , config);
         // 3. return new CorsFilter. 
        return  new new CorsFilter (the configSource); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/wanghj-15/p/11374190.html