SpringBoot08:Shiro
什么是Shiro?
一个Java的安全(权限)框架,可以完成认证、授权、加密、会话管理、Web集成、缓存等
下载地址:Apache Shiro | Simple. Java. Security.
快速启动
先在官网找到入门案例:shiro/samples/quickstart at main · apache/shiro · GitHub
步骤:
1、新建一个 Maven 工程,删除其 src 目录,将其作为父工程
2、在父工程中新建一个 Maven 模块
3、在maven模块中,复制依赖
<dependencies><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.4.2</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId><version>1.7.24</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></dependencies>
4、复制 log4j.properties
log4j.rootLogger=INFO, stdoutlog4j.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
5、复制 shiro.ini(要先在 IDEA中添加 ini 插件)
[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
6、复制 Quickstart
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
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;/*** @ClassName Quickstart* @Description TODO* @Author GuoSheng* @Date 2021/4/20 17:28* @Version 1.0**/
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):DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();IniRealm iniRealm=new IniRealm("classpath:shiro.ini");defaultSecurityManager.setRealm(iniRealm);// 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(defaultSecurityManager);// Now that a simple Shiro environment is set up, let's see what you can do:// 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 = currentUser.getSession();session.setAttribute("someKey", "aValue");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()) {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!");}//all done - log out!currentUser.logout();System.exit(0);}
}
7、运行结果
Shiro的Subject分析
Quickstart 中的一些方法:
1、获取当前用户
Subject currentUser = SecurityUtils.getSubject();
2、通过当前用户拿到 Session
Session session = currentUser.getSession();
3、用session存值取值
session.setAttribute("someKey", "aValue");String value = (String) session.getAttribute("someKey");
4、判断是否被认证
currentUser.isAuthenticated()
5、执行登录操作
currentUser.login(token);
6、打印其标识主体
currentUser.getPrincipal()
7、判断当前用户是否有某个角色
currentUser.hasRole("schwartz")
8、注销
currentUser.logout();
SpringBoot整合Shiro环境搭建
步骤:
1、导入shiro的整合依赖
<!--shiro整合spring--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.1</version></dependency>
2、在config包下,编写Shiro的配置类
①自定义 Realm 类
public class UserRealm extends AuthorizingRealm {//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了shiro的授权方法");return null;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("执行了shiro的认证方法");return null;}
}
②自定义 ShiroConfig
public class ShiroConfig {//ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//设置安全管理器bean.setSecurityManager(defaultWebSecurityManager);return bean;}//DefaultWebSecurityManager@Beanpublic DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//关联 UserRealmsecurityManager.setRealm(userRealm);return securityManager;}//创建Realm对象,需要自定义类@Beanpublic UserRealm userRealm(){return new UserRealm();}
}
Shiro实现登录拦截
功能:必须认证了才能访问add和update页面,没有认证直接跳到登录页面
步骤:
1、编写前端页面
①编写首页
<h1>首页</h1>
②编写测试页
(登录首页的时候,通过controller跳到测试页,测试页包含可以跳到add和update页面的超链接)
<h1>测试页</h1>
<p th:text="${msg}"></p><a th:href="@{/user/add}">add</a><a th:href="@{/user/update}">update</a>
③add页面
<h1>add</h1>
增加一个用户
④update页面
<h1>update</h1>
修改一个用户
⑤登录页
<h1>登录</h1>
<form action="toLogin">用户名:<input type="text" name="username"> <br>密码: <input type="password" name="password"> <br><button type="submit">提交</button>
</form>
2、编写Controller
@Controller
public class MyController {@RequestMapping({"/","/index","/index.html"})public String toIndex(Model model){model.addAttribute("msg","hello,Shiro");return "test";}@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";}
}
3、shiro配置登录拦截
@Configuration
public class ShiroConfig {//ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired 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", "authc");filterMap.put("/user/update", "authc");bean.setFilterChainDefinitionMap(filterMap);//设置登录的请求bean.setLoginUrl("/toLogin");return bean;}//DefaultWebSecurityManager@Beanpublic DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//关联 UserRealmsecurityManager.setRealm(userRealm);return securityManager;}//创建Realm对象,需要自定义类@Beanpublic UserRealm userRealm(){return new UserRealm();}
}
Shiro实现用户认证
步骤:
1、在 UserRealm中,编写认证方法
//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了shiro的认证方法");//用户名、密码(要从数据库中获取)String name = "root";String password = "123456";UsernamePasswordToken userToken = (UsernamePasswordToken)token;if(!userToken.getUsername().equals(name)){ //如果userToken中的username和数据库中取出来的name不一样return null; //抛出异常 UnknownAccountException}//密码认证,shiro做return new SimpleAuthenticationInfo("",password,"");}
2、在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";}}
步骤解析:
Shiro整合MyBatis
步骤:
1、导入依赖
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.18</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency>
2、编写application.yaml和application.properties配置文件
①application.yaml
spring:datasource:username: rootpassword: 123456url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTCdriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
②application.properties
mybatis.type-aliases-package=com.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
3、编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {private int id;private String name;private String pwd;
}
4、编写mapper层
①UserMapper接口
@Repository
@Mapper
public interface UserMapper {//根据用户名查用户信息public User queryUserByName(String name);
}
②UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper"><select id="queryUserByName" parameterType="String" resultType="User">select * from mybatis.user where name = #{name};</select>
</mapper>
5、编写service层
①UserService接口
public interface UserService{public User queryUserByName(String name);
}
②UserServiceImpl
@Service
public class UserServiceImpl implements UserService{@AutowiredUserMapper userMapper;@Overridepublic User queryUserByName(String name) {return userMapper.queryUserByName(name);}
}
6、把之前在UserRealm中直接写的name和password,改成从数据库中查出来的
public class UserRealm extends AuthorizingRealm {@AutowiredUserServiceImpl userService;//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了shiro的授权方法");return null;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了shiro的认证方法");UsernamePasswordToken userToken = (UsernamePasswordToken)token;//连接真实的数据库User user = userService.queryUserByName(userToken.getUsername());//如果user为空,说明用户不存在if(user == null){return null; //抛异常 UnknownAccountException}//密码认证,shiro做return new SimpleAuthenticationInfo("",user.getPwd(),"");}
}
Shiro请求授权实现
1、在ShiroConfig中设置访问哪些路径,需要哪些权限,并配置未授权页面
filterMap.put("/user/add","perms[user:add]"); //拥有 user:add 权限才能访问/user/addfilterMap.put("/user/update","perms[user:update]");
bean.setUnauthorizedUrl("/noauth");
2、在UserRealm中给当前用户授权,其中权限是从数据库中查出来的
@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了shiro的授权方法");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//拿到当前登录的这个对象Subject subject = SecurityUtils.getSubject();User currentUser = (User)subject.getPrincipal(); //拿到user对象info.addStringPermission(currentUser.getPerms());return info;}
3、在controller中设置未授权url处理
@RequestMapping("/noauth")@ResponseBodypublic String unauthorized(){return "未经授权,无法访问此页面";}
Shiro整合Thymeleaf
1、导入依赖
<!--shiro-thymeleaf整合--><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.0.0</version></dependency>
2、在shiroConfig中整合thymeleaf
//ShiroDialect:用来整合 shiro thymeleaf@Beanpublic ShiroDialect getShiroDialect(){return new ShiroDialect();}
3、更改前端页面
①在test页面编写一个登录连接
<p><a th:href="@{/toLogin}">登录</a>
</p>
②在首页设置add和update链接,拥有对应权限才可以访问
shiro命名空间:
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
链接:
<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>
SpringBoot08:Shiro相关推荐
- Shiro框架:Shiro简介、登陆认证入门程序、认证执行流程、使用自定义Realm进行登陆认证、Shiro的MD5散列算法
一.Shiro介绍: 1.什么是shiro: (1)shiro是apache的一个开源框架,是一个权限管理的框架,实现用户认证.用户授权. (2)spring中有spring security,是一个 ...
- shiro学习(1):shiro简介
Apache Shiro是Java的一个安全框架.对比另一个安全框架Spring Sercurity,它更简单和灵活. Shiro可以帮助我们完成:认证.授权.加密.会话管理.Web集成.缓存等. A ...
- 第一章:Shiro简介
一,shiro是什么? 一个安全框架 二,shiro能干嘛? 认证,授权,加密,回话管理,与web集成,缓存. 三,对应的API Authentication:身份认证/登录 Authorizatio ...
- shiro 单点登录_Shiro权限管理框架(一):Shiro的基本使用
其实关于Shiro的一些学习笔记很早就该写了,因为懒癌和拖延症晚期一直没有落实,直到今天公司的一个项目碰到了在集群环境的单点登录频繁掉线的问题,为了解决这个问题,Shiro相关的文档和教程没少翻.最后 ...
- shiro 同时实现url和按钮的拦截_Shiro权限管理框架(一):Shiro的基本使用
其实关于Shiro的一些学习笔记很早就该写了,因为懒癌和拖延症晚期一直没有落实,直到今天公司的一个项目碰到了在集群环境的单点登录频繁掉线的问题,为了解决这个问题,Shiro相关的文档和教程没少翻.最后 ...
- Shiro学习笔记_02:shiro的认证+shiro的授权
Shiro 学习笔记 本文基于B站UP主[编程不良人]视频教程[2020最新版Shiro教程,整合SpringBoot项目实战教程]进行整理记录,仅用于个人学习交流使用. 视频链接:https://w ...
- shiro学习系列:shiro自定义filter过滤器
shiro学习系列:shiro自定义filter过滤器 自定义JwtFilter的hierarchy(层次体系) 上代码 package com.finn.springboot.common.conf ...
- 细说shiro之一:shiro简介
细说shiro之一:shiro简介 官网:https://shiro.apache.org/ 一. Shiro是什么 Shiro是一个Java平台的开源权限框架,用于认证和访问授权.具体来说,满足对如 ...
- Shiro安全(四):Shiro权限绕过之Shiro-782
Shiro安全(四):Shiro权限绕过之Shiro-782 0x00 前言 0x01 前置知识 0x02 漏洞环境 0x03 漏洞利用 0x04 漏洞原理 Shiro层面绕过 Spring层面绕过 ...
最新文章
- 用大数据分析顾客会掏钱买你哪件商品
- linux下oracle自启动
- php登录框注入,分享一个php的防火墙,拦截SQL注入和xss
- JDBC连接池JDBCTemplate课堂笔记
- 下一代大数据即时分析架构--IOTA架构
- Codeforces Round #539 Div. 1
- LintCode MySQL 1932/1933. 挂科最多的同学 I / II
- 论文浅尝 | Learning with Noise: Supervised Relation Extraction
- 带你自学Python系列(十七):Python中类的用法(三)
- 二选一数据选择器2-1 MUX
- PCS7服务器数据包安装位置,PCS7中应用PH服务器的配置问题
- 面向对象程序设计概念
- windows XP 搭建asp运行环境
- 小米手机 root权限 获取
- termux python 打开摄像头_python+opencv 电脑调用手机的摄像头
- RK3066 遥控器调试流程
- cat6 万兆_干货:CAT5E超五类、CAT6和CAT6A超六类布线系统性能和应用上的区别
- 金山毒霸把我的oracle监听服务,金山毒霸误杀我的i_eyes.exe
- “网红”白鸦创立6年的有赞,为何不敌同样诞生于微信生态3年的拼多多?
- 大小写26个英文字母对应的ASCII值
热门文章
- Elasticsearch(7.0.0) percolate termQuery 不好使 (type:text default analyzer)
- C++实现的简单k近邻算法(K-Nearest-Neighbour,K-NN)
- Linux系统安装与使用基础之第二篇熟悉Linux操作系统
- TZT3826E静态信号测试分析系统
- 如何还原恢复格式化后的数据文件?
- 坐标转换 四参数/七参数/正形变换 ∈ C# 编程笔记
- 网址大放松 让网络一族网上过个新年(转)
- P3 元宝第三天的笔记
- R语言中的cor和cov
- msp心形16个闪灯c语言程序,心形流水灯程序