一.前言
基於上一篇springBoot2.0 配置 mybatis+mybatisPlus+redis
這一篇加入shiro實現權限管理
二.shiro介紹
2.1 功能特點
Shiro 包含 10 個內容,如下圖:
1) Authentication:身份認證/登錄,驗證用戶是不是擁有相應的身份。
2) Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能做事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具有某個權限。
3) Session Manager:會話管理,即用戶登錄后就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通 JavaSE 環境的,也可以是如 Web 環境的。
4) Cryptography:加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲。
5) Web Support:Web支持,可以非常容易的集成到 web 環境。
6) Caching:緩存,比如用戶登錄后,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率。
7) Concurrency:shiro 支持多線程應用的並發驗證,即如在一個線程中開啟另一個線程,能把權限自動傳播過去。
8) Testing:提供測試支持。
9) Run As:允許一個用戶假裝為另一個用戶(如果他們允許)的身份進行訪問。
10) Remember Me:記住我,這個是非常常見的功能,即一次登錄后,下次再來的話不用登錄了。
2.2 運行原理
Shiro 運行原理圖1(應用程序角度)如下:
1) Subject:主體,代表了當前“用戶”。這個用戶不一定是一個具體的人,與當前應用交互的任何東西都是 Subject,如網絡爬蟲,機器人等。所有 Subject 都綁定到 SecurityManager,與 Subject 的所有交互都會委托給 SecurityManager。我們可以把 Subject 認為是一個門面,SecurityManager 才是實際的執行者。
2) SecurityManager:安全管理器。即所有與安全有關的操作都會與 SecurityManager 交互,且它管理着所有 Subject。可以看出它是 Shiro 的核心,它負責與后邊介紹的其他組件進行交互,如果學習過 SpringMVC,我們可以把它看成 DispatcherServlet 前端控制器。
3) Realm:域。Shiro 從 Realm 獲取安全數據(如用戶、角色、權限),就是說 SecurityManager 要驗證用戶身份,那么它需要從 Realm 獲取相應的用戶進行比較以確定用戶身份是否合法,也需要從 Realm 得到用戶相應的角色/權限進行驗證用戶是否能進行操作。我們可以把 Realm 看成 DataSource,即安全數據源。
Shiro 運行原理圖2(Shiro 內部架構角度)如下:
1) Subject:主體,可以看到主體可以是任何與應用交互的“用戶”。
2) SecurityManager:相當於 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher。它是 Shiro 的核心,所有具體的交互都通過 SecurityManager 進行控制。它管理着所有 Subject、且負責進行認證和授權、及會話、緩存的管理。
3) Authenticator:認證器,負責主體認證的,這是一個擴展點,如果用戶覺得 Shiro 默認的不好,我們可以自定義實現。其需要認證策略(Authentication Strategy),即什么情況下算用戶認證通過了。
4) Authrizer:授權器,或者訪問控制器。它用來決定主體是否有權限進行相應的操作,即控制着用戶能訪問應用中的哪些功能。
5) Realm:可以有1個或多個 Realm,可以認為是安全實體數據源,即用於獲取安全實體的。它可以是 JDBC 實現,也可以是 LDAP 實現,或者內存實現等。
6) SessionManager:如果寫過 Servlet 就應該知道 Session 的概念,Session 需要有人去管理它的生命周期,這個組件就是 SessionManager。而 Shiro 並不僅僅可以用在 Web 環境,也可以用在如普通的 JavaSE 環境。
7) SessionDAO:DAO 大家都用過,數據訪問對象,用於會話的 CRUD。我們可以自定義 SessionDAO 的實現,控制 session 存儲的位置。如通過 JDBC 寫到數據庫或通過 jedis 寫入 redis 中。另外 SessionDAO 中可以使用 Cache 進行緩存,以提高性能。
8) CacheManager:緩存管理器。它來管理如用戶、角色、權限等的緩存的。因為這些數據基本上很少去改變,放到緩存中后可以提高訪問的性能。
9) Cryptography:密碼模塊,Shiro 提高了一些常見的加密組件用於如密碼加密/解密的。
2.3 過濾器
當 Shiro 被運用到 web 項目時,Shiro 會自動創建一些默認的過濾器對客戶端請求進行過濾。以下是 Shiro 提供的過濾器:
/admins/**=anon # 表示該 uri 可以匿名訪問
/admins/**=auth # 表示該 uri 需要認證才能訪問
/admins/**=authcBasic # 表示該 uri 需要 httpBasic 認證
/admins/**=perms[user:add:*] # 表示該 uri 需要認證用戶擁有 user:add:* 權限才能訪問
/admins/**=port[8081] # 表示該 uri 需要使用 8081 端口
/admins/**=rest[user] # 相當於 /admins/**=perms[user:method],其中,method 表示 get、post、delete 等
/admins/**=roles[admin] # 表示該 uri 需要認證用戶擁有 admin 角色才能訪問
/admins/**=ssl # 表示該 uri 需要使用 https 協議
/admins/**=user # 表示該 uri 需要認證或通過記住我認證才能訪問
/logout=logout # 表示注銷,可以當作固定配置
anon,authcBasic,auchc,user 是認證過濾器。
perms,roles,ssl,rest,port 是授權過濾器。
三.表結構
-- 權限表 -- CREATE TABLE permission ( pid BIGINT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL DEFAULT '', url VARCHAR(255) DEFAULT '', PRIMARY KEY (pid) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; INSERT INTO permission VALUES ('1', 'add', ''); INSERT INTO permission VALUES ('2', 'delete', ''); INSERT INTO permission VALUES ('3', 'edit', ''); INSERT INTO permission VALUES ('4', 'query', ''); -- 用戶表 -- CREATE TABLE user( uid BIGINT(11) NOT NULL AUTO_INCREMENT, username VARCHAR(255) NOT NULL DEFAULT '', password VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (uid) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; INSERT INTO user VALUES ('1', 'admin', '123'); INSERT INTO user VALUES ('2', 'demo', '123'); -- 角色表 -- CREATE TABLE role( rid BIGINT(11) NOT NULL AUTO_INCREMENT, rname VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (rid) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; INSERT INTO role VALUES ('1', 'admin'); INSERT INTO role VALUES ('2', 'customer'); -- 權限角色關系表 -- CREATE TABLE permission_role ( rid BIGINT(11) NOT NULL , pid BIGINT(11) NOT NULL , KEY idx_rid (rid), KEY idx_pid (pid) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; INSERT INTO permission_role VALUES ('1', '1'); INSERT INTO permission_role VALUES ('1', '2'); INSERT INTO permission_role VALUES ('1', '3'); INSERT INTO permission_role VALUES ('1', '4'); INSERT INTO permission_role VALUES ('2', '1'); INSERT INTO permission_role VALUES ('2', '4'); -- 用戶角色關系表 -- CREATE TABLE user_role ( uid BIGINT(11) NOT NULL , rid BIGINT(11) NOT NULL , KEY idx_uid (uid), KEY idx_rid (rid) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; INSERT INTO user_role VALUES (1, 1); INSERT INTO user_role VALUES (2, 2);
四.entity
1.Permission.java
package com.example.demo2.entity; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * @author sssr * @version 1.0 * @Description:權限 * @date 2019/2/17 */ @Getter @Setter public class Permission implements Serializable { private Long id; private String name; private String url; }
2.Role.java
package com.example.demo2.entity; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * @author ssr * @version 1.0 * @Description:角色 * @date 2019/2/17 */ @Getter @Setter public class Role implements Serializable { private Long id; private String name; private Set<Permission> permissions = new HashSet<>(); private Set<User> users = new HashSet<>(); }
3.User.java
package com.example.demo2.entity; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * @author sssr * @version 1.0 * @Description:用戶 * @date 2019/2/16 */ @Getter @Setter public class User implements Serializable { private Long id; private String username; private String password; private Set<Role> roles = new HashSet<>(); }
五.dao
1.UserDao.javapackage com.example.demo2.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo2.entity.User; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/16 */ @Repository public interface UserDao extends BaseMapper<User> { /** * 用戶列表 * @return */ List<User> getList(); User findByUsername(@Param("username") String username); }
2.UserDao.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.demo2.dao.UserDao"> <resultMap id="userMap" type="com.example.demo2.entity.User"> <id property="id" column="uid" /> <collection property="roles" ofType="com.example.demo2.entity.Role"> <id property="id" column="rid" /> <result property="name" column="rname" /> <collection property="permissions" ofType="com.example.demo2.entity.Permission"> <id property="id" column="pid" /> <result property="name" column="pname"/> <result property="url" column="url" /> </collection> </collection> </resultMap> <select id="getList" resultType="com.example.demo2.entity.User"> SELECT u.* FROM user u </select> <select id="findByUsername" resultMap="userMap"> SELECT u.id uid,u.username,u.password, r.id rid,r.name rname, p.id pid,p.name pname,p.url FROM user u INNER JOIN user_role ur on ur.uid = u.id INNER JOIN role r on r.id = ur.rid INNER JOIN permission_role pr on pr.rid = r.id INNER JOIN permission p on pr.pid = p.id WHERE u.username = #{username} </select> </mapper>
六.Service
1.UserService.java
package com.example.demo2.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.demo2.entity.User; import java.util.List; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/16 */ public interface UserService extends IService<User> { List<User> getList(); User findByUsername(String username); }
2.UserServiceImpl.java
package com.example.demo2.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo2.dao.UserDao; import com.example.demo2.entity.User; import com.example.demo2.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/16 */ @Service public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService { @Autowired private UserDao userDao; /** (non-Javadoc) * @value: 在redis中 保存緩存在以user命名的集合中 * @key : user集合中的關鍵字,注意字符串要以單引號括住 '',變量前綴加#號,如#userId */ @Override @Cacheable(value="user",key="'list'") public List<User> getList() { return userDao.getList(); } @Override @Cacheable(value="user",key="'userList_'+#username") public User findByUsername(String username) { return userDao.findByUsername(username); } }
七.Controller
1.UserController.java
package com.example.demo2.controller; import com.example.demo2.entity.User; import com.example.demo2.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/16 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/list") public List<User> getUserList(){ return userService.getList(); } @RequestMapping("/login") public String login() { return "login"; } @RequestMapping("/index") public String index() { User user = (User) SecurityUtils.getSubject().getPrincipal(); return "index="+user.getUsername(); } /** * 沒有權限的回調接口 * @return */ @RequestMapping("unauthorized") public String unauthorized() { return "unauthorized"; } /** * 需要admin角色才能訪問 * @return */ @RequestMapping("/admin") @RequiresRoles("/admin") public String admin() { return "admin success"; } /** * 需要修改權限才能訪問 * @return */ @RequestMapping("/edit") @RequiresPermissions("edit") public String edit() { return "edit success"; } /** * 退出登錄 * @return */ @RequestMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); if (subject != null) { subject.logout(); } return "logout"; } /** * 登錄接口 * @param username * @param password * @return */ @RequestMapping("/loginUser") public String loginUser(@RequestParam("username") String username, @RequestParam("password") String password) { UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); User user = (User) subject.getPrincipal(); return "loginSuccess"; } catch (Exception e) { return "loginError"; } } }
八.pom.xml 加入 shiro包
<!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency>
九.shiro配置
1.AuthRealm.java
package com.example.demo2.config; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.example.demo2.entity.Permission; import com.example.demo2.entity.Role; import com.example.demo2.entity.User; import com.example.demo2.service.UserService; import org.apache.shiro.authc.*; 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.context.annotation.Lazy; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/17 */ public class AuthRealm extends AuthorizingRealm { /** * @Lazy 延遲注入,不然redis注解會因為注入順序問題失效 */ @Autowired @Lazy private UserService userService; /** * 授權 * @param principals * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next(); List<String> permissionList = new ArrayList<>(); List<String> roleNameList = new ArrayList<>(); Set<Role> roleSet = user.getRoles(); if (CollectionUtils.isNotEmpty(roleSet)) { for(Role role : roleSet) { roleNameList.add(role.getName()); Set<Permission> permissionSet = role.getPermissions(); if (CollectionUtils.isNotEmpty(permissionSet)) { for (Permission permission : permissionSet) { permissionList.add(permission.getName()); } } } } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addStringPermissions(permissionList); info.addRoles(roleNameList); return info; } /** * 認證登錄 * @param token * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); User user = userService.findByUsername(username); return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName()); } }
2.CredentialMatcher.java
package com.example.demo2.config; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/17 */ public class CredentialMatcher extends SimpleCredentialsMatcher { @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String password = new String(usernamePasswordToken.getPassword()); String dbPassword = (String) info.getCredentials(); return this.equals(password, dbPassword); } }
3.ShiroConfig.java
package com.example.demo2.config; import org.apache.shiro.cache.MemoryConstrainedCacheManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; /** * @author sssr * @version 1.0 * @Description: * @date 2019/2/17 */ @Configuration public class ShiroConfig { @Bean("shiroFilter") public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(manager); //登錄接口 bean.setLoginUrl("/user/login"); //登錄成功跳轉頁面 bean.setSuccessUrl("/user/index"); //沒有權限跳轉的頁面 bean.setUnauthorizedUrl("/user/unauthorized"); LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/user/index", "authc"); filterChainDefinitionMap.put("/user/login", "anon"); filterChainDefinitionMap.put("/user/loginUser", "anon"); filterChainDefinitionMap.put("/user/admin", "roles[admin]"); filterChainDefinitionMap.put("/user/edit", "perms[edit]"); filterChainDefinitionMap.put("/druid/**", "anon"); filterChainDefinitionMap.put("/**", "user"); bean.setFilterChainDefinitionMap(filterChainDefinitionMap); return bean; } @Bean("securityManager") public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(authRealm); return manager; } @Bean("authRealm") public AuthRealm authRealm(@Qualifier("credentialMatcher") CredentialMatcher matcher) { AuthRealm authRealm = new AuthRealm(); authRealm.setCacheManager(new MemoryConstrainedCacheManager()); authRealm.setCredentialsMatcher(matcher); return authRealm; } @Bean("credentialMatcher") public CredentialMatcher credentialMatcher() { return new CredentialMatcher(); } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } @Bean public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); creator.setProxyTargetClass(true); return creator; } }
十.運行效果
1.打開地址會自動跳轉到登錄頁面
2.登錄成功
3.訪問user/edit接口,沒有權限時跳轉到沒有權限頁面
4.訪問user/index,可以正常訪問,因為沒有做權限控制
5.退出登錄