2013-07-10 47 views
1

我正在開發Spring彈簧安全的MVC webapp。基於所有者用戶的實體訪問

根據記錄的用戶和當前訪問的實體,我必須允許或拒絕用戶查看或修改它。如果用戶創建了實體,他是所有者,他可以處理實體。我可以驗證它,因爲entity.user ==用戶。

我還有一些情況,只能通過獲取實體的父代或n-parent來比較用戶。例如entity.nestedEntity.user ==用戶

我見過春季安全有ACL支持(域對象安全),但我認爲我無法處理「父情況」。而且我不是從一個空的數據庫開始的。此外,我認爲我需要爲每個對象構建acl ..所以我認爲這不是正確的方法。

現在我做控制器層的檢查,獲取當前用戶並將其與存儲在請求對象中的用戶進行比較。如果它們不相同,則拋出一個AccessDeniedException。

爲了讓事情儘可能簡單,我可以採取哪些替代方法?

謝謝馬可

回答

4

您可以實現自己的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)')等等......

+0

嗯我喜歡它!我會試一下! – gipinani

相關問題