您可以使用 spring security 实现一个简单的解决方案。这个想法是创建一个实现 org.springframework.security.access.PermissionEvaluator 的类并覆盖方法hasPermission。看下一个例子:
@Component("permissionEvaluator")
public class PermissionEvaluator implements org.springframework.security.access.PermissionEvaluator {
/**
* @param authentication represents the user in question. Should not be null.
* @param targetDomainObject the domain object for which permissions should be
* checked. May be null in which case implementations should return false, as the null
* condition can be checked explicitly in the expression.
* @param permission a representation of the permission object as supplied by the
* expression system. Not null.
* @return true if the permission is granted, false otherwise
*/
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
if (authentication != null && permission instanceof String) {
User loggedUser = (User) authentication.getPrincipal();
String permissionToCheck = (String) permission;
// in this part of the code you need to check if the loggedUser has the "permission" over the
// targetDomainObject. In this implementation the "permission" is a string, for example "read", or "update"
// The targetDomainObject is an actual object, for example a object of UserProfile class (a class that
// has the profile information for a User)
// You can implement the permission to check over the targetDomainObject in the way that suits you best
// A naive approach:
if (targetDomainObject.getClass().getSimpleName().compareTo("UserProfile") == 0) {
if ((UserProfile) targetDomainObject.getId() == loggedUser.getId())
return true;
}
// A more robust approach: you can have a table in your database holding permissions to each user over
// certain targetDomainObjects
List<Permission> userPermissions = permissionRepository.findByUserAndObject(loggedUser,
targetDomainObject.getClass().getSimpleName());
// now check if in userPermissions list we have the "permission" permission.
// ETC...
}
//access denied
return false;
}
}
现在,通过这个实现,您可以在服务层中使用 @PreAuthorize 注释,如下所示:
@PreAuthorize("hasPermission(#profile, 'update')")
public void updateUserProfileInASecureWay(UserProfile profile) {
//code to update user profile
}
@PreAuthorize 注释中的“hasPermission”从 updateUserProfileInASecureWay 方法的参数接收 targetDomainObject #profile,并且我们传递了所需的权限(在本例中为“更新”)。
此解决方案通过实施“小型”ACL 避免了 ACL 的所有复杂性。也许它可以为你工作。