一、SPEL表達式權限控制
從spring security 3.0開始已經可以使用spring Expression表達式來控制授權,允許在表達式中使用復雜的布爾邏輯來控制訪問的權限。Spring Security可用表達式對象的基類是SecurityExpressionRoot。
表達式函數
描述
hasRole([role])
用戶擁有指定的角色時返回true (Spring security默認會帶有ROLE_前綴),去除前綴參考Remove the 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 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 ids, List usernames) {
3.5 使用PostFilter 注解
PostFilter 針對返回結果進行過濾,特別適用于集合類返回值,過濾集合中不符合表達式的對象。
@PostFilter("filterObject.name == authentication.name")
List findAll();
總結
以上所述是小編給大家介紹的使用Spring安全表達式控制系統功能訪問權限問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!