Spring REST 安全测试 - 跨源问题

Spring REST Security Testing - Cross Origin Issue

我正在开发 Spring Boot 和 Spring Rest 应用程序。安全测试已报告该问题

"The web application or services inform web client of the allowed domain using the HTTP response header Access-Control-Allow-Origin. The header can contain a '*' to indicate that all domain are allowed."

补救 -

Use the Access-Control-Allow-Origin header only on chosen URLs that need to be accessed cross-domain. Don't use the header for the whole domain.

在发出 HTTP 请求时,他们使用了 origin: null,然后是 Access-Control-Allow-Origin: *

我该如何实施?

在你的项目中使用它,我认为它会解决你的问题,

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Filter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token, token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }


}