【问题标题】:How do Spring's security annotations on methods work?Spring 对方法的安全注解是如何工作的?
【发布时间】:2012-04-07 16:05:26
【问题描述】:

考虑这段代码:

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 配置文件中。

我在这里错过了什么?

【问题讨论】:

    标签: java annotations spring-security authorization


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

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

    【讨论】:

    • 有意思,想详细解释一下吗?
    【解决方案2】:

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

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

    【讨论】:

    • 您能详细说明一下吗?我找不到任何关于此的文档,并且添加 mode="aspectj" 会破坏 @PreAuthorize 对我的非静态方法。
    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 2015-09-29
    • 1970-01-01
    • 2015-12-07
    • 2021-03-10
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多