カスタム許可ロジックをチェックする独自の PermissionEvaluator を実装できます。次に、新しく作成した PermissionEvaluator を Spring Security に登録すると、Spring Security アノテーションでカスタム権限チェックを使用できます。
最小限の例 (春のセキュリティ構成):
<!-- Enable usage of @Pre & @Post security annotations -->
<global-method-security secured-annotations="enabled" pre-post-annotations="enabled">
<expression-handler ref="expressionHandler"/>
</global-method-security>
<!-- Use CustomPermissionEvaluator as permission evaluator to control access to application with specific permission rules -->
<beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator" ref="customPermissionEvaluator"/>
</beans:bean>
<beans:bean id="customPermissionEvaluator" class="com.example.CustomPermissionEvaluator">
次に、CustomPermissionEvalutor には、カスタムの「OWNER」権限とカスタム ドメイン オブジェクトの権限チェックを行う hasPermission 実装が必要です。
このようなもの:
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
...
if ("OWNER".equals(permission.toString()) && targetDomainObject instanceof Entity) {
//fetch user from Authentication and verify if user is owner of Entity
}
...
}
最後に、アノテーションを使用してセキュリティを強化できます。
@PreAuthorize("hasPermission(#someEntity, 'OWNER')")
public someMethod(Entity someEntity) { ... }
Spring Security アノテーションで評価できる新しい関数を追加することもできます (ただし、より複雑です)。その場合、独自の isOwner 関数を追加でき、PreAuthorize は @PreAuthorize('isOwner(#someEntity)') のようになります。 ..