小编典典

Spring Security CORS过滤器

spring

我们添加Spring Security到我们现有的项目中。

从这一刻起,我们No 'Access-Control-Allow-Origin' header is present on the requested resource从服务器收到401 错误。

这是因为没有Access-Control-Allow-Origin标头附加到响应。为了解决这个问题,我们Filter在退出过滤器之前的链中添加了我们自己的过滤器,但是该过滤器不适用于我们的请求。

我们的错误:

XMLHttpRequest无法加载http://localhost:8080/getKunden。所请求的资源上不存在“ Access-Control-Allow-Origin”标头。http://localhost:3000因此,不允许访问原点。响应的HTTP状态码为401。

Our Security configuration::

@EnableWebSecurity
@Configuration
@ComponentScan("com.company.praktikant")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private MyFilter filter;

@Override
public void configure(HttpSecurity http) throws Exception {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();

    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/*").permitAll();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
}

Our filter

@Component
public class MyFilter extends OncePerRequestFilter {

@Override
public void destroy() {

}

private String getAllowedDomainsRegex() {
    return "individual / customized Regex";
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    final String origin = "http://localhost:3000";

    response.addHeader("Access-Control-Allow-Origin", origin);
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Headers",
            "content-type, x-gwt-module-base, x-gwt-permutation, clientid, longpush");

    filterChain.doFilter(request, response);

}
}

Our Application

@SpringBootApplication
public class Application {
public static void main(String[] args) {
    final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
}
}

我们的过滤器是从spring-boot注册的:

2016-11-04 09:19:51.494信息9704 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean:将过滤器:“ myFilter”映射到:[/ *]

我们生成的过滤链:

2016-11-04 09:19:52.729信息9704-[ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher.AnyRequestMatcher@1,[org.springframework .security.web.context.request.async.WebAsyncManagerIntegrationFilter @ 5d8c5a8a,org.springframework.security.web.context.SecurityContextPersistenceFilter@7d6938f,org.springframework.security.web.header.HeaderWriterFilter@72aa89c,org.springframework.security.web .csrf.CsrfFilter @ 4af4df11,com.company.praktikant.MyFilter@5ba65db2,org.springframework.security.web.authentication.logout.LogoutFilter@2330834f,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@396532d1,org.springframework .security.web.servletapi.SecurityContextHolderAwareRequestFilter @ 4fc0f1a2,org.springframework.security.web.authentication。AnonymousAuthenticationFilter @ 2357120f,org.springframework.security.web.session.SessionManagementFilter @ 10867bfb,org.springframework.security.web.access.ExceptionTranslationFilter @ 4b8bf1fb,org.springframework.security.web.access.intercept.FilterSecurityInterceptor @ 42063cf1]

我们也从Spring开始尝试了该解决方案,但没有成功!控制器中的@CrossOrigin注释也无济于事。

编辑1:
尝试了@PiotrSołtysiak的解决方案。cors过滤器未在生成的过滤器链中列出,我们仍然遇到相同的错误。

2016-11-04 10:22:49.881信息8820-[ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher.AnyRequestMatcher@1,[org.springframework .security.web.context.request.async.WebAsyncManagerIntegrationFilter @ 4c191377,org.springframework.security.web.context.SecurityContextPersistenceFilter@28bad32a,org.springframework.security.web.header.HeaderWriterFilter@3c3ec668,org.springframework.security.web .csrf.CsrfFilter @ 288460dd,org.springframework.security.web.authentication.logout.LogoutFilter@1c9cd096,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3990c331,org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter @ 1e8d4ac1,org.springframework.security.web.authentication.www.BasicAuthenticationFilter @ 2d61d2a4,org。springframework.security.web.savedrequest.RequestCacheAwareFilter@380d9a9b,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@abf2de3,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2a5c161b,org.springframework.security.web.session。 SessionManagementFilter @ 3c1fd3e5,org.springframework.security.web.access.ExceptionTranslationFilter @ 3d7055ef,org.springframework.security.web.access.intercept.FilterSecurityInterceptor @ 5d27725a]access.ExceptionTranslationFilter @ 3d7055ef,org.springframework.security.web.access.intercept.FilterSecurityInterceptor @ 5d27725a]access.ExceptionTranslationFilter @ 3d7055ef,org.springframework.security.web.access.intercept.FilterSecurityInterceptor @ 5d27725a]

顺便说一句,我们正在使用spring-security版本4.1.3。!


阅读 628

收藏
2020-04-12

共1个答案

小编典典

从Spring Security 4.1开始,这是使Spring Security支持CORS(在Spring Boot 1.4 / 1.5中也需要)的正确方法:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

and:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

千万不能做任何的下方,这是错误的方式来尝试解决问题:

  • http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
  • web.ignoring().antMatchers(HttpMethod.OPTIONS);
2020-04-12