春のセキュリティで簡単なソリューションを実装できます。 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も」受信
@PreAuthorize("hasPermission(#profile, 'update')")
public void updateUserProfileInASecureWay(UserProfile profile) {
//code to update user profile
}
をupdateUserProfileInASecureWayメソッドのパラメータからtargetDomainObject #profileを取得し、必要な権限(この場合は 'update')も渡します。
このソリューションは、「小さな」ACLを実装することによってACLのすべての複雑さを回避します。多分それはあなたのために働くことができます。
別に何かを作成する必要はありません。ロール管理はSpringセキュリティによって提供されます。ロール 'ROLE_READ、ROLE_CREATE'などを簡単に作成し、' @Secured( "condition") 'または' @PreAuthorize( "condition") 'というアノテーションを使用することができます。また、何を試してみましたか? –
**オブジェクトと一緒にメソッドを保護したい** –
安全なオブジェクトとはどういう意味ですか?メソッドはオブジェクトのgetterを呼び出します。メソッドが許可されていない場合は、オブジェクトも順番に許可されません。また、何を試してみたのですか? –