How to configure CORS support in Spring Boot

How to configure CORS support in Spring Boot

CORS (Cross-Origin Resource Sharing) is a web browser security feature that controls script files on a web page to load other web resources from different sources. When developing modern web applications, it is often necessary to request different resources across domains, such as API services or other web applications. This article will describe how to configure CORS (Cross-Origin Resource Sharing) support in a Spring Boot application to allow cross-origin requests.

Insert image description here

What is CORS?

CORS (Cross-Origin Resource Sharing) is a security feature that controls whether the browser allows JavaScript code in a web page to load other web resources from different sources. By default, browsers do not allow cross-origin requests to prevent cross-site request forgery (CSRF) attacks. But in some cases, such as when sending HTTP requests from a front-end application to a back-end API, cross-origin restrictions need to be lifted, which requires CORS support.

CORS support in Spring Boot

Spring Boot provides a simple and powerful way to configure CORS support, allowing you to define which cross-origin requests are allowed and which are prohibited. In Spring Boot, you can configure CORS policies through annotations or configuration files.

Configure CORS using annotations

In Spring Boot, you can use the @CrossOrigin annotation to configure the CORS policy. This annotation can be applied to controller methods or to the entire controller class. Here is an example of configuring CORS using annotations:

@RestController
@RequestMapping("/api")
public class MyController {
    
    

    @GetMapping("/data")
    @CrossOrigin(origins = "http://localhost:8080")
    public ResponseEntity<String> getData() {
    
    
        // 处理请求并返回响应
        return ResponseEntity.ok("Hello from the server!");
    }
}

In the above code, the @CrossOrigin annotation is used in the getData method to specify the origin that allows cross-domain requests. In this example, only requests from http://localhost:8080 are allowed to access this interface.

Configure CORS using configuration files

In addition to using annotations, you can configure CORS policies by defining properties in application.properties or application.yml. Here is an example of configuring CORS using a configuration file:

currently application.propertiescurrently:

# 允许所有源访问该接口
spring.mvc.cors.allow-credentials=false
spring.mvc.cors.allowed-headers=*
spring.mvc.cors.allowed-methods=GET,POST,PUT,DELETE
spring.mvc.cors.allowed-origins=*
spring.mvc.cors.exposed-headers=Authorization,Link,X-Total-Count
spring.mvc.cors.max-age=3600

currently application.ymlcurrently:

spring:
  mvc:
    cors:
      allow-credentials: false
      allowed-headers: "*"
      allowed-methods: "GET,POST,PUT,DELETE"
      allowed-origins: "*"
      exposed-headers: "Authorization,Link,X-Total-Count"
      max-age: 3600

In the above configuration, we allow cross-origin requests from all origins, defining the allowed HTTP methods, allowed request headers, allowed exposed headers, and maximum cache time.

Advanced CORS configuration

In addition to basic CORS configuration, Spring Boot also provides more advanced configuration options for more granular control of CORS policies. You can use theCorsConfigurationSourceinterface to customize the CORS configuration.

The following is an example of how to create a customCorsConfigurationSource to dynamically configure a CORS policy based on the request path:

@Configuration
public class CustomCorsConfiguration {
    
    

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setExposedHeaders(Arrays.asList("Authorization", "Link", "X-Total-Count"));
        config.setMaxAge(3600L);
        
        // 根据路径动态配置CORS策略
        source.registerCorsConfiguration("/api/**", config);
        
        return source;
    }
}

In the above example, we created a custom CorsConfigurationSource Bean and dynamically configured the CORS policy based on the request path (here /api/**).

Run Spring Boot application

Now that you have CORS support configured, you can run your Spring Boot application and test the CORS functionality. Start the Spring Boot application using the following command:

./mvnw spring-boot:run

Or use Maven Wrapper:

mvn spring-boot:run

Your Spring Boot application will start on the default port (usually 8080).

Test CORS policy

You can use your browser's developer tools or a tool such as Postman to test the CORS policy. Try making HTTP requests from different origins (such as http://localhost:8080 and http://localhost:3000) to ensure that the CORS policy is working as expected.

Summarize

In modern web development, CORS (Cross-Origin Resource Sharing) is an important security feature used to control cross-domain requests. Spring Boot provides multiple ways to configure CORS policies, which can be chosen according to your needs. When developing web applications, ensure that CORS policies are configured correctly to allow cross-domain requests and maintain the security and availability of your application. I hope this article was helpful and gave you a better understanding of how to configure CORS support in Spring Boot. Happy coding!

Guess you like

Origin blog.csdn.net/u013749113/article/details/133669618