Shiro安全框架学习
步骤
快速开始
名词介绍:
Subject:表示当前用户
Shiro SecurityManager:管理所有的Subject,管理安全的
Realm:数据访问控制,和数据打交道
1、导入maven的依赖shiro的依赖,日志的依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>2.0.0-alpha5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
注意依赖的作用域不能是test,否则log4j不能使用
2、配置shiro的配置文件
3、Quickstart
从官网拿来.java文件
shiro中的subject分析
参考https://github.com/apache/shiro/blob/main/samples/quickstart/src/main/java/Quickstart.java
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// get the currently executing user:
//获取当前用户对象
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过当前用户拿到Session
Session session = currentUser.getSession();
//设置了一个someKey,aVlaue
session.setAttribute("someKey", "aValue");
//拿到刚才Session里面设置的值,相当于脱离了web存值取值
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
//判断当前的用户是否被认证
if (!currentUser.isAuthenticated()) {
//Token:令牌,通过用户的账号密码,获取一个令牌,此时没有获取,随机设置
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);//设置j记住我
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!");
}
//all done - log out!注销功能
currentUser.logout();
//
System.exit(0);
}
重要的几个方法
//获取当前用户对象
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户拿到Session
Session session = currentUser.getSession();
//判断当前的用户是否被认证
currentUser.isAuthenticated
//获取用户是否拥有该角色
currentUser.hasRole("schwartz")
//获取当前用户的权限
currentUser.isPermitted("lightsaber:wield")
//注销
currentUser.logout();
SpringBoot整合Shiro环境搭建
1、thymeleaf模板
<!--thymeleaf模板依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
2、controllor搭建
3、web页面,首页的搭建
4、导入jar包,依赖
<dependencies>
<!--
Subject:用户
SecurityManager 管理所有用户
Realm:连接数据
-->
<!--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>
<!--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,这是MyBatis官方提供的适配Spring Boot,而不是Spring Boot自己的-->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</dependency>
</dependencies>
5、创建config包
创建类:
ShiroConfig:作用是注册Bean
①创建reaml对象,需要自定义类
②创建DefaultWebSecurityManager:这个Bean关联Realm,它是一个中间商,使用方法securityManager.setRealm(userRealm)
③ShiroFilterFactoryBean:这个Bean关联上面的,设置安全管理器
@Configuration
public class ShiroConfig {
//以下三个方法倒着写
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultSecurityManager defaultSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
//添加Shiro的内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证才能访问
user:必须拥有记住我功能才能用
perms:必须拥有资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截
Map<String,String> filterMap = new LinkedHashMap<String,String>();
//授权:正常的情况下,没有授权,会跳转到未授权界面
//这句话表示,要想访问/user/add,必须有字符串user:add才能访问下面同理
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
//授权
bean.setFilterChainDefinitionMap(filterMap);//往内置过滤器中添加
//设置未授权界面
bean.setUnauthorizedUrl("/noauth");
//设置登录的请求
bean.setLoginUrl("/toLogin");
return bean;
}
//DefaultSecurityManager
//@Qualifier("userRealm"):此注解表示将下面注入到spring容器中的UserRealm指定起来
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm,此时不能直接获取UserRealm,需要技巧
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象,需要自定义
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合ShiroDialect:用来整合shiro和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
自定义类:继承extends AuthorizingRealm
UserRealm
Shiro实现登录拦截
在ShiroConfig中配置
//添加Shiro的内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证才能访问
user:必须拥有记住我功能才能用
perms:必须拥有资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截
Map<String,String> filterMap = new LinkedHashMap<String,String>();
//授权:正常的情况下,没有授权,会跳转到未授权界面
//这句话表示,要想访问/user/add,必须有字符串user:add才能访问下面同理
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
Shiro实现用户认证
在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";
}
}
再在自定义的Reaml中编写认证,获取数据库中的用户及权限
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());//userToken.getUsername():获取用户名
if(user==null){//没有这个人
return null;//UnknownAccountException
}
//登录成功之后传给前端一个Session,用于验证是否显示登录这个按钮
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密码认证,shiro做~
// String name = "root";
// String password = "123456";
// UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// if (!userToken.getUsername().equals(name)){
// return null;
// }
//第一个参数传值给
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
Shiro整合MyBatis
1、依赖导入
<dependencies>
<!--
Subject:用户
SecurityManager 管理所有用户
Realm:连接数据
-->
<!--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>
<!--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,这是MyBatis官方提供的适配Spring Boot,而不是Spring Boot自己的-->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</dependency>
</dependencies>
2、编写配置文件applicatin.yml配置druid文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/databasename?severTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatement: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: durid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、编写pojo类User
4、创建包mapper并创建UserMapper接口相当于dao层
package com.joy.mapper;
import com.joy.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author 焦恩越
* @create 2021-11-19-21:46
*/
@Repository//注册到spring容器中
@Mapper//表明这是一个mapper
public interface UserMapper {
public User queryUserByName(String name);
}
5、在resource中创建mapper包并创建UserMapper.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.joy.mapper.UserMapper">
<select id="queryUserByName" resultType="com.joy.pojo.User">
select id,name,pwd from user where name=#{name}
</select>
</mapper>
6、编写service层
7、在UserRealm中注册service进行认证,在认证里面连接数据库
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
//拿到用户名密码封装成一个令牌对象
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());//userToken.getUsername():获取用户名
if(user==null){//没有这个人
return null;//UnknownAccountException
}
//登录成功之后传给前端一个Session,用于验证是否显示登录这个按钮
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密码认证,shiro做~
//第一个参数传值给
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
8、Shiro请求授权实现
在自定义的ShiroConfig的ShiroFilterFactoryBean中设置访问权限
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultSecurityManager);
//添加Shiro的内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证才能访问
user:必须拥有记住我功能才能用
perms:必须拥有资源的权限才能访问
role:拥有某个角色权限才能访问
*/
//拦截设置权限
Map<String,String> filterMap = new LinkedHashMap<String,String>();
//授权:正常的情况下,没有授权,会跳转到未授权界面
//这句话表示,要想访问/user/add,必须有字符串user:add才能访问下面同理
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);//往内置过滤器中添加
在ShiroConfig中给用户授予权限
//自定义的UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权");
//SimpleAuthorizationInfo():进行授权的对象
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前登录的这个对象
Subject subject = SecurityUtils.getSubject();
User user = (User)subject.getPrincipal();//拿到User对象,获取下面认证中的User对象,因为不能直接获取,得通过令牌获取,但是授权中没有令牌对象
//设置当前用户权限,实际是一个字符串,在数据库中拿到
info.addStringPermission(user.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了认证");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());//userToken.getUsername():获取用户名
if(user==null){//没有这个人
return null;//UnknownAccountException
}
//登录成功之后传给前端一个Session,用于验证是否显示登录这个按钮
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密码认证,shiro做~也可以实现加密
//第一个参数传值给授权使用,用于获取用户数据库字段中的权限
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}

浙公网安备 33010602011771号