Spring+Shrio的解决方案
shiro中可以在自己实现的身份验证filter中加入以下代码:
@Override protected boolean preHandle(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if(request.getMethod().equals(RequestMethod.OPTIONS.name())) { response.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); }
shiro中AccessControlFilter提供了访问控制的基础功能;比如是否允许访问/当访问拒绝时如何处理等,也是我们一般自定义权限验证时候的一个父类,我们通过重写他的 onPreHandle 方法判断是否是 option 请求,如果是则设置相应状态,(响应头已经在之前文章中通过filter配置过了)返回false表示该拦截器实例已经处理了,将直接返回即可。
Tomcat配置
需要修改tomcat的全局web.xml文件在 CATALINA_HOME/conf 下,加入以下配置。
<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Nginx配置
add_header 'Access-Control-Allow-Methods' 'GET,OPTIONS,PUT,DELETE' always; add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Origin' '$http_origin' always; add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With' always; if ($request_method = OPTIONS ) { return 200; }
Apache配置
Header always set Access-Control-Allow-Origin "http://waffle" Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS" Header always set Access-Control-Allow-Credentials "true" Header always set Access-Control-Allow-Headers "Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With" RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L]
js请求示例
请求时候需要加上 Authorization 和 Content-Type 头。
$http({ method: 'POST', url: scope.webdav.url, withCredentials: true, headers: { Authorization: 'Basic ' + btoa(user + ':' + password), 'Content-Type': 'application/vnd.google-earth.kml+xml; charset=utf-8' }, data: getKml()
})