简体   繁体   English

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

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

Consider this code:考虑这段代码:

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

}

I ran the code in STS (SpringSource Tool Suite) and it worked as expected.我在 STS(SpringSource Tool Suite)中运行了代码,它按预期工作。 (It printed "Changing passwords..." .) Then I renamed the password to something else, expecting the method call to fail now. (它打印了"Changing passwords..." 。)然后我将密码重命名为其他内容,希望方法调用现在失败。

I have already added the line <global-method-security pre-post-annotations="enabled"/> to my applicationContext-security.xml configuration file.我已经将行<global-method-security pre-post-annotations="enabled"/>添加到我的applicationContext-security.xml配置文件中。

What am I missing here?我在这里想念什么?

  1. These annotations don't work on static methods这些注释不适用于static方法
  2. To make these annotations work you need to declare your object as a bean of the application context (the one with <global-method-security> element), and call the annotated method on the instance obtained from the context.要使这些注释起作用,您需要将 object 声明为应用程序上下文的一个 bean(具有<global-method-security>元素的那个),并在从上下文中获得的实例上调用带注释的方法。

Basically, these annotations are based on Spring AOP support and inherit all limitations of a proxy-based AOP .基本上,这些注释基于 Spring AOP 支持并继承了基于代理的 AOP的所有限制。 For better understanding you can take a look at the Spring AOP documentation .为了更好地理解,您可以查看Spring AOP 文档

@PreAuthorize does work on static methods, but you need to set the mode of global-method-security to aspectj @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