Spring Boot中的跨域资源共享配置

发布时间:2024-10-05 09:01:00 作者:小樊
来源:亿速云 阅读:81

在Spring Boot中,我们可以使用@CrossOrigin注解来实现跨域资源共享(CORS)的配置。这个注解可以应用在Controller类或者方法上。以下是一些常见的配置方式:

  1. 全局配置

在Spring Boot 2.x中,你可以通过创建一个配置类并使用@EnableWebMvcWebMvcConfigurer接口来实现全局的CORS配置。例如:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

注意:allowedOrigins("*")表示允许所有来源,这在生产环境中可能不安全。你应该指定具体的、可信的来源域名。 2. 局部配置

你也可以在Controller类或方法上直接使用@CrossOrigin注解来实现局部的CORS配置。例如:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

在这个例子中,只有来自http://example.com的请求才会被允许访问/hello端点。 3. 过滤器的配置

另外,你还可以通过配置一个全局的CORS过滤器来实现CORS。例如:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterRegistration() {
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new CorsFilter());
        registration.addUrlPatterns("/*");
        registration.setAllowedOrigins("*");
        registration.setAllowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
        registration.setAllowedHeaders("*");
        registration.setAllowCredentials(true);
        registration.setMaxAge(3600);
        return registration;
    }
}

这种方式与全局配置类似,但使用了过滤器来实现CORS。

请注意,上述示例中的配置可能不适用于所有场景。在生产环境中,你应该根据具体需求和安全考虑来调整CORS配置。例如,避免使用allowedOrigins("*"),而是指定具体的、可信的来源域名。

推荐阅读:
  1. Spring Boot通过CORS处理跨域问题的方法
  2. 详解Spring MVC CORS 跨域

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot

上一篇:Linux系统中Docker容器化应用的测试策略

下一篇:Spring Boot中的环境变量读取

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》