2011-07-12 46 views
0

考慮以下代碼:方法的Spring安全註解如何工作?

import java.util.Collections; 

import org.springframework.security.access.prepost.PreAuthorize; 
import org.springframework.security.core.userdetails.User; 

public class SecureStuff { 
    @PreAuthorize("#user.password == #oldPassword") 
    public static void changePassword(User user, String oldPassword, String newPassword){ 
     System.out.print("Changing passwords ..."); 
    } 

    public static void main(String[] args) { 
     User joe = new User("Joe", "HansWurst", true, true, true, true, Collections.EMPTY_LIST); 
     changePassword(joe, "HansWurst", "TeeWurst"); 
    } 

} 

我跑了STS的代碼(SpringSource工具套件)和它的工作如預期。 (它打印"Changing passwords ..."。) 然後我將密碼重命名爲其他內容,期望現在方法調用失敗。

我已將<global-method-security pre-post-annotations="enabled"/>行添加到我的applicationContext-security.xml配置文件中。

缺少什麼我在這裏?

回答

5
  1. 這些註釋不上static方法
  2. 爲了使這些註釋工作,你需要聲明你的對象作爲應用程序上下文(具有<global-method-security>元素)的一個bean,並調用註解的方法工作從上下文獲得的實例。

基本上,這些註釋基於Spring AOP支持並繼承了proxy-based AOP的所有限制。爲了更好地理解,你可以看看Spring AOP documentation

+0

有趣,注意解釋一下更詳細的? – soc

+0

@soc:更新.. – axtavt

1

@PreAuthorize做靜態方法的工作,但你需要全球方法的安全模式設置爲AspectJ的

<global-method-security pre-post-annotations="enabled" mode="aspectj"/> 
+0

你能詳細說明嗎?我無法找到任何文檔,並添加mode =「aspectj」打破了我的非靜態方法的@PreAuthorize。 – Tomasz