实现
在配置文件中设置白名单,名称可以自定义,对应好就行
1 | xy.cors-white-list=https//www.JD.com/,https//www.JD.com:81,https//api.JD.com,https//shop.JD.com,https//h5.shop.JD.com |
通过@Value获取白名单,手动匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | @Value ( "${xy.cors-white-list}" ) private String whiteList; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String origin = request.getHeader( "origin" ); response.setHeader( "Access-Control-Allow-Origin" , Tools.asList(whiteList.split( "," )).contains(origin) ? origin : "-" ); response.setHeader( "Access-Control-Allow-Credentials" , "true" ); response.setHeader( "Access-Control-Allow-Methods" , "POST, GET, PATCH, DELETE, PUT, OPTIONS" ); response.setHeader( "Access-Control-Max-Age" , "3600" ); response.setHeader( "Access-Control-Allow-Headers" , "*" ); if ( "OPTIONS" .equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } |