注:該博客是對上一遍博客的進階https://www.cnblogs.com/fernfei/p/12194828.html
一、創建項目並導入依賴
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<artifactId>mysql-connector-java</artifactId>
注:maven默認不編譯src/main/java下的xml文件,需要我們手動導入
二、相關配置和代碼
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/security
spring.datasource.username=root
spring.datasource.password=123
3)數據庫表結構
密碼是123 springsecurity加密算法后的密文,可以讓同樣的密碼每次生成的密文都不一樣,從而不會重復,我們案列中的密文是我偷懶復制粘貼的所以一樣
4)創建實體類User、Role、Menu
4.1)創建User實現UserDetails
這里要實現UserDetails接口,這個接口好比一個規范。防止開發者定義的密碼變量名各不相同,從而導致springSecurity不知道哪個方法是你的密碼
我給的數據庫中user表沒有UserDetails的幾個方法,可以直接手動給它true
有的,就用數據庫查出來的屬性!
4.2)創建Role類
4.3)創建Menu類
5)創建UserMapper類&&UserMapper.xml和MenuMapper類&&MenuMapperxml
5.1)UserMapper.class
注:以前在SSM框架之所以不用加類似@Service和@controller的注解時因為我們在xml文件已經配置了,如今使用SpringBoot所以我們也要改變寫法
一共兩種寫法
5.1.1)在類上直接加@Mapper
5.1.2)在SpringBoot啟動類上配置全局的掃描
5.2)UserMapper.xml
5.3)MenuMapper類
5.4)MenuMapper.xml
sql語句是左外連接,主表menu_role連查menu和role
SELECTm. *,r.idasrid,r.nameasrname,r.nameZhasrnameZhfrommenu_rolemrLEFTJOINmenumONmr.mid=m.idLEFTJOINroleronmr.rid=r.id
6)創建UserService&&MenuService
6.1)創建UserService實現UserServiceDetails接口
6.2)創建MenuService
7)創建CustomFilterInvocationSecurityMetadataSource
7.1)實現接口FilterInvocationSecurityMetadataSource
注:加@comppent注解,把自定義類注冊成spring組件
7.2)supports返回值設成true表示支持
7.3)重寫getAttributes()方法
8)創建CustomAccessDecisionManager
8.1)實現AccessDecisionManager接口
注:加@comppent注解,把自定義類注冊成spring組件
8.2)將兩個supports()都設置成true
8.3)重寫decide()方法
9)創建WebSecurityConfig配置類
9.1)WebSecurityConfig實現WebSecurityConfigurerAdapter
9.2)注入一會所需要的類
9.3)SpringSecurity5.0之后必須密碼加密
9.4)將數據庫查出的賬戶密碼交給SpringSecurity去判斷
9.5)配置HttpSecurity
這里只寫了主要代碼真正業務還需要判斷登陸成功跳轉頁面和登陸失敗跳轉頁面
可以訪問我前面針對HttpSecurity比較詳細的博客
https://www.cnblogs.com/fernfei/p/12185186.html
10)Controller

