PermissionsAuthorizationFilter是权限验证的关键过滤器。
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
return this.isAccessAllowed(request, response,mappedValue) || this.onAccessDenied(request, response,mappedValue);
}
具体验证方法如下:
委托subject验证,subject又委托authleam数据源进行验证,
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
Subject subject = this.getSubject(request, response);
String[] perms = (String[])mappedValue;
boolean isPermitted = true;
if(perms != null && perms.length > 0) {
if(perms.length == 1) {
if(!subject.isPermitted(perms[0])) {
isPermitted = false;
}
} else if(!subject.isPermittedAll(perms)) {
isPermitted = false;
}
}
return isPermitted;
}
@Override
public boolean isPermitted(PrincipalCollection principals, String permission) {
this.assertRealmsConfigured();
Iterator var3 = this.getRealms().iterator();
Realm realm;
do {
if(!var3.hasNext()) {
return false;
}
realm = (Realm)var3.next();
} while(!(realm instanceof Authorizer) || !((Authorizer)realm).isPermitted(principals, permission));
return true;
}
这里调用AuthenAuthorityRealm的验证方法,AuthorizationInfo info = this.getAuthorizationInfo(principals);会调用用户自定义的数据源获取权限信息。
public boolean isPermitted(PrincipalCollection principals, String permission){
Permission p = this.getPermissionResolver().resolvePermission(permission);
AuthorizationInfo info = this.getAuthorizationInfo(principals);
Collection perms = this.getPermissions(info);
if(perms != null && !perms.isEmpty()) {
Iterator var4 = perms.iterator();
while(var4.hasNext()) {
Permission perm = (Permission)var4.next();
if(perm.implies(p)) {
return true;
}
}
}
return false;
}
而上面的this.onAccessDenied(request, response,mappedValue);这个方法则会在无权限的时候调用。
无权限时,则会重定向到无权限路径。
protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = this.getSubject(request, response);
if(subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
String unauthorizedUrl = this.getUnauthorizedUrl();
HttpServletRequest httpRequest=WebUtils.toHttp(request);
if (httpRequest.getHeader("X-Requested-With") == null || !httpRequest.getHeader("X-Requested-With").equals("XMLHttpRequest")) {
if(StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}else {
WebUtils.toHttp(response).sendError(401,"没有权限");
}
}
return false;
}