最近在做个项目,启用了Angularjs作为前端框架,后端则使用java服务端,引入了shiro框架作为权限管理。
理想是丰满的,现实是骨感的。
起先单域测试下一切Ok,进行二级域名跨域测试就出现问题了。
本文是基于单个顶级域名多个子域名的跨域
项目架构并非采用SpringMVC,以及SSH等主流框架,使用了自己公司的非主流框架,请各位同学自己纠正
遇到坑以及填坑
- Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods
跨域请求的时候遇到了Access-Control-Allow-Origin问题,起先在Filter中是这么解决的,代码如下:
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Headers", "accept, content-type");
response.addHeader("Access-Control-Allow-Methods", "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT");
但是考虑到Origin全开放有点不好吧,然后我也多想,就直接在Filter中写了一个Origin的校验,代码如下:
private String getDomain(String host) {
if (host.endsWith(domain)) {
return SecondDomainKit.contains(host.substring(0, host.length() - (domain.length() + 1)));
} else return null;
}
response的Header设置修改为:
// 校验数据来源,成功后进行跨域授权
String origin = request.getHeader("Origin");
if (StrKit.notBlank(origin)) {
Pattern pattern = Pattern.compile("([a-zA-z]+://){0,1}([^\\s]*)");
Matcher matcher = pattern.matcher(origin);
if (matcher.find()) {
String host = matcher.group(2);
if (host.endsWith(domain) && !host.equals(domain) && StrKit.notBlank(getDomain(host))) {
response.addHeader("Access-Control-Allow-Origin",
request.getScheme() + "://" + getDomain(host) + "." + domain);
response.addHeader("Access-Control-Allow-Headers", "accept, content-type");
response.addHeader("Access-Control-Allow-Methods", "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT");
}
}
}
- session不共享
在shiro.ini中配置为使用Cookies进行Session管理,配置如下:
sessionIdCookie = org.apache.shiro.web.servlet.SimpleCookie
sessionIdCookie.name = JMSESSIONID #可修改Cookie的名称
sessionIdCookie.domain = xxxx.com #这里填入顶级域名
sessionIdCookie.maxAge = 604800
...
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionIdCookie = $sessionIdCookie
sessionManager.sessionIdCookieEnabled = true
...
- POST请求中session会刷新,导致登陆成功之后,Shiro任然取不到身份信息,这个也困扰了我好久。直接给出修改代码,在js中修改如下:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
将Filter中response的Header修改下,代码如下:
// 校验数据来源,成功后进行跨域授权
String origin = request.getHeader("Origin");
if (StrKit.notBlank(origin)) {
Pattern pattern = Pattern.compile("([a-zA-z]+://){0,1}([^\\s]*)");
Matcher matcher = pattern.matcher(origin);
if (matcher.find()) {
String host = matcher.group(2);
if (host.endsWith(domain) && !host.equals(domain) && StrKit.notBlank(getDomain(host))) {
response.addHeader("Access-Control-Allow-Origin",
request.getScheme() + "://" + getDomain(host) + "." + domain);
response.addHeader("Access-Control-Allow-Headers", "accept, content-type");
response.addHeader("Access-Control-Allow-Methods", "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT");
// 是否支持cookie跨域
response.addHeader("Access-Control-Allow-Credentials", "true");
}
}
}
网友评论