Spring Security:
在更新Spring Security3.0到4.0系列时,出现UrlMatcher和AntUrlPathMatcher失效,原因是4.0系列中已经不存在这两个类了,在使用时可以用如下方式替换:
原码:
private UrlMatcher urlMatcher = new AntUrlPathMatcher(); //3.0版本
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation)object;
String requestURL = fi.getRequestUrl();
Map<String, Collection<ConfigAttribute>> others = null;
try{
SecurityUser user =(SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
others = user.getOtherPermissions();
}catch (Exception e) {
System.out.println("加载额外权限异常!!!可能此请求前并未曾登录!!!");
}
// 如果后台改了权限资源表,则须刷新内存,在这通过判断resourceMap是否为null来重载所有资源权限信息
if (resourceMap == null) {
loadResourceDefine();
}
Iterator<String> iterator = resourceMap.keySet().iterator();
while (iterator.hasNext()) {
String resURL = iterator.next();
if (urlMatcher.pathMatchesUrl(resURL+"**",requestURL)) {//这里要改成正则表达式的匹配方式
// 从额外权限列表中取,如果取得到则返回,取不到返回该URL对应的权限[session]
if(others!=null && others.containsKey(resURL)){
Collection<ConfigAttribute> tempCA = new ArrayList<ConfigAttribute>();
tempCA.addAll(others.get(resURL));
tempCA.addAll(resourceMap.get(resURL));
return tempCA;
}
return resourceMap.get(resURL);
}
}
return null;
}
4.0版本替换:
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation)object;
Map<String, Collection<ConfigAttribute>> others = null;
try{
SecurityUser user =(SecurityUser) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
others = user.getOtherPermissions();
}catch (Exception e) {
System.out.println("加载额外权限异常!!!可能此请求前并未曾登录!!!");
}
// 如果后台改了权限资源表,则须刷新内存,在这通过判断resourceMap是否为null来重载所有资源权限信息
if (resourceMap == null) {
loadResourceDefine();
}
Iterator<String> iterator = resourceMap.keySet().iterator();
while (iterator.hasNext()) {
String resURL = iterator.next();
//4.0版本,这里要改成正则表达式的匹配方式
RequestMatcher requestMatcher = new AntPathRequestMatcher(resURL + "**");
//if (urlMatcher.pathMatchesUrl(resURL+"**",requestURL)) { 3.0版本
if (requestMatcher.matches(fi.getHttpRequest())) {
// 从额外权限列表中取,如果取得到则返回,取不到返回该URL对应的权限[session]
if(others!=null && others.containsKey(resURL)){
Collection<ConfigAttribute> tempCA = new ArrayList<ConfigAttribute>();
tempCA.addAll(others.get(resURL));
tempCA.addAll(resourceMap.get(resURL));
return tempCA;
}
return resourceMap.get(resURL);
}
}
return null;
}