首頁  >  文章  >  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. .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