javascript
Spring Boot2 整合 Shiro ,两种方式全总结!
前言:在 Spring Boot 中做權(quán)限管理,一般來說,主流的方案是 Spring Security ,但是,僅僅從技術(shù)角度來說,也可以使用 Shiro。
文章目錄
- 一、Spring Security 和 Shiro 的比較
- 二、原生的整合
- 2.1. 創(chuàng)建一個 Spring Boot 項(xiàng)目
- 2.1. 加入 Shiro 相關(guān)的依賴
- 2.2. 完整pom
- 2.3. 自定義核心組件 Realm
- 2.4. 配置 Shiro
- 2.5. 配置登錄 Controller
- 三、測試驗(yàn)證
- 3.1. 首先訪問 /hello 接口
- 3.2. 然后調(diào)用 /doLogin 接口完成登錄
- 3.3. 再次訪問 /hello 接口
- 四、使用 Shiro Starter
- 4.1. 創(chuàng)建工程,和上面的一樣
- 4.2. pom
- 4.3. 創(chuàng)建 Realm
- 4.4. 配置 Shiro 基本信息
- 4.5. 配置 ShiroConfig
- 五、總結(jié)
今天gblfy就來和大家聊聊 Spring Boot 整合 Shiro 的話題!
一、Spring Security 和 Shiro 的比較
一般來說,Spring Security 和 Shiro 的比較如下:
| 是一個重量級的安全管理框架 | 則是一個輕量級的安全管理框架 |
| 概念復(fù)雜,配置繁瑣 | 概念簡單、配置簡單 |
| 功能強(qiáng)大 | 功能簡單 |
雖然 Shiro 功能簡單,但是也能滿足大部分的業(yè)務(wù)場景。所以在傳統(tǒng)的 SSM 項(xiàng)目中,一般來說,可以整合 Shiro。
在 Spring Boot 中,由于 Spring Boot 官方提供了大量的非常方便的開箱即用的 Starter ,當(dāng)然也提供了 Spring Security 的 Starter ,使得在 Spring Boot 中使用 Spring Security 變得更加容易,甚至只需要添加一個依賴就可以保護(hù)所有的接口,所以,如果是 Spring Boot 項(xiàng)目,一般選擇 Spring Security 。
這只是一個建議的組合,單純從技術(shù)上來說,無論怎么組合,都是沒有問題的。
在 Spring Boot 中整合 Shiro ,有兩種不同的方案:
第一種就是原封不動的,將 SSM 整合 Shiro 的配置用 Java 重寫一遍。
第二種就是使用 Shiro 官方提供的一個 Starter 來配置,但是,這個 Starter 并沒有簡化多少配置。
二、原生的整合
2.1. 創(chuàng)建一個 Spring Boot 項(xiàng)目
只需要添加 Web 依賴即可
2.1. 加入 Shiro 相關(guān)的依賴
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.4.0</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.0</version></dependency>2.2. 完整pom
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.4.0</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.0</version></dependency>2.3. 自定義核心組件 Realm
package com.gblfy.realm;import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection;/*** @author gblfy* @Description https://www.gblfy.com* @Date 2019/12/8 15:45*/ public class MyRealm extends AuthorizingRealm {@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {return null;}@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {String username = (String) token.getPrincipal();if (!"gblfy".equals(username)) {throw new UnknownAccountException("賬戶不存在!");}return new SimpleAuthenticationInfo(username, "123", getName());} }在 Realm 中實(shí)現(xiàn)簡單的認(rèn)證操作即可,不做授權(quán),授權(quán)的具體寫法和 SSM 中的 Shiro 一樣,不贅述。這里的認(rèn)證表示用戶名必須是 javaboy ,用戶密碼必須是 123 ,滿足這樣的條件,就能登錄成功!
2.4. 配置 Shiro
package com.gblfy.config;import com.gblfy.realm.MyRealm; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import java.util.LinkedHashMap; import java.util.Map;/*** @author gblfy* @Description https://www.gblfy.com* @Date 2019/12/8 15:45* <p>* 在這里進(jìn)行 Shiro 的配置* Shiro 的配置主要配置 3 個 Bean* <p>* 1. 首先需要提供一個 Realm 的實(shí)例* 2. 需要配置一個 SecurityManager,在 SecurityManager 中配置 Realm* 3. 配置一個 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路徑攔截規(guī)則等*/ @Configuration public class ShiroConfig {@BeanMyRealm myRealm() {return new MyRealm();}@BeanSecurityManager securityManager() {DefaultWebSecurityManager manager = new DefaultWebSecurityManager();manager.setRealm(myRealm());return manager;}@BeanShiroFilterFactoryBean shiroFilterFactoryBean() {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//指定 SecurityManagerbean.setSecurityManager(securityManager());//登錄頁面bean.setLoginUrl("/login");//登錄成功頁面bean.setSuccessUrl("/index");//訪問未獲授權(quán)路徑時跳轉(zhuǎn)的頁面bean.setUnauthorizedUrl("/unauthorizedurl");//配置路徑攔截規(guī)則,注意,要有序Map<String, String> map = new LinkedHashMap<>();map.put("/doLogin", "anon");map.put("/**", "authc");bean.setFilterChainDefinitionMap(map);return bean;} }在這里進(jìn)行 Shiro 的配置主要配置 3 個 Bean :
①首先需要提供一個 Realm 的實(shí)例。
②需要配置一個 SecurityManager,在 SecurityManager 中配置 Realm。
③配置一個 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路徑攔截規(guī)則等。
④配置登錄和測試接口。
其中,ShiroFilterFactoryBean 的配置稍微多一些,配置含義如下:
①setSecurityManager 表示指定 SecurityManager。
②setLoginUrl 表示指定登錄頁面。
③setSuccessUrl 表示指定登錄成功頁面。
④接下來的 Map 中配置了路徑攔截規(guī)則,注意,要有序。
2.5. 配置登錄 Controller
package com.gblfy.controller;import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController;/*** @author gblfy* @Description https://www.gblfy.com* @Date 2019/12/8 15:45*/ @RestController public class LoginController {/*** 登錄方法** @param username* @param password*/@PostMapping("/doLogin")public String doLogin(String username, String password) {Subject subject = SecurityUtils.getSubject();try {subject.login(new UsernamePasswordToken(username, password));return "登錄成功!";} catch (AuthenticationException e) {e.printStackTrace();return "登錄失敗!";}}/*** 測試方法** @return*/@GetMapping("/hello")public String helloWord() {return "helloWord";}/*** 統(tǒng)一攔截登錄頁面** @return*/@GetMapping("/login")public String login() {return "please login!";} }三、測試驗(yàn)證
測試時,首先訪問 /hello 接口,由于未登錄,所以會自動跳轉(zhuǎn)到 /login 接口
3.1. 首先訪問 /hello 接口
http://localhost:8080/hello3.2. 然后調(diào)用 /doLogin 接口完成登錄
http://localhost:8080/doLogin?username=gblfy&password=1233.3. 再次訪問 /hello 接口
就可以成功訪問了:
四、使用 Shiro Starter
上面這種配置方式實(shí)際上相當(dāng)于把 SSM 中的 XML 配置拿到 Spring Boot 中用 Java 代碼重新寫了一遍,除了這種方式之外,我們也可以直接使用 Shiro 官方提供的 Starter 。
4.1. 創(chuàng)建工程,和上面的一樣
4.2. pom
創(chuàng)建成功后,添加 shiro-spring-boot-web-starter ,這個依賴可以代替之前的 shiro-web 和 shiro-spring 兩個依賴,pom.xml 文件如下:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring-boot-web-starter</artifactId><version>1.4.0</version></dependency>4.3. 創(chuàng)建 Realm
這里的 Realm 和前面的一樣,我就不再贅述。
4.4. 配置 Shiro 基本信息
接下來在 application.properties 中配置 Shiro 的基本信息:
shiro:sessionManager:sessionIdCookieEnabled: truesessionIdUrlRewritingEnabled: trueunauthorizedUrl: /unauthorizedurlweb:enabled: truesuccessUrl: /indexloginUrl: /login# 第一行表示是否允許將sessionId 放到 cookie 中 # 第二行表示是否允許將 sessionId 放到 Url 地址攔中 # 第三行表示訪問未獲授權(quán)的頁面時,默認(rèn)的跳轉(zhuǎn)路徑 # 第四行表示開啟 shiro # 第五行表示登錄成功的跳轉(zhuǎn)頁面 # 第六行表示登錄頁面4.5. 配置 ShiroConfig
package com.gblfy.config;import com.gblfy.realm.MyRealm; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;/*** @author gblfy* @Description https://www.gblfy.com* @Date 2019/12/8 15:4** 在這里進(jìn)行 Shiro 的配置* Shiro 的配置主要配置 3 個 Bean 。** 1. 首先需要提供一個 Realm 的實(shí)例* 2. 需要配置一個 SecurityManager,在 SecurityManager 中配置 Realm* 3. 配置一個 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路徑攔截規(guī)則等*/ @Configuration public class ShiroConfig {@BeanMyRealm myRealm() {return new MyRealm();}@BeanDefaultWebSecurityManager securityManager() {DefaultWebSecurityManager manager = new DefaultWebSecurityManager();manager.setRealm(myRealm());return manager;}@BeanShiroFilterChainDefinition shiroFilterChainDefinition() {DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();definition.addPathDefinition("/doLogin", "anon");definition.addPathDefinition("/**", "authc");return definition;} }這里的配置和前面的比較像,但是不再需要 ShiroFilterFactoryBean 實(shí)例了,替代它的是 ShiroFilterChainDefinition ,在這里定義 Shiro 的路徑匹配規(guī)則即可。
這里定義完之后,接下來的登錄接口定義以及測試方法都和前面的一致,我就不再贅述了。大家可以參考上文。
五、總結(jié)
本文主要向大家介紹了 Spring Boot 整合 Shiro 的兩種方式,一種是傳統(tǒng)方式的 Java 版,另一種則是使用 Shiro 官方提供的 Starter,兩種方式,不知道大家有沒有學(xué)會呢?
本文案例,我已經(jīng)上傳到 碼云,歡迎大家 star:
https://gitee.com/gb_90/SpringBoot2_Practical_Column
總結(jié)
以上是生活随笔為你收集整理的Spring Boot2 整合 Shiro ,两种方式全总结!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (需求实战_进阶_03)SSM集成Rab
- 下一篇: Flowable 生成工作流图片时, 不