Spring boot introductory tutorial-CORS cross-domain support

CORS (Cross-Origin Resource Sharing) "Cross-Origin Resource Sharing" is a W3C standard that allows browsers to send Ajax requests to cross-domain servers, breaking the restriction that Ajax can only access resources within this site. We will encounter cross-domain errors in front-end requests and back-end servers during development. Let's talk about how to make the SpringBoot project support CORS cross-domain.

The first step is to build a SpringBoot project. Spring 4.2 provides @CrossOrigion annotation to achieve CORS support.

How to build a SpringBoot project and add related dependencies, I will not go into details here, I believe it is a side dish for everyone.

The second step is to configure CORSConfiguration, global cross-domain settings.

Create a new class CORSConfiguration, inherit WebMvcConfigurerAdapter, and override the addCorsMappings method.

@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedHeaders("*");
        super.addCorsMappings(registry);
    }
}

The detailed configuration information is described as follows: 
addMapping: Configure the path that can be cross-domain, and can be configured arbitrarily, and can be specific to the direct request path. 
allowedMethods: Allow all request methods to access the cross-domain resource server, such as: POST, GET, PUT, DELETE, etc. 
AllowedOrigins: Allow all requested domain names to access our cross-domain resources. Single or multiple pieces of content can be fixed, such as: "http://www.aaa.com". Only this domain name can access our cross-domain resources. 
allowedHeaders: All request headers are allowed to access, and any request header information can be customized.

For example:

1. Allow domain name access

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:63342");//允许域名访问,如果*,代表所有域名
            }
        };
    }
}

2. Only allow requests with Authorizationor Tokenin the header to access

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedHeaders("Authorization", "Token")//允许的头信息
                        .allowedOrigins("http://localhost:63342");
            }
        };
    }
}

3. Only support post access

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedHeaders("Authorization", "Token")
                        .allowedMethods("POST")//只允许post方式
                        .allowedOrigins("http://localhost:63342");
            }
        };
    }
}

Local cross-domain settings

The above is configured for global cross-domain access, and local access control can also be configured

Annotation @CrossOrigin above the class

@CrossOrigin(origins = "http://domain.com", allowedHeaders = "token", methods = {RequestMethod.GET, RequestMethod.POST})
@RestController
public class TestResource{

}

@CrossOrigin above method

@RestController
public class TestResource{
    @CrossOrigin(origins = "http://domain.com", allowedHeaders = {"header1", "header2"})
    @GetMapping("/api/test")
    public String test(){
        return "test";
    }
}

Guess you like

Origin blog.csdn.net/qq_27828675/article/details/90175379