SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

通過前一篇文章 ,我們已經可以簡單地使用 SpringSecurity 對應用實現登錄鑑權,但是問題在於,用戶信息或者是在配置文件中,或者是在代碼中寫死,應用啟動後被加載至內存,這並不符合實際的生產需要,在實際的生產應用中,我們需要使用數據庫對用戶及角色信息進行持久化,在執行登錄操作時,從數據庫中獲取用戶信息。

目標

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

準備工作

創建用戶表 user、角色表 role、用戶角色關係表 user_role

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

操作步驟

添加依賴

引入 Spring Boot Starter 父工程

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

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

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

配置

配置一下數據源

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權


編碼

實體類

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

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

用戶實體類 user,實現權限接口 UserDetails,主要方法是 getAuthorities,用於獲取用戶的角色列表

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

用戶角色關係實體

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

Repository 層

分別為三個實體類添加 Mapper

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

實現 UserDetailsService 接口

UserDetailsService 是 SpringSecurity 提供的登陸時用於根據用戶名獲取用戶信息的接口

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

權限配置

繼承 SpringSecurity 提供的 WebSecurityConfigurerAdapter 配置 userDetailsService 及加密方式

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

啟動類

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

驗證結果

初始化數據

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

SpringBoot2.0實戰(25)整合SpringSecurity之數據庫登錄鑑權

校驗

網頁訪問 http://localhost:8080,將自動跳轉登錄頁,輸入 user/123456 進行登錄,可以使用 debugger 進行調試。

源碼地址

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

結束語

使用數據庫進行鑑權,是實際應用中最基本的需求。


分享到:


相關文章: