在 Spring Boot 中做權限管理,一般來說,主流的方案是 Spring Security ,但是,僅僅從技術角度來說,也可以使用 Shiro。
今天松哥就來和大家聊聊 Spring Boot 整合 Shiro 的話題!
一般來說,Spring Security 和 Shiro 的比較如下:
Spring Security 是一個重量級的安全管理框架;Shiro 則是一個輕量級的安全管理框架
Spring Security 概念複雜,配置繁瑣;Shiro 概念簡單、配置簡單
Spring Security 功能強大;Shiro 功能簡單
…
雖然 Shiro 功能簡單,但是也能滿足大部分的業務場景。所以在傳統的 SSM 項目中,一般來說,可以整合 Shiro。
在 Spring Boot 中,由於 Spring Boot 官方提供了大量的非常方便的開箱即用的 Starter ,當然也提供了 Spring Security 的 Starter ,使得在 Spring Boot 中使用 Spring Security 變得更加容易,甚至只需要添加一個依賴就可以保護所有的接口,所以,如果是 Spring Boot 項目,一般選擇 Spring Security 。
這只是一個建議的組合,單純從技術上來說,無論怎麼組合,都是沒有問題的。
在 Spring Boot 中整合 Shiro ,有兩種不同的方案:
第一種就是原封不動的,將 SSM 整合 Shiro 的配置用 Java 重寫一遍。
第二種就是使用 Shiro 官方提供的一個 Starter 來配置,但是,這個 Starter 並沒有簡化多少配置。
原生的整合
創建項目創建一個 Spring Boot 項目,只需要添加 Web 依賴即可:
項目創建成功後,加入 Shiro 相關的依賴,完整的 pom.xml 文件中的依賴如下:
<dependencies><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></dependencies>
創建 Realm
接下來我們來自定義核心組件 Realm:
public class MyRealm extends AuthorizingRealm {@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); if (!"javaboy".equals(username)) { throw new UnknownAccountException("帳戶不存在!"); } return new SimpleAuthenticationInfo(username, "123", getName()); }}
在 Realm 中實現簡單的認證操作即可,不做授權,授權的具體寫法和 SSM 中的 Shiro 一樣,不贅述。這裡的認證表示用戶名必須是 javaboy ,用戶密碼必須是 123 ,滿足這樣的條件,就能登錄成功!
配置 Shiro
接下來進行 Shiro 的配置:
@Configurationpublic class ShiroConfig {@Bean MyRealm myRealm() { return new MyRealm(); } @Bean SecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myRealm()); return manager; } @Bean ShiroFilterFactoryBean shiroFilterFactoryBean() { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager()); bean.setLoginUrl("/login"); bean.setSuccessUrl("/index"); bean.setUnauthorizedUrl("/unauthorizedurl"); Map<String, String> map = new LinkedHashMap<>(); map.put("/doLogin", "anon"); map.put("/**", "authc"); bean.setFilterChainDefinitionMap(map); return bean; }}
在這裡進行 Shiro 的配置主要配置 3 個 Bean :
首先需要提供一個 Realm 的實例。
需要配置一個 SecurityManager,在 SecurityManager 中配置 Realm。
配置一個 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路徑攔截規則等。
配置登錄和測試接口。
其中,ShiroFilterFactoryBean 的配置稍微多一些,配置含義如下:
setSecurityManager 表示指定 SecurityManager。
setLoginUrl 表示指定登錄頁面。
setSuccessUrl 表示指定登錄成功頁面。
接下來的 Map 中配置了路徑攔截規則,注意,要有序。
這些東西都配置完成後,接下來配置登錄 Controller:
@RestControllerpublic class LoginController {@PostMapping("/doLogin") public void doLogin(String username, String password) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password)); System.out.println("登錄成功!"); } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("登錄失敗!"); } } @GetMapping("/hello") public String hello() { return "hello"; } @GetMapping("/login") public String login() { return "please login!"; }}
測試時,首先訪問 /hello 接口,由於未登錄,所以會自動跳轉到 /login 接口:
然後調用 /doLogin 接口完成登錄:
再次訪問 /hello 接口,就可以成功訪問了:
使用 Shiro Starter
上面這種配置方式實際上相當於把 SSM 中的 XML 配置拿到 Spring Boot 中用 Java 代碼重新寫了一遍,除了這種方式之外,我們也可以直接使用 Shiro 官方提供的 Starter 。
創建工程,和上面的一樣建成功後,添加 shiro-spring-boot-web-starter ,這個依賴可以代替之前的 shiro-web 和 shiro-spring 兩個依賴,pom.xml 文件如下:
<dependencies><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></dependencies>
創建 Realm
這裡的 Realm 和前面的一樣,我就不再贅述。
配置 Shiro 基本信息
接下來在 application.properties 中配置 Shiro 的基本信息:
shiro.sessionManager.sessionIdCookieEnabled=trueshiro.sessionManager.sessionIdUrlRewritingEnabled=trueshiro.unauthorizedUrl=/unauthorizedurlshiro.web.enabled=trueshiro.successUrl=/indexshiro.loginUrl=/login
配置解釋:
第一行表示是否允許將sessionId 放到 cookie 中
第二行表示是否允許將 sessionId 放到 Url 地址攔中
第三行表示訪問未獲授權的頁面時,默認的跳轉路徑
第四行表示開啟 shiro
第五行表示登錄成功的跳轉頁面
第六行表示登錄頁面
配置 ShiroConfig
@Configurationpublic class ShiroConfig {@Bean MyRealm myRealm() { return new MyRealm(); } @Bean DefaultWebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(myRealm()); return manager; } @Bean ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition(); definition.addPathDefinition("/doLogin", "anon"); definition.addPathDefinition("/**", "authc"); return definition; }}
這裡的配置和前面的比較像,但是不再需要 ShiroFilterFactoryBean 實例了,替代它的是 ShiroFilterChainDefinition ,在這裡定義 Shiro 的路徑匹配規則即可。
這裡定義完之後,接下來的登錄接口定義以及測試方法都和前面的一致,我就不再贅述了。大家可以參考上文。
總結
本文主要向大家介紹了 Spring Boot 整合 Shiro 的兩種方式,一種是傳統方式的 Java 版,另一種則是使用 Shiro 官方提供的 Starter,兩種方式,不知道大家有沒有學會呢?
本文案例,我已經上傳到 GitHub ,歡迎大家 star:https://github.com/lenve/javaboy-code-samples
關於本文,有問題歡迎留言討論。
原文:https://blog.csdn.net/u012702547/article/details/91413078