dome地址:GitHub - tancheng250/SpringBoot-Shiro-Mybatis-: 可实现SpringBoot+Shiro+Mybatis的整合操作 实现了授权、认证、加密、注册、登录等操作喜欢给个收藏
1.导入pom依赖
<!-- shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.0</version>
</dependency>
<!-- mysql8.0 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid的starter自动配置(包含了druid的jar)-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.创建表结构
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80023
Source Host : localhost:3306
Source Schema : shiro
Target Server Type : MySQL
Target Server Version : 80023
File Encoding : 65001
Date: 11/09/2021 13:22:46
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for perm
-- ----------------------------
DROP TABLE IF EXISTS `perm`;
CREATE TABLE `perm` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`pName` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`pUrl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of perm
-- ----------------------------
INSERT INTO `perm` VALUES (1, 'user:select', NULL);
INSERT INTO `perm` VALUES (2, 'user:update', NULL);
INSERT INTO `perm` VALUES (3, 'user:insert', NULL);
INSERT INTO `perm` VALUES (4, 'user:delete', NULL);
INSERT INTO `perm` VALUES (5, 'user:load', NULL);
INSERT INTO `perm` VALUES (6, 'user:export', NULL);
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`rid` int(0) NOT NULL AUTO_INCREMENT,
`rname` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`rid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'admin');
INSERT INTO `role` VALUES (2, 'user');
INSERT INTO `role` VALUES (3, 'guest');
-- ----------------------------
-- Table structure for role_perm
-- ----------------------------
DROP TABLE IF EXISTS `role_perm`;
CREATE TABLE `role_perm` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`permID` int(0) DEFAULT NULL,
`roleID` int(0) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role_perm
-- ----------------------------
INSERT INTO `role_perm` VALUES (1, 1, 1);
INSERT INTO `role_perm` VALUES (2, 2, 1);
INSERT INTO `role_perm` VALUES (3, 3, 1);
INSERT INTO `role_perm` VALUES (4, 4, 1);
INSERT INTO `role_perm` VALUES (5, 5, 1);
INSERT INTO `role_perm` VALUES (6, 6, 1);
INSERT INTO `role_perm` VALUES (7, 1, 2);
INSERT INTO `role_perm` VALUES (8, 5, 2);
INSERT INTO `role_perm` VALUES (9, 6, 2);
INSERT INTO `role_perm` VALUES (10, 1, 3);
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', '28a62ea2dd309e68648b5bb9c596e1cf', 'b3f5c67792fc2f9118f70b7c1d59df61');
INSERT INTO `user` VALUES (2, 'tancheng', '53d3d0648051d2b07adf4f7bde3a4f2c', 'e7097dac4dc8e19d58d264b92fe1885d');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`userID` int(0) DEFAULT NULL,
`roleID` int(0) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES (1, 1, 1);
INSERT INTO `user_role` VALUES (2, 1, 2);
INSERT INTO `user_role` VALUES (3, 1, 3);
INSERT INTO `user_role` VALUES (4, 2, 2);
INSERT INTO `user_role` VALUES (5, 2, 3);
SET FOREIGN_KEY_CHECKS = 1;
3.自定义realm
package com.tc.shiro.Realm;
import com.tc.dao.UserMapper;
import com.tc.pojo.User;
import com.tc.service.userService;
import lombok.extern.slf4j.Slf4j;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Arrays;
import java.util.Set;
/**
* @author 谭铖
* @date 2021/9/7 19:19
*/
@Component
@Slf4j
public class LoginRealm extends AuthorizingRealm {
@Autowired
private userService userService;
/**
* 授权
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 获取对象用户名
String primaryPrincipal = (String) principals.getPrimaryPrincipal();
System.out.println("权限授权用户:"+primaryPrincipal);
User login = this.userService.login(primaryPrincipal);
if (!ObjectUtils.isEmpty(login)) {
// 查询用户角色
Set<String> perms = this.userService.getPremByUserId(login.getId());
System.out.println("角色权限:"+perms);
// 查询角色权限(如果不使用set集合会出现重复权限 set可以去重 当然底层也是set)
Set<String> roles = this.userService.getRolesByUserId(login.getId());
System.out.println("用户角色:"+roles);
// 创建授权器
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 传入授权角色
simpleAuthorizationInfo.setRoles(roles);
// 传入授权角色操作
simpleAuthorizationInfo.setStringPermissions(perms);
// 返回
return simpleAuthorizationInfo;
}
return null;
}
/**
* 登录拦截
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 查询到用户名
String principal = (String) token.getPrincipal();
// 数据库查询
User user = userService.login(principal);
if (user == null) {
throw new UnknownAccountException();
}
// 判断对象是否为空
if (!ObjectUtils.isEmpty(user)) {
// 传入密码md5+salt随机盐
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),getName());
// 返回
return info;
}
return null;
}
}
4、配置shiro
package com.tc.conf;
import com.tc.shiro.Realm.LoginRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* @author 谭铖
* @date 2021/9/7 19:17
*/
@Configuration
public class ShiroConfig {
/**
* realm自定义
* @return
*/
@Bean
Realm getLoginRealm(){
LoginRealm loginRealm = new LoginRealm();
// 定制MD5管理
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 设置MD5
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
// 添加散列
hashedCredentialsMatcher.setHashIterations(1024);
return loginRealm;
}
/**
* 安全管理器
* @return
*/
@Bean
DefaultWebSecurityManager getDefaultSecurityManager(){
// 创建
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 传入自定义的realm
securityManager.setRealm(getLoginRealm());
return securityManager;
}
/**
* ShiroFilterFactoryBean 实例了,替代它的是 ShiroFilterChainDefinition ,在这里定义 Shiro 的路径匹配规则即可。
* 拦截器
* @return
*/
@Bean
ShiroFilterChainDefinition shiroFilterChainDefinition(){
// 创建过滤对象
DefaultShiroFilterChainDefinition filterChainDefinition = new DefaultShiroFilterChainDefinition();
HashMap<String, String> hashMap = new LinkedHashMap<>();
//anon:无需认证即可访问。
//authc:需要认证才可访问。
//user:点击“记住我”功能可访问。
hashMap.put("/login","anon");
hashMap.put("/register","anon");
hashMap.put("/register.jsp","anon");
hashMap.put("/**","authc");
// 添加至过滤
filterChainDefinition.addPathDefinitions(hashMap);
return filterChainDefinition;
}
}
5、application
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
server.port=8888
server.servlet.context-path=/shiro
#应用名称
spring.application.name=shiro
#是否允许将sessionId 放到 cookie 中
shiro.sessionManager.sessionIdCookieEnabled=true
#是否允许将 sessionId 放到 Url 地址拦中
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
#访问未获授权的页面时,默认的跳转路径
shiro.unauthorizedUrl=/login
#表示开启 shiro
shiro.web.enabled=true
#表示登录成功的跳转页面
shiro.successUrl=/index
#表示登录页面
shiro.loginUrl=/login
#数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?serverTime=UTC
spring.datasource.username=root
spring.datasource.password=123456
#mybatis配置
#扫描实体类
mybatis.type-aliases-package=com.tc.pojo
#扫描mapper.xml
mybatis.mapper-locations=classpath:mybatis/*.xml
#logging.level.root=debug
#logging.level.com.tc.dao=debug
6、创建对象
pojo
package com.tc.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @author 谭铖
* @date 2021/9/8 13:44
* 用户注册
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String salt;
}
dao
package com.tc.dao;
import com.tc.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Set;
/**
* @author 谭铖
* @date 2021/9/8 14:25
* 登录注册
*/
@Mapper
public interface UserMapper {
int register(User user);
User selectByPrimaryKey(String username);
Set<String> getRolesByUserId(Integer id);
Set<String> getPremByUserId(Integer id);
}
<?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.tc.dao.UserMapper" >
<insert id="register" parameterType="user">
insert into user values(null,#{username},#{password},#{salt});
</insert>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultType="user">
select * from user where username=#{username};
</select>
<!-- 查询角色-->
<select id="getRolesByUserId" resultType="string" parameterType="integer">
SELECT r.rname
FROM user u
LEFT JOIN user_role ur
ON u.id = ur.userID
LEFT JOIN role r
ON r.rid = ur.roleID
WHERE u.id=#{id};
</select>
<!-- 查询角色操作-->
<select id="getPremByUserId" resultType="string" parameterType="integer">
SELECT p.pName
FROM user u
LEFT JOIN user_role ur
ON u.id = ur.userID
LEFT JOIN role r
ON r.rid = ur.roleID
LEFT JOIN role_perm rm
ON r.rid = rm.roleID
LEFT JOIN perm p
ON p.id = rm.permID
WHERE u.id=#{id};
</select>
</mapper>
service
package com.tc.service;
import com.tc.pojo.User;
import java.util.Set;
/**
* @author 谭铖
* @date 2021/9/8 14:28
*/
public interface userService {
/**
* 登录判断
* @param username
* @return
*/
public User login(String username);
/**
* 注册操作
* @param user
* @return
*/
public boolean register(User user);
/**
* 角色判断
* @param id
* @return
*/
Set<String> getRolesByUserId(Integer id);
/**
* 权限判断
* @param id
* @return
*/
Set<String> getPremByUserId(Integer id);
}
package com.tc.service.impl;
import com.tc.Utils.RandomShrio;
import com.tc.dao.UserMapper;
import com.tc.pojo.User;
import com.tc.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
/**
* @author 谭铖
* @date 2021/9/8 14:31
*/
@Service
@Transactional
public class UserserviceImpl implements userService{
@Autowired
UserMapper userDAO;
/**
* 登录
* @param
*/
@Override
public User login(String username) {
User user1 = userDAO.selectByPrimaryKey(username);
return user1;
}
/**
* 注册
* @param user
*/
@Override
public boolean register(User user) {
String salt = RandomShrio.Shiroran();
// 密码生成为md5
Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
// 传入密码
user.setPassword(md5Hash.toHex());
// 盐值
user.setSalt(salt);
// 注册
try {
userDAO.register(user);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public Set<String> getRolesByUserId(Integer id) {
return userDAO.getRolesByUserId(id);
}
@Override
public Set<String> getPremByUserId(Integer id) {
return userDAO.getPremByUserId(id);
}
}
controller
package com.tc.Controller;
import com.tc.dao.UserMapper;
import com.tc.pojo.User;
import com.tc.service.userService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author 谭铖
* @date 2021/9/7 19:58
* 登录页面跳转
*/
@Controller
public class LoginPage {
@Autowired
private userService userService;
@GetMapping({"/","login"})
public String loginPage(){
return "login";
}
@PostMapping("/login")
public String login(User user){
User login = userService.login(user.getUsername());
try {
if (user.getUsername().equals(login.getUsername())) {
Md5Hash md5Hash = new Md5Hash(user.getPassword(),login.getSalt(),1024);
String s = md5Hash.toHex();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),s);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
System.out.println("登录成功");
return "redirect:/index";
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("账号或密码错误");
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("控制指标");
}
return "login";
}
@GetMapping("/index")
public String indexPage(){
return "index";
}
@GetMapping("/logout")
public String logout(){
// 获取登录对象
Subject subject = SecurityUtils.getSubject();
// 判断用户是否登录 false为未登录 反之true
if (subject.isAuthenticated()) {
// 退出登录
subject.logout();
}
return "redirect:/";
}
/**
* 注册register
*/
@PostMapping("register")
public String Register(User user){
boolean register = userService.register(user);
if (register) {
System.out.println("注册成功");
return "login";
}else{
System.out.println("shi版");
}
return "register";
}
}
jsp页面
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@page pageEncoding="UTF-8" isErrorPage="false" contentType="text/html; UTF-8" %>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<h1>首页</h1>
<a href="${pageContext.request.contextPath}/logout">退出登录</a>
<ul>
<%-- 有任意一个确实--%>
<shiro:hasAnyRoles name="user,admin">
<li>
<a href="">用户管理</a>
<ul>
<%-- 角色操作--%>
<shiro:hasPermission name="user:select">
<li>select·</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:update">
<li>update·</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:insert">
<li>insert·</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:delete">
<li>delete·</li>
</shiro:hasPermission>
</ul>
</li>
</shiro:hasAnyRoles>
<%-- 包含admin--%>
<shiro:hasRole name="admin">
<li><a href="">仓库管理</a></li>
<li><a href="">订单管理</a></li>
<li><a href="">迷信管理</a></li>
</shiro:hasRole>
<li><a href="">奥数管理</a></li>
</ul>
<%--<ul>--%>
<%-- <li>--%>
<%-- <a href="">用户管理</a>--%>
<%-- <ul>--%>
<%-- <li>select·</li>--%>
<%-- <li>update·</li>--%>
<%-- <li>insert·</li>--%>
<%-- <li>delete·</li>--%>
<%-- </ul>--%>
<%-- </li>--%>
<%-- <li><a href="">仓库管理</a></li>--%>
<%-- <li><a href="">订单管理</a></li>--%>
<%-- <li><a href="">迷信管理</a></li>--%>
<%-- <li><a href="">奥数管理</a></li>--%>
<%--</ul>--%>
</body>
</html>
登录
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isErrorPage="false" %>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>login</title>
</head>
<body>
<h1>登录页面</h1>
<form action="${pageContext.request.contextPath}/login" method="post" >
账号:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<input type="submit" value="login">
</form>
</body>
</html>
注册
<%@page contentType="text/html; UTF-8" isErrorPage="false" pageEncoding="UTF-8" %>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>register</title>
</head>
<body>
<h1>register</h1>
<form action="${pageContext.request.contextPath}/register" method="post" >
账号:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<input type="submit" value="register">
</form>
</body>
</html>