简体   繁体   中英

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. (It printed "Changing passwords..." .) Then I renamed the password to something else, expecting the method call to fail now.

I have already added the line <global-method-security pre-post-annotations="enabled"/> to my applicationContext-security.xml configuration file.

What am I missing here?

  1. These annotations don't work on static methods
  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.

Basically, these annotations are based on Spring AOP support and inherit all limitations of a proxy-based AOP . For better understanding you can take a look at the Spring AOP documentation .

@PreAuthorize does work on static methods, but you need to set the mode of global-method-security to aspectj

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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