How to enable CORS in Grails 3.0.1

后端 未结 7 1316
有刺的猬
有刺的猬 2021-02-18 22:45

I would like to do cross origin communication using Grails in server side. The only documentation that I found is this one

https://grails.org/plugin/cors

but thi

7条回答
  •  一向
    一向 (楼主)
    2021-02-18 23:00

    We used a normal servlet filter with an entry in resources.groovy to solve this problem:

    public class CorsFilter extends OncePerRequestFilter {
    
        @Override
        protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
                throws ServletException, IOException {
    
            String origin = req.getHeader("Origin");
    
            boolean options = "OPTIONS".equals(req.getMethod());
            if (options) {
                if (origin == null) return;
                resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
                resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
                resp.addHeader("Access-Control-Max-Age", "3600");
            }
    
            resp.addHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
            resp.addHeader("Access-Control-Allow-Credentials", "true");
    
            if (!options) chain.doFilter(req, resp);
        }
    }
    

    resources.groovy:

    beans = {
        corsFilter(CorsFilter)
    }
    

    This works with CORS requests using basic authentication. I wrote the Grails 2.x plugin and this seemed easier than getting it to work with Grails 3.

提交回复
热议问题