弹簧启动安全性的CORS问题

时间:2018-05-02 08:20:28

标签: spring-security cors

我使用弹簧靴,弹簧安全,并希望避免任何cors动作。我在这里尝试第二个答案(Can you completely disable CORS support in Spring?)我需要为cors添加自定义过滤器,这里是过滤器:

@Component
public class CorsFilter extends OncePerRequestFilter {

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

        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addIntHeader("Access-Control-Max-Age", 10);
        filterChain.doFilter(request, response);
    }
}

所以我在CorsFilter创建了类插入,我犯了错误:

'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'corsFilter' is expected to be of type 'org.springframework.web.filter.CorsFilter' but was actually of type 'fa.backend.core.security.CorsFilter'

我的安全配置如下所示:

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().antMatcher("/users").authorizeRequests()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .and()
                .addFilterBefore(
                        new JWTLoginFilter(tokenAuthentication, authenticationManagerBean()),
                        UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

你能告诉我如何解决这个问题吗?我的目标是禁用任何可能的行动,因为从前端我收到:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

1 个答案:

答案 0 :(得分:1)

删除配置覆盖中的'cors()。和'之后的部分。以下是片段。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/users").authorizeRequests()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .and()
                .addFilterBefore(
                        new JWTLoginFilter(tokenAuthentication, authenticationManagerBean()),
                        UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }