吃透Shiro源码7----AuthenticationInfo与重载
技术手法
(1)多个方法重载设计思路
如果有多重方法在重载的话,提供一个同名的private或protected方法。各种重载对象最后转成此private或protected方法需要的格式。其实今天处理的代码并不复杂,实际上就是通过AuthenticationInfo对象,将其解析成Collection<Permission>。
@Override
public void checkPermission(PrincipalCollection subjectPrincipal, String permission)
throws AuthorizationException {
Permission perm = getPermissionResolver().resolvePermission(permission);
AuthorizationInfo authorizationInfo = this.getAuthorizationInfo(subjectPrincipal);
checkPermission(perm, authorizationInfo);
}
@Override
public void checkPermission(PrincipalCollection subjectPrincipal, Permission permission)
throws AuthorizationException {
AuthorizationInfo authorizationInfo = this.getAuthorizationInfo(subjectPrincipal);
checkPermission(permission, authorizationInfo);
}
protected void checkPermission(Permission permission,
AuthorizationInfo authorizationInfo) {
if (!isPermitted(permission, authorizationInfo)) {
String msg = "用户无:[" + permission + "]权限";
throw new UnauthorizedException(msg);
}
}
(2)AuthenticationInfo设计思路
大佬总是面向接口编程的。如果是我设计,我根本想不到把这些对象抽象为接口。
public interface AuthorizationInfo extends Serializable {
/**
* 获取角色列表
*
* @return 角色列表
*/
Collection<String> getRoles();
/**
* 获取权限列表(字符串)
*
* @return 权限列表
*/
Collection<String> getStringPermissions();
/**
* 获取所有权限(对象)
*
* @return
*/
Collection<Permission> getObjectPermissions();
}
private Collection<Permission> getPermissions(AuthorizationInfo info) {
if (info == null) {
return CollectionUtils.emptySet();
}
Collection<Permission> result = new HashSet<>();
//把AuthorizationInfo中的三种不同的权限组合取出来,分别解析
Collection<Permission> objectPermissions = info.getObjectPermissions();
if (CollectionUtils.isNotEmpty(objectPermissions)) {
result.addAll(objectPermissions);
}
Collection<String> stringPerms = info.getStringPermissions();
if (CollectionUtils.isNotEmpty(stringPerms)) {
result.addAll(this.resolvePermissions(stringPerms));
}
Collection<String> roles = info.getRoles();
if (CollectionUtils.isNotEmpty(roles)) {
result.addAll(this.resolveRolePermissions(roles));
}
return result;
}