用戶權限管理一般是對用戶頁面、按鈕的訪問權限管理。Shiro框架是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和會話管理,對於Shiro的介紹這里就不多說。本篇博客主要是了解Shiro的基礎使用方法,在權限管理系統中集成Shiro實現登錄、url和頁面按鈕的訪問控制。
一、引入依賴
使用SpringBoot集成Shiro時,在pom.xml中可以引入shiro-spring-boot-web-starter。由於使用的是thymeleaf框架,thymeleaf與Shiro結合需要 引入thymeleaf-extras-shiro。
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.4.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro --> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
二、增加Shiro配置
有哪些url是需要攔截的,哪些是不需要攔截的,登錄頁面、登錄成功頁面的url、自定義的Realm等這些信息需要設置到Shiro中,所以創建Configuration文件ShiroConfig。

package com.example.config; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { @Bean("shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); //攔截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); // 配置不會被攔截的鏈接 順序判斷 filterChainDefinitionMap.put("/static/**", "anon"); //配置退出 過濾器,其中的具體的退出代碼Shiro已經替我們實現了 filterChainDefinitionMap.put("/logout", "logout"); //<!-- 過濾鏈定義,從上向下順序執行,一般將/**放在最為下邊 -->:這是一個坑呢,一不小心代碼就不好使了; //<!-- authc:所有url都必須認證通過才可以訪問; anon:所有url都都可以匿名訪問--> filterChainDefinitionMap.put("/**", "authc"); // 如果不設置默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 shiroFilterFactoryBean.setLoginUrl("/login"); // 登錄成功后要跳轉的鏈接 shiroFilterFactoryBean.setSuccessUrl("/index"); //未授權界面; shiroFilterFactoryBean.setUnauthorizedUrl("/403"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } @Bean(name="defaultWebSecurityManager") //創建DefaultWebSecurityManager public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")MyShiroRealm userRealm){ DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); defaultWebSecurityManager.setRealm(userRealm); return defaultWebSecurityManager; } //創建Realm @Bean(name="userRealm") public MyShiroRealm getUserRealm(){ return new MyShiroRealm(); } @Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); } }
ShiroDialect這個bean對象是在thymeleaf與Shiro結合,前端html訪問Shiro時使用。
三、自定義Realm
在自定義的Realm中繼承了AuthorizingRealm抽象類,重寫了兩個方法:doGetAuthorizationInfo和doGetAuthenticationInfo。doGetAuthorizationInfo主要是用來處理權限配置,doGetAuthenticationInfo主要處理身份認證。這里在doGetAuthorizationInfo中,將role表的id和permission表的code分別設置到SimpleAuthorizationInfo對象中的role和permission中。還有一個地方需要注意:@Component("authorizer"),剛開始我沒設置,但報錯提示需要一個authorizer的bean,查看AuthorizingRealm可以發現它implements了Authorizer,所以在自定義的realm上添加@Component("authorizer")就可以了。

package com.example.config; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.example.pojo.Permission; import com.example.pojo.Role; import com.example.pojo.User; import com.example.service.RoleService; import com.example.service.UserService; @Component("authorizer") public class MyShiroRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private RoleService roleService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("權限配置-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); User user = (User)principals.getPrimaryPrincipal(); System.out.println("User:"+user.toString()+" roles count:"+user.getRoles().size()); for(Role role:user.getRoles()){ authorizationInfo.addRole(role.getId()); role=roleService.getRoleById(role.getId()); System.out.println("Role:"+role.toString()); for(Permission p:role.getPermissions()){ System.out.println("Permission:"+p.toString()); authorizationInfo.addStringPermission(p.getCode()); } } System.out.println("權限配置-->authorizationInfo"+authorizationInfo.toString()); return authorizationInfo; } /*主要是用來進行身份認證的,也就是說驗證用戶輸入的賬號和密碼是否正確。*/ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); //獲取用戶的輸入的賬號. String username = (String)token.getPrincipal(); System.out.println(token.getCredentials()); //通過username從數據庫中查找 User對象,如果找到,沒找到. //實際項目中,這里可以根據實際情況做緩存,如果不做,Shiro自己也是有時間間隔機制,2分鍾內不會重復執行該方法 User user = userService.getUserById(username); System.out.println("----->>userInfo="+user); if(user == null){ return null; } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user, //用戶名 "123456", //密碼 getName() //realm name ); return authenticationInfo; } }
四、登錄認證
1.登錄頁面
這里做了一個非常丑的登錄頁面,主要是自己懶,不想在網上復制粘貼找登錄頁面了。

<!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="format-detection" content="telephone=no"> </head> <form action="/login" method="post"> <label>用戶名:</label><input type="text" name="id" id="id" ><br> <label >密碼:</label><input type="text" name="pwd" id="pwd" ><br> <button type="submit">登錄</button><button type="reset">取消</button> </form> </body> </html>
2.處理登錄請求
在LoginController中通過登錄名、密碼獲取到token實現登錄。

package com.example.controller; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController { //退出的時候是get請求,主要是用於退出 @RequestMapping(value = "/login",method = RequestMethod.GET) public String login(){ return "login"; } //post登錄 @RequestMapping(value = "/login",method = RequestMethod.POST) public String login(Model model,String id,String pwd){ //添加用戶認證信息 Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken( id, "123456"); try { subject.login(usernamePasswordToken); return "home"; } catch (UnknownAccountException e) { //用戶名不存在 model.addAttribute("msg","用戶名不存在"); return "login"; }catch (IncorrectCredentialsException e) { //密碼錯誤 model.addAttribute("msg","密碼錯誤"); return "login"; } } @RequestMapping(value = "/index") public String index(){ return "home"; } }
五、Controller層訪問控制
1.首先來數據庫的數據,兩張圖是用戶角色、和角色權限的數據。
2.設置權限
這里在用戶頁面點擊編輯按鈕時設置需要有id=002的角色,在點擊選擇角色按鈕時需要有code=002的權限。
@RequestMapping(value = "/edit",method = RequestMethod.GET) @RequiresRoles("002")//權限管理; public String editGet(Model model,@RequestParam(value="id") String id) { model.addAttribute("id", id); return "/user/edit"; }
@RequestMapping(value = "/selrole",method = RequestMethod.GET) @RequiresPermissions("002")//權限管理; public String selctRole(Model model,@RequestParam("id") String id,@RequestParam("type") Integer type) { model.addAttribute("id",id); model.addAttribute("type", type); return "/user/selrole"; }
當使用用戶001登錄時,點擊編輯,彈出框如下,提示沒有002的角色
點擊選擇角色按鈕時提示沒有002的權限。
當使用用戶002登錄時,點擊編輯按鈕,顯示正常,點擊選擇角色也是提示沒002的權限,因為權限只有001。
六、前端頁面層訪問控制
有時為了不想像上面那樣彈出錯誤頁面,需要在按鈕顯示上進行不可見,這樣用戶也不會點擊到。前面已經引入了依賴並配置了bean,這里測試下在html中使用shiro。
1.首先設置html標簽引入shiro
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
2.控制按鈕可見
這里使用shiro:hasAnyRoles="002,003"判斷用戶角色是否是002或003,是則顯示不是則不顯示。
<div class="layui-inline"> <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-normal newsAdd_btn" onclick="addUser('')">添加用戶</a> </div> <div class="layui-inline"> <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-danger batchDel" onclick="getDatas();">批量刪除</a> </div>
當001用戶登錄時,添加用戶、批量刪除按鈕都不顯示,只顯示查詢按鈕。
當002用戶登錄時,添加用戶、批量刪除按鈕都顯示
七、小結
這里只是實現了Shiro的簡單的功能,Shiro還有很多很強大的功能,比如session管理等,而且目前權限管理模塊還有很多需要優化的功能,左側導航欄的動態加載和權限控制、Shiro與Redis結合實現session共享、Shiro與Cas結合實現單點登錄等。后續可以把項目做為開源項目,慢慢完善集成更多模塊例如:Swagger2、Redis、Druid、RabbitMQ等供初學者參考。