簡體   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