您可以實現自己的PermissionEvaluator,將檢查您的自定義權限的邏輯。 然後,您使用Spring Security註冊您新創建的PermissionEvaluator,並且您可以使用 您在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應該調用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) { ... }
也可以(但更復雜),以增加新的功能,你可以在這種情況下,你可以添加你自己的isOwner函數並且PreAuthorize可以看起來像@PreAuthorize('isOwner(#someEntity)')等等......
嗯我喜歡它!我會試一下! – gipinani