Spring 5 Cors和Csrf集成用于angular js前端http 401

时间:2019-05-18 09:13:09

标签: spring spring-boot spring-security

我正在尝试执行从angular js前端到Spring Boot中间件(Spring Boot 2.1.4)的请求。在我将应用程序迁移到Spring Boot之前,该设置可以正常工作。

在Spring Boot迁移后,来自Web XML的所有筛选器和安全性配置均已以带注释的类的形式进行配置。

现在,我的用户界面请求被spring boot拒绝,并且cors策略为401的http (Allowed-Origin)错误

我当前的项目设置如下

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasAnyRole("ROLE_USER").anyRequest()
                .authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository());
    }

    private CsrfTokenRepository csrfTokenRepository() {
        CustomDomainCookieCsrfTokenRepository repository = new CustomDomainCookieCsrfTokenRepository();
        repository.setCookieHttpOnly(false);
        return repository;
    }

}

@WebFilter("/*")
public class ForceCORSFilter extends OncePerRequestFilter {

    protected final Logger log = Logger.getLogger(this.getClass());
    private CacheService cacheService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            List<String> originList = getCacheService().getValidOriginUrI();
            String clientOrigin = request.getHeader("origin");
            if (clientOrigin == null) {
                // process the request even if origin is null
                processValidRequest(request, response, filterChain, clientOrigin);
            }
            if (clientOrigin != null) {
                // Origin should be validated if not null
                if (originList.contains(clientOrigin)) {
                    processValidRequest(request, response, filterChain, clientOrigin);
                } else {
                    log.info("####################### ORIGIN IS INVALID #######################" + clientOrigin);
                    filterChain.doFilter(request, response);
                }
            }
        } catch (Exception e) {
            response.getWriter()
                    .write("An error has occured while processing the request. Please retry with proper request.");
            log.info("An error has occured in the request " + e.getMessage());
        }
    }

    private void processValidRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain,
            String clientOriginAllowed) throws IOException, ServletException {
        response.addHeader("Access-Control-Allow-Origin", clientOriginAllowed);
        response.addHeader("Access-Control-Allow-Credentials", "true");
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, HEAD");
            response.addHeader("Access-Control-Allow-Headers",
                    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization, X-XSRF-TOKEN");
        } else {
            filterChain.doFilter(request, response);
        }
    }

    public CacheService getCacheService() {
        return cacheService;
    }

    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

}

有人可以指出这里有什么问题吗?为什么我仍然得到

  

http 401“没有'Access-Control-Allow-Origin'标头出现在   请求的资源”错误。

1 个答案:

答案 0 :(得分:0)

一个问题可能是优先事项-筛选器的运行顺序不正确。您可以使用@Order(Ordered.HIGHEST_PRECEDENCE),使其在Spring Security过滤器之前运行。

说过,Spring已经对CORS提供了一流的支持,因此根本不需要繁琐地定义过滤器。请参见documentationan example