首页  >  文章  >  Java  >  如何集成Spring Security CORS过滤器?

如何集成Spring Security CORS过滤器?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-01 12:52:22190浏览

How to Integrate Spring Security CORS Filter?

Spring Security CORS 过滤器集成

Spring Security 需要 CORS 配置来处理跨域请求。要具体解决此问题,请按照以下步骤操作:

  1. 实现 WebMvcConfigurerAdapter:

    <code class="java">@Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
        }
    }</code>
  2. 在 HttpSecurity 中配置 CORS:

    <code class="java">@Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().configurationSource(corsConfigurationSource());
        }
    
        @Bean
        public CorsConfigurationSource corsConfigurationSource() {
            final CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(ImmutableList.of("*"));
            configuration.setAllowedMethods(ImmutableList.of("HEAD",
                                "GET", "POST", "PUT", "DELETE", "PATCH"));
            configuration.setAllowCredentials(true);
            configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }</code>

重要说明:

  • 避免使用 http.authorizeRequests().antMatchers (HttpMethod.OPTIONS, "/**").permitAll();或 web.ignoring().antMatchers(HttpMethod.OPTIONS);,因为它们是不正确的解决方案。
  • 有关更多详细信息,请参阅官方 Spring Security 文档:http://docs.spring.io/spring- security/site/docs/4.2.x/reference/html/cors.html

以上是如何集成Spring Security CORS过滤器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn