1.什么是shiro?
- Apache Shiro 是一个java的安全(权限)框架。
- Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
- Shiro可以完成,认证,授权,加密,会话管理, Web集成,缓存等。会话过程更便捷,并可为应用提供安全保障。
- 启动一个简易shiro:
内容网址:https://github.com/apache/shiro
maven下的内容在:shiro/samples/quickstart
- 导入依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
- 导入配置文件
- 运行helloshiro:
shiro中三大对象
- Subject : 用户
- SecurityManage:管理所有用户
- Realm: 连接数据
SpringBoot 整合Shiro环境搭建
- 创建springboot项目:
- 导入依赖:
<!-- shiro和spring的整合 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
- config配置文件书写:
自定义的UserRealm
- 继承AuthorizingRealm方法。 方法重写授权和认证:
//自定义UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override //方法重写 Ctrl+i
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;
}
}
ShiroConfig配置类:
- 起始加上注解@Configuration:给我们的类加上了cglib代理。在执行我们的配置类的方法时,会执行cglib代理类中的方法
- 配置三个方法ShiroFilterFactoryBean 、DefaultWebSecurityManager、创建UserRealm对象(逆序配置)
- @Bean 是把方法加入spring进行托管 ,使用@Qualifier在容器中拿出,可以给bean赋予名字,如果不赋予名字默认为方法名。
@Configuration //加上@Configuration注解主要是给我们的类加上了cglib代理。在执行我们的配置类的方法时,会执行cglib代理类中的方法
public class ShiroConfig {
//ShiroFilterFactoryBean : 3
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return shiroFilterFactoryBean;
}
@Bean(name = "SecurityManager")
//DefaultWebSecurityManager : 2 @Qualifier("userRealm")这个注解就是从spring容器中拿我们托管的UserRealm实例bean,这个实例默认名字叫方法名
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager SecurityManager = new DefaultWebSecurityManager();
//关联UserRealm
SecurityManager.setRealm(userRealm);
return SecurityManager;
}
//创建UserRealm对象 自定义 : 1
@Bean //也可以设置bean名字@Bean(name = "user") ,如果不设置就是方法名注入spring容器中
public UserRealm userRealm(){
return new UserRealm();
}
}
- shiro的登录拦截
shiro内置过滤器
- anon:无需认证就可以访问
- authc:必须认证了才能访问
- user:必须拥有记住我功能才能用
- perms:拥有对某个资源的权限才能访间;
- role:拥有某个角色权限才能访问
//ShiroFilterFactoryBean : 3
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证了才能让间
user:必须拥有记住我功能才能用
perms:拥有对某 个资源的权限才能访间;
role:拥有某个角色权限才能访问
*/
Map<String,String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","anon"); //地址一定要为controller中跳转的地址
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
bean.setLoginUrl("/toLogin");
return bean;
}
- shiro用户认证
- 登录页面:
<div>
<h1>登录</h1>
<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>
</div>
- controller:
@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";
}
}
- UserRealm认证方法:
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
//用户名,密码,数据中取
String name = "root";
String password = "123456";
UsernamePasswordToken userTaken = (UsernamePasswordToken) token; //获取controller中输入的taken(账户密码)
if(!userTaken.getUsername().equals(name)) {
return null; //自动抛出controller中的异常
}
//密码不需要我们操作,shiro自动操作
return new SimpleAuthenticationInfo("",password,"");
}
shiro整合mybatis
- 添加依赖:
<!--mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<!--log4j-->
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
- yml配置数据源:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/ssm?useUnicode=true?characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些的,需要自己绑定
#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.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- propertise绑定mybatise:
#绑定mybatis 的实体类
mybatis.type-aliases-package= com.qing.pojo
#绑定mybatis的配置文件层
mybatis.mapper-locations= classpath:mapper/*.xml
- sql语句mapper.xml配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qing.mapper.EmployeeMapper">
<!--查询单个用户-->
<select id="queryEmployeeByUsername" resultType="Employee" parameterType="String">
select * from employee where username = #{username};
</select>
</mapper>
- 实体类(pojo)、dao(mapper)、接口接口实现类(service):
- dao加注解:@Repository @Mapper 将mapper注入spring容器中
- 接口实现类:@Service
- 接口中内容和dao内容一样,且实现类和接口都放在service中
shiro的认证配置
config中的userRealm认证配置:
- 认证主要是为了验证用户名是否正确,密码shiro自动在数据库中进行验证
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userTaken = (UsernamePasswordToken) token; //获取controller中输入的taken(账户密码)
Employee employee = employeeService.queryEmployeeByUsername(userTaken.getUsername());
if(employee == null) {
return null; //自动抛出controller中的异常
}
//密码不需要我们操作,shiro自动操作
return new SimpleAuthenticationInfo("",employee.getPassword(),"");
}
shiro的权限配置
config中的userRealm授权配置:
- 主要是为了设置登录用户只有在拥有相应权限等级才能进入
- 在shiroConfig中添加权限:
- 在shiroConfig中添加权限:
//授权 ,正常情况下跳转到授权页面
filterMap.put("/user/add","perms[1]"); //add页面只能权限内容为"1"才能进行访问
filterMap.put("/user/update","perms[2]"); //update页面只能权限内容为"2"才能进行访问
//未授权页面
bean.setUnauthorizedUrl("/unauth"); //未授权页面跳转
- 在UserRealm中查询数据库中是否含有权限并返回:
//授权
@Override //方法重写 Ctrl+i
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//为用户授权
//info.addStringPermission("1");
//拿到当前登录对象
Subject subject = SecurityUtils.getSubject(); //拿到当前登录对象
Employee employee = (Employee) subject.getPrincipal(); //拿到Employee对象
info.addStringPermission(employee.getPerms()); //为用户授权
return info;
}
主页显示定制(删除、显示可用)
- 导入命名空间 ,使用shiro:hasPermission=""来判断用户是否拥有这一个权限。
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
- shiro:Authenticated来判断用户是否认证(登录)
- shiro:notAuthenticated表示未认证
- thymeleaf 和 shiro的整合依赖
<!--shiro-thymeleaf整合包-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
- 在div中添加如下代码,实现shiro-thymeleaf整合:
//整合ShiroDialect:用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
- 主页代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${model}">
<div shiro:Authenticated><a th:href="@{/logout}">退出</a></div> <!-- Authenticated表示被认证以后-->
<div shiro:notAuthenticated><a th:href="@{/toLogin}">登录</a></div> <!--notAuthenticated表示未认证-->
<hr>
<div shiro:hasPermission="1">
<a th:href="@{/user/add}">添加</a>
</div>
<div shiro:hasPermission="2"> <!--如果有权限"2" 显示div内容-->
<a th:href="@{/user/update}">修改</a>
</div>
</body>
</html>