繁体   English   中英

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

[英]How do Spring's security annotations on methods work?

考虑这段代码:

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 Tool Suite)中运行了代码,它按预期工作。 (它打印了"Changing passwords..." 。)然后我将密码重命名为其他内容,希望方法调用现在失败。

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

我在这里想念什么?

  1. 这些注释不适用于static方法
  2. 要使这些注释起作用,您需要将 object 声明为应用程序上下文的一个 bean(具有<global-method-security>元素的那个),并在从上下文中获得的实例上调用带注释的方法。

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

@PreAuthorize 确实适用于 static 方法,但您需要将 global-method-security 的模式设置为 aspectj

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM