Spring对方法的安全注释如何工作?

soc*_*soc 0 java authorization annotations spring-security

考虑以下代码:

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");
    }

}
Run Code Online (Sandbox Code Playgroud)

我在STS(SpringSource工具套件)中运行代码,它按预期工作.(它打印出来"Changing passwords ...".)然后我将密码重命名为其他东西,期待方法调用现在失败.

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

我在这里错过了什么?

axt*_*avt 6

  1. 这些注释不适用于static方法
  2. 要使这些注释工作,您需要将对象声明为应用程序上下文的bean(带<global-method-security>元素的bean ),并在从上下文获取的实例上调用带注释的方法.

基本上,这些注释基于Spring AOP支持并继承了基于代理的AOP的所有限制.为了更好地理解,您可以查看Spring AOP文档.