shiro介绍
功能特点
Shiro 包含 10 个内容,如下图:
-
Authentication:身份认证/登录,验证用户是不是拥有相应的身份。
-
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某 个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限。
-
Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的。
-
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储。
-
Web Support:Web支持,可以非常容易的集成到 web 环境。
-
Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率。
-
Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去。
-
Testing:提供测试支持。
-
Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问。
-
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
运行原理
Shiro 运行原理图1(应用程序角度)如下:
-
Subject:主体,代表了当前“用户”。这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等。所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager。我们可以把 Subject 认为是一个门面,SecurityManager 才是实际的执行者。
-
SecurityManager:安全管理器。即所有与安全有关的操作都会与 SecurityManager 交互,且它管理着所有 Subject。可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,我们可以把它看成 DispatcherServlet 前端控制器。
-
Realm:域。Shiro 从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法,也需要从 Realm 得到用户相应的角色/权限进行验证用户是否能进行操作。我们可以把 Realm 看成 DataSource,即安全数据源。
Shiro 运行原理图2(Shiro 内部架构角度)如下:
-
Subject:主体,可以看到主体可以是任何与应用交互的“用户”。
-
SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher。它是 Shiro 的核心,所有具体的交互都通过 SecurityManager 进行控制。它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。
-
Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得 Shiro 默认的不好,我们可以自定义实现。其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了。
-
Authrizer:授权器,或者访问控制器。它用来决定主体是否有权限进行相应的操作,即控制着用户能访问应用中的哪些功能。
-
Realm:可以有1个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的。它可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等。
-
SessionManager:如果写过 Servlet 就应该知道 Session 的概念,Session 需要有人去管理它的生命周期,这个组件就是 SessionManager。而 Shiro 并不仅仅可以用在 Web 环境,也可以用在如普通的 JavaSE 环境。
-
SessionDAO:DAO 大家都用过,数据访问对象,用于会话的 CRUD。我们可以自定义 SessionDAO 的实现,控制 session 存储的位置。如通过 JDBC 写到数据库或通过 jedis 写入 redis 中。另外 SessionDAO 中可以使用 Cache 进行缓存,以提高性能。
-
CacheManager:缓存管理器。它来管理如用户、角色、权限等的缓存的。因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能。
-
Cryptography:密码模块,Shiro 提高了一些常见的加密组件用于如密码加密/解密的。
过滤器
当 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 是授权过滤器。
入门demo
废话不多说,上代码
表结构5张表
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 50712
Source Host : localhost:3306
Source Schema : shiro
Target Server Type : MySQL
Target Server Version : 50712
File Encoding : 65001
Date: 08/01/2020 13:40:44
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
`url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES (1, 'add', '');
INSERT INTO `permission` VALUES (2, 'delete', '');
INSERT INTO `permission` VALUES (3, 'edit', '');
INSERT INTO `permission` VALUES (4, 'query', '');
-- ----------------------------
-- Table structure for permission_role
-- ----------------------------
DROP TABLE IF EXISTS `permission_role`;
CREATE TABLE `permission_role` (
`rid` bigint(11) NOT NULL,
`pid` bigint(11) NOT NULL,
INDEX `idx_rid`(`rid`) USING BTREE,
INDEX `idx_pid`(`pid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of permission_role
-- ----------------------------
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);
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`rname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'admin');
INSERT INTO `role` VALUES (2, 'customer');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', '202cb962ac59075b964b07152d234b70');
INSERT INTO `user` VALUES (2, 'demo', '202cb962ac59075b964b07152d234b70');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`uid` bigint(11) NOT NULL,
`rid` bigint(11) NOT NULL,
INDEX `idx_uid`(`uid`) USING BTREE,
INDEX `idx_rid`(`rid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1);
INSERT INTO `user_role` VALUES (2, 2);
SET FOREIGN_KEY_CHECKS = 1;
application.yml
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
p6spy: false
username: root
password: 123456
url: jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useSSL=false
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
suffix: .ftl
template-loader-path: classpath:/templates
logging:
level:
com.wangtao.dao: error
mybatis-plus:
mapper-locations: classpath:mapper/*.xml,classpath:mapper/*/*.xml
实体类
User.java
package com.wangtao.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
public class User implements Serializable {
private Long id;
private String username;
private String password;
private Set<Role> roles = new HashSet<>();
}
Role.java
package com.wangtao.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@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<>();
}
Permission.java
package com.wangtao.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class Permission implements Serializable {
private Long id;
private String name;
private String url;
}
dao
UserDao.java
package com.wangtao.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wangtao.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserDao extends BaseMapper<User> {
/**
* 用户列表
* @return
*/
List<User> getList();
User findByUsername(@Param("username") String username);
}
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.wangtao.dao.UserDao">
<resultMap id="userMap" type="com.wangtao.entity.User">
<id property="id" column="uid" />
<result property="username" column="username"/>
<result property="password" column="password"/>
<collection property="roles" ofType="com.wangtao.entity.Role">
<id property="id" column="rid" />
<result property="name" column="rname" />
<collection property="permissions" ofType="com.wangtao.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.wangtao.entity.User">
SELECT u.*
FROM user u
</select>
<select id="findByUsername" resultMap="userMap">
SELECT
u.id uid,
u.username username,
u.PASSWORD password,
r.id rid,
r.rname 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
UserService.java
package com.wangtao.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wangtao.entity.User;
import java.util.List;
public interface UserService extends IService<User> {
List<User> getList();
User findByUsername(String username);
}
UserServiceImpl.java
package com.wangtao.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangtao.dao.UserDao;
import com.wangtao.entity.User;
import com.wangtao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
@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
UserController.java
package com.wangtao.controller;
import com.wangtao.entity.User;
import com.wangtao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@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")
@ResponseBody
public String index() {
User user = (User) SecurityUtils.getSubject().getPrincipal();
return "index="+user.getUsername();
}
/**
* 没有权限的回调接口
* @return
*/
@RequestMapping("unauthorized")
@ResponseBody
public String unauthorized() {
return "unauthorized";
}
/**
* 需要admin角色才能访问
* @return
*/
@RequestMapping("/admin")
// @RequiresRoles("/admin")
@ResponseBody
public String admin() {
return "admin success";
}
/**
* 需要修改权限才能访问
* @return
*/
@RequestMapping("/edit")
// @RequiresPermissions("edit")
@ResponseBody
public String edit() {
return "edit success";
}
@RequestMapping("/add")
// @RequiresPermissions("add")
@ResponseBody
public String add() {
return "add success";
}
/**
* 退出登录
* @return
*/
@RequestMapping("/logout")
@ResponseBody
public String logout() {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
subject.logout();
}
return "logout";
}
/**
* 登录接口
* @param username
* @param password
* @return
*/
@RequestMapping("/loginUser")
@ResponseBody
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配置
AuthRealm.java
package com.wangtao.shiro;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.wangtao.entity.Permission;
import com.wangtao.entity.Role;
import com.wangtao.entity.User;
import com.wangtao.service.UserService;
import org.apache.shiro.SecurityUtils;
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.session.Session;
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;
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.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);
//进行认证,将正确数据给shiro处理,第一个参数用户信息,第二个密码,第三个realm名
AuthenticationInfo authInfo = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
//清之前的授权信息
super.clearCachedAuthorizationInfo(authInfo.getPrincipals());
//登录信息放进session中
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("userSession", user);
return authInfo;
}
}
CredentialMatcher.java
package com.wangtao.shiro;
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;
public class CredentialMatcher extends SimpleCredentialsMatcher {
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String password = Encrypt.md5Hash(String.valueOf(usernamePasswordToken.getPassword()));
String dbPassword = (String) info.getCredentials();
return this.equals(password, dbPassword);
}
}
Encrypt.java
package com.wangtao.shiro;
import org.apache.shiro.crypto.hash.Md5Hash;
public class Encrypt {
/**
*单次MD5Hash
* @param password
* @return 加密后的密码
*/
public static String md5Hash(String password){
return new Md5Hash(password).toString();
}
/**
*MD5Hash+盐+多次散列运算
* @param password
* @return 加密后的密码
*/
public static String md5Hash(String password, String salt){
return new Md5Hash(password,salt,2).toString();
}
}
ShiroConfig.java
package com.wangtao.shiro;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilter(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("/user/add", "perms[add]");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/**", "user");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return bean;
}
/**
* 注入安全管理器
* @return
*/
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置realm
securityManager.setRealm(authRealm());
return securityManager;
}
/**
* 注入自定义的shiro 授权验证类
* @return
*/
@Bean
public AuthRealm authRealm(){
AuthRealm authRealm = new AuthRealm();
authRealm.setCredentialsMatcher(credentialMatcher());
return authRealm;
}
/**
* 注入自定义的密码加密校验类
* @return
*/
@Bean
public CredentialMatcher credentialMatcher(){
return new CredentialMatcher();
}
/**
* 开启shiro aop 注解支持
* 使用代理方式,所以需要开启代码支持
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
login.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>权限控制登陆系统</h1>
<form action="/login" method="post">
<span>用户名称</span><input type="text" name="username" /> <br>
<span>用户密码</span><input type="password" name="password" /> <br>
<input type="submit" value="登陆">
</form>
<#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>
运行效果截图
admin用户登录,拥有所有权限
换成demo用户登录
显示无权限
其他功能请自行探索,告辞