一.前言html
基於上一篇springBoot2.0 配置 mybatis+mybatisPlus+redis前端
這一篇加入shiro實現權限管理java
二.shiro介紹web
2.1 功能特色redis
Shiro 包含 10 個內容,以下圖:spring
1) Authentication:身份認證/登陸,驗證用戶是否是擁有相應的身份。數據庫
2) Authorization:受權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能作事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具備某個權限。apache
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.退出登陸