其实这个问题一开始是解决的,一个@CrossOrigin搞定,但是后来在shiro中获取用户的时候有获取不到的问题,特别记录!
为啥又跟shiro扯上关系呢?因为shiro认证授权都没问题,登录也没毛病,但是在获取菜单的时候俺需要get到当前用户的时候就有问题了,明明相同的配置,为啥就是获取不到呢?百度到一个论坛上大佬说前台要传cookie下来(其实是一个sessionId),俺还是很纳闷,但是还是有个思路了。
在前端axios配置中加上一句axios.defaults.withCredentials = true后,新的问题又来了:
Access to XMLHttpRequest at 'http://127.0.0.1:8081/logon' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
翻译一下这句话
当请求的凭据模式为“include”时,响应中“Access Control Allow Origin”头的值不能是通配符“*”。XMLHttpRequest启动的请求的凭据模式由withCredentials属性控制。
开始在这里纠结了老半天,都是围绕着@CrossOrigin去解决这个问题,但是发现我把Access Control Allow Origin的值设为当前我请求的ip和端口时有报跨域异常。不错,就是@CrossOrigin失效了,找了好久还是没有找到解决方式,可能是我搜索的姿势不对吧QAQ。
后来还是用Filter自定义拦截器顺利解决
这就是完整的头头:
//response.reset(); response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin")); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACES"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE"); response.setHeader("Access-Control-Allow-Credentials", "true");
如果你想自己一步一步探索,将会依次碰到 Access-Control-Allow-Origin不能为通配符“*”、Access-Control-Allow-Credentials为空、Access-Control-Allow-Headers没有被允许等等问题(自己瞎吉儿翻译的,有怪莫怪有怪莫怪,嘿嘿)
探索是永恒无尽的力量!