What is the method for configuring cross-origin in Spring Boot?

There are several ways to configure cross-origin requests in Spring Boot.

  1. Utilize a global configuration class:
    Create a global configuration class that extends WebMvcConfigurerAdapter, and override the addCorsMappings method to define the paths and request methods allowed for cross-origin requests. For example:
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}
  1. Add the @CrossOrigin annotation to the Controller class or method to configure cross-origin requests. For example:
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class MyController {

    // ...
}

The origins attribute in the annotation specifies the sources allowed for cross-origin requests, and a wildcard “*” can be used to allow all sources. The maxAge attribute specifies the validity period of preflight requests in seconds.

  1. Utilizing Filter:
    Create a Filter class that implements the javax.servlet.Filter interface, and add cross-origin request configuration in the doFilter method. For example:
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials","true");
        chain.doFilter(req, res);
    }

    // ...
}

Here are several common methods used for configuring cross-origin requests in Spring Boot. Choose the appropriate method based on specific requirements.

bannerAds