SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

通過前面的文章,我們已經實現了基於數據進行登錄鑑權及基於註解的方式進行方法鑑權


註解方式的方法鑑權:

通過 @EnableGlobalMethodSecurity 註解來開啟方法鑑權。

securedEnabled:開啟 @Secured 註解

  • 單個角色:@Secured(“ROLE_USER”)
  • 多個角色任意一個:@Secured({“ROLE_USER”,“ROLE_ADMIN”})

prePostEnabled:開啟 @PreAuthorize 及 @PostAuthorize 註解,分別適用於進入方法前後進行鑑權,支持表達式

  • 允許所有訪問:@PreAuthorize(“true”)
  • 拒絕所有訪問:@PreAuthorize(“false”)
  • 單個角色:@PreAuthorize(“hasRole(‘ROLE_USER’)”)
  • 多個角色與條件:@PreAuthorize(“hasRole(‘ROLE_USER’) AND hasRole(‘ROLE_ADMIN’)”)
  • 多個角色或條件:@PreAuthorize(“hasRole(‘ROLE_USER’) OR hasRole(‘ROLE_ADMIN’)”)

jsr250Enabled:開啟 JSR-250 相關注解

  • 允許所有訪問:@PermitAll
  • 拒絕所有訪問:@DenyAll
  • 多個角色任意一個:@RolesAllowed({“ROLE_USER”, “ROLE_ADMIN”})

雖然非常靈活,但是畢竟是硬編碼,不符合實際的生產需求,在項目中,每個角色的可訪問權限必須是可調整的,一般情況下使用數據庫進行持久化。

目標

整合 SpringSecurity 及 MybatisPlus 實現使用讀取數據庫數據進行方法鑑權

思路

使用配置類的 HttpSecurity 提供的 access 方法,通過擴展SpEL表達式,實現自定義鑑權

<code>.access("@authService.canAccess(request, authentication)")/<code>

其中 authService 是 Spring 容器中的 Bean,canAccess 是其中的一個方法。

<code>@Service
public class AuthService {
public boolean canAccess(HttpServletRequest request, Authentication authentication) {
//在這裡編寫校驗代碼…
return true;

}
}/<code>

準備工作

創建用戶表 user、角色表 role、用戶角色關係表 user_role,資源表 resource,資源角色關係表 role_resource

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

操作步驟

添加依賴

引入 Spring Boot Starter 父工程

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

添加 springSecurity 及 mybatisPlus 的依賴,添加後的整體依賴如下

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

配置

配置一下數據源

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

編碼

用戶登錄相關代碼請參考 ,這裡不再粘貼。

實體類

角色實體類 Role,實現權限接口 GrantedAuthority

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

資源實體

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

資源角色關係實體

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

Repository 層

分別為三個實體類添加 Mapper

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

實現自定義方法鑑權

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

註冊配置

不用再聲明 @EnableGlobalMethodSecurity 註解,註冊自定義鑑權方法 authService.canAccess。

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

去掉原來的方法鑑權相關注解

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

啟動類
SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

驗證結果

初始化數據

執行測試用例進行初始化數據

SpringBoot2.0實戰(30)整合SpringSecurity基於數據庫方法鑑權

校驗

使用 admin 登錄可以訪問 /hello 及 /secure,使用 user 登錄則只能訪問 /hello

源碼地址

本章源碼 : https://gitee.com/gongm_24/spring-boot-tutorial.git

參考

249.Spring Boot+Spring Security:基於URL動態權限:擴展access()的SpEL表達式


分享到:


相關文章: