使用Spring安全表達式控制系統功能訪問權限

一、SPEL表達式權限控制

spring security 3.0開始已經可以使用spring Expression表達式來控制授權,允許在表達式中使用複雜的布爾邏輯來控制訪問的權限。Spring Security可用表達式對象的基類是SecurityExpressionRoot。

表達式函數 描述
hasRole([role]) 用戶擁有指定的角色時返回true (Spring security默認會帶有ROLE_前綴),去除前綴參考
hasAnyRole([role1,role2]) 用戶擁有任意一個指定的角色時返回true
hasAuthority([authority]) 擁有某資源的訪問權限時返回true
hasAnyAuthority([auth1,auth2]) 擁有某些資源其中部分資源的訪問權限時返回true
permitAll 永遠返回true
denyAll 永遠返回false
anonymous 當前用戶是anonymous時返回true
rememberMe 當前用戶是rememberMe用戶返回true
authentication 當前登錄用戶的authentication對象
fullAuthenticated 當前用戶既不是anonymous也不是rememberMe用戶時返回true
hasIpAddress('192.168.1.0/24')) 請求發送的IP匹配時返回true

部分朋友可能會對Authority和Role有些混淆。Authority作為資源訪問權限可大可小,可以是某按鈕的訪問權限(如資源ID:biz1),也可以是某類用戶角色的訪問權限(如資源ID:ADMIN)。當Authority作為角色資源權限時,hasAuthority(’ROLE_ADMIN’)與hasRole(’ADMIN’)是一樣的效果。

二、SPEL在全局配置中的使用

我們可以通過繼承WebSecurityConfigurerAdapter,實現相關的配置方法,進行全局的安全配置(之前的章節已經講過) 。下面就為大家介紹一些如何在全局配置中使用SPEL表達式。

2.1.URL安全表達式

config.antMatchers("/system/*").access("hasAuthority('ADMIN') or hasAuthority('USER')")
      .anyRequest().authenticated();

這裏我們定義了應用/person/*URL的範圍,只有擁有ADMIN或者USER權限的用戶才能訪問這些person資源。

2.2.安全表達式中引用bean

這種方式,比較適合有複雜權限驗證邏輯的情況,當Spring Security提供的默認表達式方法無法滿足我們的需求的時候。首先我們定義一個權限驗證的RbacService。

@Component("rbacService")
@Slf4j
public class RbacService {
    //返回true表示驗證通過
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        //驗證邏輯代碼
        return true;
    }
    public boolean checkUserId(Authentication authentication, int id) {
        //驗證邏輯代碼
        return true;
    }
}

對於”/person/{id}”對應的資源的訪問,調用rbacService的bean的方法checkUserId進行權限驗證,傳遞參數為authentication對象和person的id。該id為PathVariable,以#開頭表示。

config.antMatchers("/person/{id}").access("@rbacService.checkUserId(authentication,#id)")
      .anyRequest().access("@rbacService.hasPermission(request,authentication)");

三、 Method表達式安全控制

如果我們想實現方法級別的安全配置,Spring Security提供了四種註解,分別是@PreAuthorize , @PreFilter , @PostAuthorize 和 @PostFilter

3.1.開啟方法級別註解的配置

在Spring安全配置代碼中,加上EnableGlobalMethodSecurity註解,開啟方法級別安全配置功能。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

3.2 使用PreAuthorize註解

@PreAuthorize 註解適合進入方法前的權限驗證。只有擁有ADMIN角色才能訪問findAll方法。

@PreAuthorize("hasRole('ADMIN')")
List<Person> findAll();

3.3 使用PostAuthorize註解

@PostAuthorize 在方法執行后再進行權限驗證,適合根據返回值結果進行權限驗證。Spring EL 提供返回對象能夠在表達式語言中獲取返回的對象returnObject。下文代碼只有返回值的name等於authentication對象的name才能正確返回,否則拋出異常。

@PostAuthorize("returnObject.name == authentication.name")
Person findOne(Integer id);

3.4 使用PreFilter註解

PreFilter 針對參數進行過濾,下文代碼錶示針對ids參數進行過濾,只有id為偶數才能訪問delete方法。

//當有多個對象是使用filterTarget進行標註
@PreFilter(filterTarget="ids", value="filterObject%2==0")
public void delete(List<Integer> ids, List<String> usernames) {

3.5 使用PostFilter 註解

PostFilter 針對返回結果進行過濾,特別適用於集合類返回值,過濾集合中不符合表達式的對象。

@PostFilter("filterObject.name == authentication.name")
List<Person> findAll();

期待您的關注

  • 博主最近新寫了一本書:
  • 本文轉載註明出處(必須帶連接,不能只轉文字):。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

網頁設計公司推薦更多不同的設計風格,搶佔消費者視覺第一線

※廣告預算用在刀口上,網站設計公司幫您達到更多曝光效益

※自行創業 缺乏曝光? 下一步"網站設計"幫您第一時間規劃公司的門面形象

台灣寄大陸海運貨物規則及重量限制?

大陸寄台灣海運費用試算一覽表