SpringBoot整合Shiro
1.创建一个springboot项目
项目结构图
表结构
1.1pom文件依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lanou</groupId>
<artifactId>springboot-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-shiro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--shiro-thymeleaf-->
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.11</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<!--
Subject: 用户
SecurityManager: 管理所有用户
Realm: 连接数据
-->
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.0</version>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 properties文件
#datasource
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shiro?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
#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
mybatis:
type-aliases-package: com.lanou.pojo
mapper-locations: classpath:mapper/*xml
1.3 编写页面
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.thymeleaf.org/thymeleaf-extras-shiro ">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<div shiro:notAuthenticated>
<a th:href="@{/toLogin}">登录</a>
</div>
<!--<div shiro:Authenticated="*:*">
<a href="#" th:href="@{/logout}">注销</a>
</div>-->
<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
在template目录下创建user文件夹
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
2.后台代码部分
user类
package com.lanou.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String perm;
}
mapper接口
@Mapper
@Repository
public interface UserMapper {
User queryUserByName(String name);
}
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.lanou.mapper.UserMapper">
<select id="queryUserByName" resultType="com.lanou.pojo.User" parameterType="String">
select * from t_user where username=#{name}
</select>
</mapper>
service接口
public interface UserService {
User queryUserByName(String name);
}
service实现类
package com.lanou.service;
import com.lanou.mapper.UserMapper;
import com.lanou.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 queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
controller
package com.lanou.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","Hello,Shiro123456789");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "/user/add";
}
@RequestMapping("/user/update")
public String update(){
return "/user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, Model model){
//获取当前的用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
subject.login(token);//执行登录的方法,如果没有异常就说明ok了
return "index";
}catch (UnknownAccountException e){ //用户名不存在
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){//密码不存在
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "需要授权才能访问该页面";
}
}
config
package com.lanou.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean:3
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shirode内置过滤器
/*
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有 记住我 功能才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有某个角色权限
*/
//拦截
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
//filterChainDefinitionMap.put("/user/add","authc");
//filterChainDefinitionMap.put("/user/update","authc");
//授权,正常情况下,没有授权会跳转到未授权页面401
filterChainDefinitionMap.put("/user/add","perms[user:add]");
filterChainDefinitionMap.put("/user/update","perms[user:update]");
filterChainDefinitionMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//未授权的的页面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager:2
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建 realm 对象:需要自定义类:1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合ShiroDialect:用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm自定义验证
package com.lanou.config;
import com.lanou.pojo.User;
import com.lanou.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.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import javax.annotation.Resource;
public class UserRealm extends AuthorizingRealm {
@Resource
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerm());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了==>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken)token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){//没有这个人
return null;
}
//密码认证,shiro做
//MD5 及 MD5盐值加密
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
}
2. Shiro常见面试题
2.1什么是shiro
Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密、会话管理、与web集成、缓存等功能,对于任何一个应用程序,都可以提供全面的安全服务,相比其他安全框架,shiro要简单的多。
2.2 shiro的核心概念Subject、SecurityManager、Realm
Subject:主体,代表了当前"用户",这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如爬虫、机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者。
SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,SecurityManager相当于springmvc中的dispatchrServlet前端控制器。
Realm:域,shiro从Realm获取安全数据(如用户,角色,权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。
2.3 Authentication 身份验证
principals:身份,即主体的标识属性,可以是任何东西,如用户名,邮箱等,唯一即可。
credentials:证明/凭证,即只有主体知道的安全值,如密码/数字证书等。
身份认证流程:
(1)首先调用Subject.login(token)进行登录,其会自动委托给SecurityManager,调用之前必须通过SecurityUtils.setSecurityManager()设置;
(2)SecurityManager负责真正的身份验证逻辑;它会委托给Authenticator进行身份验证;
(3)Authenticator才是真正的身份验证者,shiro api中核心的身份认证入口点,此处可以自定义插入自己的实现;
(4)Authenticator可能会委托给相应的AuthenticStrategy进行多Realm身份验证,默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证;
(5)Authenticator会把相应的token传入Realm,从Realm获取身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处可以配置多个Realm将按照相应的顺序及策略进行访问。Authenticator及AuthenticationStrategy
(6)Authenticator的职责是验证用户账号,是shiroapi中身份验证核心的入口点。
(7)AuthenticationStrategy认证策略ModularRealmAuthenticator默认使用AtLeastOneSuccessfulStrategy策略
1 > FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功认证信息,其他的忽略;
2 > AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份验证成功的认证信息;
3 > AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
自定义实现认证时一般继承AbstractAuthenticationStrategy即可
2.4 Authorization授权
授权,也叫访问控制,即在应用中控制谁能访问哪些资源(如访问页面/编辑数据/页面操作等)。在授权中需要了解的几个关键对象:主体(Subject)、资源(Resource)、权限(Permission)、角色(Role)。
授权方式:
- 编程式:通过写if/else授权代码完成
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("admin")){
//有权限
} else {
//没有权限
}
- 注解
@RequiresRoles("admin")
public void helloWord(){
//有权限
}
- JSP标签
<shiro:hasRole name = "admin">
<!--有权限-->
</shiro:hasRole>
基于资源的访问控制
1.隐式角色:硬编码的方式(if/else);粗粒度造成的问题:如果有一天不需要了那么就需要修改相应代码把所有相关的地方进行删除;
-
显示角色:规则:资源标识符:操作(user:create,user:update)这种方式叫资源级别的粒度;好处:如果需要修改都是一个资源级别的修改,不会对其他模块代码产生影响,粒度小;但实现起来可能稍微复杂点,需要维护 “用户—角色,角色—权限(资源:操作)” 之间的关系
Permission:字符串通配符权限
规则:资源标识符。操作:对象实例ID
":"表示资源/操作/实例的分割
","表示操作的分割
"*"表示任意资源/操作/实例
-
单个资源多个权限
Role=system:user:update,system:user:delete 。等价于 role=system:user:update,delete。
但是反过来规则不成立。
代码判断
subject().checkPermissions(“system:user:update,delete”)
-
单个资源全部权限:role=sys:user:*/sys:user
-
所有资源全部权限:role=*:view; subject.checkPermissions(“user:view”);
-
实例级别的权限
单实多限:role=“user:update,delete:1”;
subject().checkPermissions(“user:update,delete:1”);
相应代码把所有相关的地方进行删除;
-
显示角色:规则:资源标识符:操作(user:create,user:update)这种方式叫资源级别的粒度;好处:如果需要修改都是一个资源级别的修改,不会对其他模块代码产生影响,粒度小;但实现起来可能稍微复杂点,需要维护 “用户—角色,角色—权限(资源:操作)” 之间的关系
Permission:字符串通配符权限
规则:资源标识符。操作:对象实例ID
":"表示资源/操作/实例的分割
","表示操作的分割
"*"表示任意资源/操作/实例
-
单个资源多个权限
Role=system:user:update,system:user:delete 。等价于 role=system:user:update,delete。
但是反过来规则不成立。
代码判断
subject().checkPermissions(“system:user:update,delete”)
-
单个资源全部权限:role=sys:user:*/sys:user
-
所有资源全部权限:role=*:view; subject.checkPermissions(“user:view”);
-
实例级别的权限
单实多限:role=“user:update,delete:1”;
subject().checkPermissions(“user:update,delete:1”);
all实单限: