Apache Shiro
是一个强大且易用的 Java
安全框架,执行身份验证、授权、密码和会话管理。使用 Shiro
的易于理解的 API
,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
官方案例:https://github.com/apache/shiro/tree/master/samples
官方文档: http://shiro.apache.org/tutorial.html
新建一个项目,再新建一个module
在module中导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
IDEA安装ini插件 settings > Plugins > Install JetBrains
在resources
下新建一个shrio.ini
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================
# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
在 resources
下新建一个 log4j.properties
文件
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
新建一个 Quickstart.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
//获取当前用户对象的 Subject
Subject currentUser = SecurityUtils.getSubject();
// 通过当前用户拿到session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 判断当前用户是否被认证
if (!currentUser.isAuthenticated()) {
//token :登录并获取令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true); //设置记住我
try {
currentUser.login(token); //执行登录操作
} catch (UnknownAccountException uae) {
//未知用户名
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
//密码错误
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
//账户锁定
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//粗粒度?
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//细粒度?
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
新建springboot项目;
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.0</version>
</dependency>
我们使用java config的方式自定义shiro的三个基本类
UserRealm 需要单独创建一个config,我们在项目新建一个config包,再新建一个UserReamlm.java
;
这里需要继承AuthorizingRealm
类,并重写两个函数
我们先建立基本的架构,如下
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权 doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证 doGetAuthenticationInfo");
return null;
}
}
在 config 包下我们再新建一个ShiroConfig.java
,使用 @Configuration
注册到我们的java config中;
重写三个模块,并使用@bean
注解将这些模块注册到我们的spring中
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;
@Configuration
public class ShiroConfig {
//1. 创建 realm 对象,需要自定义类
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//2. DefaultWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDafaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//3. ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
//设置安全管理器
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
}
由于这三个模块需要相互关联,需要使用@Qualifier
在模块的参数中引用我们注册的bean;
例如,我们已经将 userRealm()
模块使用@Bean
注解将该模块注册到spring中,但是后面定义的DefaultWebSecurityManager
模块需要关联 userRealm
() 模块,所以需要使用 @Qualifier
引用userRealm
() 模块,默认使用模块的名称注册到spring,所以这里我们直接输入 “userRealm
” 作为 @Qualifier
的参数,也可以自定义Bean的名称,使用name属性,例如: @Bean(name = "test")
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
<hr>
<a href="/add"></a>
<a href="/update"></a>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
目录结构
controller/Mycontroller.java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/", "index.html"})
private String Index(Model model){
model.addAttribute("msg", "Hello Shiro");
return "index";
}
@RequestMapping("/user/add")
private String add(){
return "user/add";
}
@RequestMapping("/user/update")
private String update(){
return "user/update";
}
}
关闭 thymeleaf 缓存
spring.thymeleaf.cache=false
测试
添加shiro的内置过滤器
我们在ShiroConfig
配置中的 ShiroFilterFactoryBean
模块进行配置;
config/ShiroConfig.java
LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
//配置add和update页面需要认证之后才能访问
filterMap.put("/user/add", "authc");
filterMap.put("/user/update", "authc");
bean.setFilterChainDefinitionMap(filterMap);
重新启动项目,测试一下
再访问add或者update页面时,由于我们没有认证,默认就跳转到了登录页面,默认是login.jsp
我们来配置一下我们的登录页面
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<form th:action="@{/login}" method="post" >
<h1>用户登录</h1>
<hr>
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
配置控制器
controller/MyController.java
@GetMapping("/login")
private String tologin(){
return "login";
}
在ShiroFilterFactoryBean
配置Shrio过滤器的登录跳转页面
config/ShiroConfig.java
bean.setLoginUrl("/login");
重新启动项目,测试
测试成功!
这里可以参考前面的Quickstart
@PostMapping("/login")
private String login(String username, String password, Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//获取将用户信息加密后的token
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token); //执行登录操作
return "index";
} catch (UnknownAccountException | IncorrectCredentialsException uae) {
//用户名不存在或密码错误
model.addAttribute("msg", "用户名或密码错误");
return "login";
} catch (LockedAccountException lae) {
//账户锁定
model.addAttribute("msg", "用户已锁定");
return "login";
}
catch (AuthenticationException ae) {
//未知错误
model.addAttribute("msg", "未知错误");
return "login";
}
}
前端login.html
页面添加错误提示标签
<p style="color: red" th:text="${msg}"></p>
测试
我们来到之前配置的UserRealm
的认证模块,配置一些模拟认证的信息
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证 doGetAuthorizationInfo");
//用户,密码,从数据库中获取
String username = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
if(!userToken.getUsername().equals(username)){
return null; // 抛出异常 UnknownAccountException
}
//密码认证,由shiro处理
return new SimpleAuthenticationInfo("", password, "");
}
测试一下
下面我们整合到数据库来实现完整的业务流程
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!--MYSQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--日志log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--mybatis整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
设置配置文件参数 application.yml
spring:
datasource:
username: root
password: 123123
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
设置mybatis的配置 application.properties
mybatis.type-aliases-package=com.springboot.study.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(30) CHARACTER SET utf8mb4 NOT NULL,
`passwd` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
建立pojo,为了代码简洁我们使用lombok快速生成(日常我们可以使用Alt + Insert
键进行快速生成)
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String username;
private String passwd;
}
建立mapper
import com.springboot.study.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User selectByUsername(String username);
}
建立mybatis的xml配置
在resources
下新建一个mapper目录,并创建mybatis.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.springboot.study.mapper.UserMapper">
<select id="selectByUsername" parameterType="String" resultType="User">
select * from mybatis.user where username = #{username}
</select>
</mapper>
配置service层
新建接口 UserService
,对应实现我们的 UserMapper
import com.springboot.study.pojo.User;
public interface UserService {
public User selectByUsername(String username);
}
新建 UserServiceImpl
实现 UserService
import com.springboot.study.mapper.UserMapper;
import com.springboot.study.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User selectByUsername(String username) {
return userMapper.selectByUsername(username);
}
}
在单元测试中测试service接口是否能正常使用
@Autowired
UserService userService;
@Test
void contextLoads() {
User root = userService.selectByUsername("admin");
System.out.println(root);
}
OK测试成功,接下来我们整合到Shrio中进行认证;
新建一个常量作为md5加密的盐值
utils/Salt.java
package com.springboot.study.utils;
public class Salt {
public static final String addSalt = "A0ds9L,ds"; // 自定义一个随机的字符作为加密盐值
}
我们将前面自定义的 UserRealm
中的 doGetAuthenticationInfo
方法修改一下,实现从数据库读取用户信息进行认证,并使用md5加密效验
@Autowired
UserService userService; //注入我们的service接口
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证 doGetAuthorizationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//用户,密码,从数据库中获取
User user = userService.selectByUsername(userToken.getUsername());
if(user == null){
return null; // 抛出异常 UnknownAccountException
}
//密码使用md5进行加密
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
user,
user.getPasswd(),
ByteSource.Util.bytes(Salt.addSalt), //使用额外的盐值进行加密处理,具体加密方式在ShiroConfig中设置
getName());
//密码认证,由shiro处理
return simpleAuthenticationInfo;
}
我们回到 ShiroConfig
中配置凭证比较器 和 Realm
/**
* 凭证比较器-加密加盐加次数
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//加密算法
hashedCredentialsMatcher.setHashIterations(1); //加密迭代次数,这里我们默认设置为1
return hashedCredentialsMatcher;
}
/**
* 1. 自定义的Realm
* */
@Bean
public UserRealm userRealm(){
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return userRealm;
}
这里需要注意的是,我们在 userRealm
方法新增了 setCredentialsMatcher()
这个方法,使我们的凭证比较器生效。
我们使用 Md5Hash
这个模块加密一段字符串,作为用户的密码储存到数据库中
String md5Hash = new Md5Hash("123123", addSalt).toString();
重启项目,测试登录
登录成功。
基本的数据对象关系 :
一个用户对应一个角色,一个角色对应多种权限,一个权限对应一个URL;URL可以使用通配符例如:/user/**
/*
Navicat MySQL Data Transfer
Source Server : local
Source Server Version : 50726
Source Host : localhost:3306
Source Database : mybatis
Target Server Type : MYSQL
Target Server Version : 50726
File Encoding : 65001
Date: 2020-02-23 21:56:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for shiro_permision
-- ----------------------------
DROP TABLE IF EXISTS `shiro_permision`;
CREATE TABLE `shiro_permision` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`path` varchar(100) NOT NULL,
`permision` varchar(100) NOT NULL,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shiro_permision
-- ----------------------------
INSERT INTO `shiro_permision` VALUES ('2', '/user/update', 'user:update', '更新权限');
INSERT INTO `shiro_permision` VALUES ('3', '/user/query', 'user:query', '查询权限');
INSERT INTO `shiro_permision` VALUES ('4', '/index', 'anon', '访问主页');
INSERT INTO `shiro_permision` VALUES ('5', '/user/add', 'user:add', '添加权限');
-- ----------------------------
-- Table structure for shiro_role
-- ----------------------------
DROP TABLE IF EXISTS `shiro_role`;
CREATE TABLE `shiro_role` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`role` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shiro_role
-- ----------------------------
INSERT INTO `shiro_role` VALUES ('1', 'root', '超级管理员');
INSERT INTO `shiro_role` VALUES ('2', 'user', '普通用户');
-- ----------------------------
-- Table structure for shiro_role_permision
-- ----------------------------
DROP TABLE IF EXISTS `shiro_role_permision`;
CREATE TABLE `shiro_role_permision` (
`role_id` int(11) NOT NULL,
`permision_id` int(11) NOT NULL,
KEY `role_id` (`role_id`),
KEY `permision_id` (`permision_id`),
CONSTRAINT `shiro_role_permision_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `shiro_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `shiro_role_permision_ibfk_2` FOREIGN KEY (`permision_id`) REFERENCES `shiro_permision` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shiro_role_permision
-- ----------------------------
INSERT INTO `shiro_role_permision` VALUES ('2', '3');
INSERT INTO `shiro_role_permision` VALUES ('1', '2');
INSERT INTO `shiro_role_permision` VALUES ('1', '5');
INSERT INTO `shiro_role_permision` VALUES ('1', '4');
INSERT INTO `shiro_role_permision` VALUES ('2', '5');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(30) CHARACTER SET utf8mb4 NOT NULL,
`passwd` varchar(100) NOT NULL,
`role_id` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_ibfk_1` (`role_id`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `shiro_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'user', 'd39cac196ae3e7d54a4ea2b1e90ca8c1', '2');
INSERT INTO `user` VALUES ('2', 'admin', 'd39cac196ae3e7d54a4ea2b1e90ca8c1', '1');
使用 mybatis 生成器进行自动生成 dao
、 pojo
、 mapper
等代码
<!--mybatis生成器插件-->
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<!-- 配置数据库链接及mybatis generator core依赖 生成mapper时使用 -->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
在 resources
下新建 generator
目录 并创建 配置文件generatorConfig.xml
系应该数据库等信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="123123">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.springboot.study.pojo" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.springboot.study.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="shiro_permision" domainObjectName="ShiroPermision" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="shiro_role" domainObjectName="ShiroRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="shiro_role_permision" domainObjectName="ShiroRolePermision" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
配置完成后,点击idea右上角的 Maven project
,找到我们的 generator
插件
点击插件会自动生成pojo、dao、和mybatis sql实现的xml配置文件
service层需要我们手动实现;
由于使用mybatis生成器自动生成的代码会覆盖掉我们原有的代码,所以我们需要重新实现一下用户认证的mapper,并进行测试
在 springboot主入口
处配置一个MapperScan
用于扫描我们定义的dao
@MapperScan(basePackages = "com.springboot.study.mapper")
定义一个mapper,使用用户名查询用户信息
在UserMapper
下新增
User selectByUsername(String username);
service层配置
UserService
User selectByUsername(String username);
UserServiceImpl
@Autowired
UserMapper userMapper;
@Override
public User selectByUsername(String username) {
User user = userMapper.selectByUsername(username);
return user;
}
UserMapper.xml
在增加mapper行为
<select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from user
where username = #{username}
</select>
回到我们的 UserRealm.java
给用户进行认证
//批量添加权限
List<ShiroPermision> shiroPermisions = shiroPermisionService.selectAllInfo();
for (ShiroPermision per: shiroPermisions) {
//根据表添加权限
if(per.getPermision().equals("anon") || per.getPermision().equals("authc")){
filterMap.put(per.getPath(), per.getPermision());
}else{
filterMap.put(per.getPath(), "perms[%s]".replaceFirst("%s", per.getPermision()));
}
}
bean.setFilterChainDefinitionMap(filterMap);
过滤器设置权限逻辑:
shiro_permision
,先赋值过滤器类型,过滤器为authc
的则进行权限赋值准备工作:
mapper
和service
实现ShiroPermisionMapper
中的mapper实现
//获取权限表的所有信息
List<ShiroPermision> selectAllInfo();
在ShiroPermisionMapper.xml
中新增 mybatis配置
<!--获取权限表的所有信息-->
<select id="selectAllInfo" resultType="ShiroPermision" >
select * from shiro_permision
</select>
配置service和serviceImpl
public List<ShiroPermision> selectAllInfo() {
List<ShiroPermision> shiroPermisions = shiroPermisionMapper.selectAllInfo();
return shiroPermisions;
}
回到我们的ShiroConfig
的过滤器中,修改成从ShiroPermision
表中添加权限信息
//批量添加权限
List<ShiroPermision> shiroPermisions = shiroPermisionService.selectAllInfo();
for (ShiroPermision per: shiroPermisions) {
//根据表添加权限
if(per.getPermision().equals("anon") || per.getPermision().equals("authc")){
filterMap.put(per.getPath(), per.getPermision());
}else{
filterMap.put(per.getPath(), "perms[%s]".replaceFirst("%s", per.getPermision()));
}
}
bean.setFilterChainDefinitionMap(filterMap);
授权逻辑:
shiro_role_permision
表中对应的权限信息添加查询所有角色与权限对应关系;
添加mapper
Collection<Integer> selectByRoleId(int roleId);
添加service
Collection<String> getPemisionrInfos(int roleId);
添加serviceImpl
@Autowired
ShiroRolePermisionMapper shiroRolePermisionMapper;
@Autowired
ShiroPermisionMapper shiroPermisionMapper;
@Override
public Collection<String> getPemisionrInfos(int roleId){
Collection<Integer> shiroRolePermisions = shiroRolePermisionMapper.selectByRoleId(roleId);
Collection<String> pers = new ArrayList<>();
for(Integer perId: shiroRolePermisions) {
String per = shiroPermisionMapper.selectByPrimaryKey(perId).getPermision();
if(!(per.equals("anon") || per.equals("authc"))){
pers.add(per);
}
}
return pers;
}
在 ShiroRolePermisionMapper
添加配置
<!--获取所有权限对应信息-->
<select id="selectByRoleId" resultType="int" parameterType="int">
select permision_id from shiro_role_permision where role_id = #{roleId}
</select>
效果测试: