spring bootカスタムフィルタのドメイン横断問題を解決します.

1142 ワード

カスタムフィルタを使うとき
カスタムフィルタを使用すると、注@CrossOriginは無効になりますので、以下のコードで解決します.
public class TokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServlet Requestrequest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // do something
        cors(request, response);
        // do something
    }
  
    private void cors(HttpServletRequest request, HttpServletResponse response) {
        String allowOrigin = request.getHeader("Origin");
        String allowMethods = "GET,PUT, POST, DELETE";
        String allowHeaders = "Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Cache-Control, Expires, Content-Type, X-E4M-With";
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", allowHeaders);
        response.addHeader("Access-Control-Allow-Methods", allowMethods);
        response.addHeader("Access-Control-Allow-Origin", allowOrigin);
    }
}