如何在 Spring Security 中自定義權限表達式

前面的文章中,松哥已經和小伙伴們聊了 Spring Security 中的權限表達式了,還沒看過的小伙伴們可以先看下,本文將在前文的基礎上繼續完善:

1. SpEL 回顧

經過上篇文章的學習,小伙伴們已經知道了,在 Spring Security 中,@PreAuthorize、@PostAuthorize 等注解都是支持 SpEL 表達式的。

在 SpEL 表達式中,如果上來就直接寫要執行的方法名,那么就說明這個方法是 RootObject 對象中的方法,如果要執行其他對象的方法,那么還需要寫上對象的名字,例如如下兩個例子:

@PreAuthorize("hasAuthority('system:user:add')")
public String add() {
    return "add";
}

上面這個例子中,表達式中的方法是 hasAuthority,沒有寫對象名,那么就說明這個方法是 SpEL 中 RootObject 對象中的方法。

@PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(SysOperLog operLog) {
    startPage();
    List<SysOperLog> list = operLogService.selectOperLogList(operLog);
    return getDataTable(list);
}

上面這個例子中,權限注解中的表達式方法是 @ss.hasPermi('monitor:operlog:list'),其中 ss 是指 Spring 容器中的一個對象名,hasPermi 則是這個對象中的方法。

好啦,經過前面文章的學習,這些基本知識大家都已經掌握了。

2. 如何自定義

其實上面給出來的第二個例子就是一個自定義的例子。

不過,這種自定義方式太自由了,自由到沒有在 Spring Security 架構內完成這件事。所以,今天我想和小伙伴們聊一聊,如何在不使用第三方對象的情況下,來自定義一個權限判斷的表達式。

首先小伙伴們知道,我們在 @PreAuthorize 注解中使用的不用加對象名就能調用的權限方法,如 hasAuthorityhasPermissionhasRolehasAnyRole 等,基本上都是由 SecurityExpressionRoot 及其子類提供的,準確來說是由 MethodSecurityExpressionRoot 類提供的。

MethodSecurityExpressionRoot 類實際上繼承自 SecurityExpressionRoot,只不過增加了過濾對象以及返回值對象。我們來看下 MethodSecurityExpressionRoot 的方法摘要:

[圖片上傳失敗...(image-c1f6ef-1657541408706)]

再來看看 SecurityExpressionRoot 中的方法:

[圖片上傳失敗...(image-4214e6-1657541408706)]

這些就是 RootObject 對象中的所有方法了,也是我們能夠在 @PreAuthorize 注解中使用的所有方法了。

那么現在想在已有方法上繼續擴展新方法,那么我們可以通過自定義類繼承自 SecurityExpressionRoot 對象,擴展這個 RootObject 對象,在該對象中繼續添加新的方法,進而實現自定義權限表達式。

好啦,說干就干,開搞!

本文的案例在前文的基礎上繼續完成,所以這里我就不從頭開始寫了。

3. 自定義 ExpressionRoot

首先我們自定義一個類繼承自 SecurityExpressionRoot 并實現 MethodSecurityExpressionOperations 接口(本來直接繼承自 MethodSecurityExpressionRoot 即可,但是因為這個類不是 public 的,沒法繼承,所以我們就實現 MethodSecurityExpressionOperations 接口即可):

public class CustomSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * Creates a new instance
     *
     * @param authentication the {@link Authentication} to use. Cannot be null.
     */
    public CustomSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    /**
     * 判斷當前對象是否具備某一個權限
     * @param permission
     * @return
     */
    public boolean hasPermission(String permission) {
        //獲取當前登錄用戶所具有的權限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if (antPathMatcher.match(authority.getAuthority(), permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否具備多個權限中的任意一個權限
     * @param permissions
     * @return
     */
    public boolean hasAnyPermissions(String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            for (String permission : permissions) {
                if (antPathMatcher.match(authority.getAuthority(), permission)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean hasAllPermissions:(String... permissions) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        for (String permission : permissions) {
            boolean flag = false;
            for (GrantedAuthority authority : authorities) {
                if (antPathMatcher.match(authority.getAuthority(), permission)) {
                    flag = true;
                }
            }
            if (!flag) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void setFilterObject(Object filterObject) {
        this.filterObject = filterObject;
    }

    @Override
    public Object getFilterObject() {
        return filterObject;
    }

    @Override
    public void setReturnObject(Object returnObject) {
        this.returnObject = returnObject;
    }

    @Override
    public Object getReturnObject() {
        return returnObject;
    }

    @Override
    public Object getThis() {
        return this;
    }
}

加了 @Override 注解的方法,都是普普通通的常規方法,沒啥好說的。我們自己主要實現了三個方法,分別是:

  • hasPermission:判斷當前用戶是否具備某一個給定的權限。
  • hasAnyPermissions:判斷當前用戶是否具備給定的多個權限中的某一個。
  • hasAllPermissions:判斷當前用戶是否具備所有的給定的權限。

這里邊的邏輯我就不啰嗦了,都是基本的 Java 語法而已。

另外,用 AntPathMatcher 做比對是為了支持通配符,這個在上篇文章中已經說過了,這里不再贅述。

Spring Security 中,MethodSecurityExpressionRoot 的配置是通過 DefaultMethodSecurityExpressionHandler 來完成的,現在我們自定義了 CustomSecurityExpressionRoot,那也得有一個 Handler 來配置 CustomSecurityExpressionRoot,所以,再來一個類繼承自 DefaultMethodSecurityExpressionHandler,如下:

public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {
    @Override
    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
        CustomSecurityExpressionRoot root = new CustomSecurityExpressionRoot(authentication);
        root.setTrustResolver(getTrustResolver());
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setRoleHierarchy(getRoleHierarchy());
        return root;
    }
}

在 createSecurityExpressionRoot 方法中創建一個 CustomSecurityExpressionRoot 對象,對象的 TrustResolver、權限評估器以及角色層級等,統統都用默認的方案即可。

配置完成后,再配置一下 CustomMethodSecurityExpressionHandler 這個 Bean 即可,如下:

@Bean
CustomMethodSecurityExpressionHandler customMethodSecurityExpressionHandler() {
    return new CustomMethodSecurityExpressionHandler();
}

好啦,這就注入成功了。

接下來,我們就可以在權限注解中使用這個自定義的方法了:

@PreAuthorize("hasPermission('system:user:add')")
public String add() {
    return "add";
}

這個自定義權限表達式的思路,說到底還是在 Spring Security 體系中玩,個人感覺這種方式更合理一些。

在 TienChin 項目中,松哥也將按照這種思路去改造 RuoYi-Vue 腳手架。屆時在 TienChin 項目視頻中,我再和大伙細聊,對視頻感興趣的小伙伴,戳這里:TienChin 項目配套視頻來啦

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內容