Spring Boot学习之Shiro
文章目录
零 全部源码地址
一 Shiro简介
- Apache Shiro 是一个Java 的安全(权限)框架。
- Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
- Shiro官网
1.1 Shiro功能
功能 | 说明 |
---|---|
Authentication | 身份认证、登录,验证用户是不是拥有相应的身份; |
Authorization | 授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否进行某些操作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限 |
Session Manager | 会话管理,即用户登录后就是第一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通的JavaSE环境,也可以是Web环境; |
Cryptography | 加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储; |
Web Support | Web支持,可以非常容易的集成到Web环境; |
Caching | 缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高效率 |
Concurrency | Shiro支持多线程应用的并发验证,即,如在一个线程中开启另一个线程,能把权限自动的传播过去 |
Testing | 提供测试支持; |
Run As | 允许一个用户假装为另一个用户(如果他们允许)的身份进行访问; |
Remember Me | 记住登录功能,即一次登录后,下次再来的话不用登录 |
1.2 Shiro架构(外部视角)
-
从应用程序角度来观察如何使用shiro完成工作
-
subject:
- 应用代码直接交互的对象是Subject【Shiro的对外API核心就是Subject】
- 与当前应用交互的任何东西都是Subject,与Subject的所有交互都会委托给SecurityManager
- Subject其实是一个门面,SecurityManageer 才是实际的执行者
-
SecurityManager
- 安全管理器,即所有与安全有关的操作都会与SercurityManager交互,并且它管理着所有的Subject。
- 它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC的DispatcherServlet的角色
-
Realm
- Shiro从Realm获取安全数据(如用户,角色,权限)
- SecurityManager 要验证用户身份,需要从Realm 获取相应的用户进行比较,来确定用户的身份是否合法;也需要从Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行
- 可以把Realm看成DataSource。
1.3 Shiro架构(内部视角)
组件名称 | 说明 |
---|---|
Subject | 任何可以与应用交互的 ‘用户’; |
Security Manager | Shiro的心脏,所有具体的交互都通过Security Manager进行控制,它管理者所有的Subject,且负责进行认证,授权,会话,及缓存的管理。 |
Authenticator | 负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略(Authentication Strategy) |
Authorizer | 授权器【访问控制器】用来决定主体是否有权限进行相应的操作【即控制着用户能访问应用中的那些功能】 |
Realm | 可以有一个或者多个的realm,可以认为是安全实体数据源【即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm】 |
SessionManager | 管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的JavaSE环境中 |
CacheManager | 缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能; |
Cryptography | 密码模块,Shiro 提供了一些常见的加密组件用于密码加密,解密 |
二 Shiro快速入门
2.1 演示代码&部分源码解读
-
创建一个maven工程删掉不必要的东西
-
根据官方文档,我们来导入Shiro的依赖
<dependencies> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-coreartifactId> <version>1.4.1version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>jcl-over-slf4jartifactId> <version>1.7.21version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>1.7.21version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>1.2.17version> dependency>dependencies>
-
编写Shiro配置
- log4j.properties
log4j.rootLogger=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache librarieslog4j.logger.org.apache=WARN# Springlog4j.logger.org.springframework=WARN# Default Shiro logginglog4j.logger.org.apache.shiro=INFO# Disable verbose logginglog4j.logger.org.apache.shiro.util.ThreadContext=WARNlog4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
- shiro.ini
[users]# user 'root' with password 'secret' and the 'admin' roleroot = secret, admin# user 'guest' with the password 'guest' and the 'guest' roleguest = 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
-
编写QuickStrat
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;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); // 获取当前的对象 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!"); } //all done - log out!退出 currentUser.logout(); // 结束 System.exit(0); }}
-
测试结果
2023-01-27 17:35:00,334 INFO [org.apache.shiro.session.mgt.AbstractValidatingSessionManager] - Enabling session validation scheduler... 2023-01-27 17:35:00,712 INFO [Quickstart] - Retrieved the correct value! [aValue] 2023-01-27 17:35:00,713 INFO [Quickstart] - User [lonestarr] logged in successfully. 2023-01-27 17:35:00,713 INFO [Quickstart] - May the Schwartz be with you! 2023-01-27 17:35:00,713 INFO [Quickstart] - You may use a lightsaber ring. Use it wisely. 2023-01-27 17:35:00,714 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun! 进程已结束,退出代码0
三 Spring Boot集成Shio
3.0 准备操作
-
搭建一个SpringBoot项目、选中web模块
-
导入Maven依赖 thymeleaf
<dependency> <groupId>org.thymeleafgroupId> <artifactId>thymeleaf-spring5artifactId> dependency> <dependency> <groupId>org.thymeleaf.extrasgroupId> <artifactId>thymeleaf-extras-java8timeartifactId> dependency>
-
编写一个页面 index.html
DOCTYPE html><html lang="en"xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Titletitle>head><body><h1>首页h1><p th:text="${msg}">p>body>html>
-
编写controller进行访问测试
import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class MyController {@RequestMapping({"/","/index"})public String toIndex(Model model){model.addAttribute("msg","hello,Shiro");return "index";}}
3.1 整合Shiro
-
导入Shiro 和 spring整合的依赖
<dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-springartifactId> <version>1.9.1version> dependency>
-
编写Shiro 配置类 【config包下】
import org.springframework.context.annotation.Configuration;//声明为配置类@Configurationpublic class ShiroConfig {//创建 ShiroFilterFactoryBean//创建 DefaultWebSecurityManager//创建 realm 对象}
-
先创建一个 realm 对象
- 需要自定义一个 realm 的类,用来编写一些查询的方法,或者认证与授权的逻辑
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;//自定义Realmpublic class UserRealm extends AuthorizingRealm {//执行授权逻辑@Overrideprotected AuthorizationInfodoGetAuthorizationInfo(PrincipalCollection principals) {System.out.println("执行了=>授权逻辑PrincipalCollection");return null;}//执行认证逻辑@Overrideprotected AuthenticationInfodoGetAuthenticationInfo(AuthenticationToken token) throwsAuthenticationException {System.out.println("执行了=>认证逻辑AuthenticationToken");return null;}}
-
将这个类注册到Bean中【ShiroConfig中】
@Configurationpublic class ShiroConfig {//创建 ShiroFilterFactoryBean//创建 DefaultWebSecurityManager//创建 realm 对象@Beanpublic UserRealm userRealm(){return new UserRealm();}}
-
创建
DefaultWebSecurityManager
//创建 ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBeangetShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();//设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);return shiroFilterFactoryBean;}
-
ShiroConfig
全部代码//声明为配置类@Configurationpublic class ShiroConfig {//创建 ShiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBeangetShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();//设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);return shiroFilterFactoryBean;}//创建 DefaultWebSecurityManager@Bean(name = "securityManager")public DefaultWebSecurityManagergetDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();//关联RealmsecurityManager.setRealm(userRealm);return securityManager;}//创建 realm 对象@Beanpublic UserRealm userRealm(){return new UserRealm();}}
3.2 页面拦截实现
-
编写两个页面、在templates目录下新建一个 user 目录
add.html update.html
<body><h1>addh1>body>
<body><h1>updateh1>body>
-
编写跳转到页面的controller
@RequestMapping("/user/add")public String toAdd(){return "user/add";}@RequestMapping("/user/update")public String toUpdate(){return "user/update";}
-
在index页面上,增加跳转链接
<a th:href="@{/user/add}">adda> <hr/> <a th:href="@{/user/update}">updatea>
-
添加Shiro的内置过滤器
@Beanpublic ShiroFilterFactoryBeangetShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();//设置安全管理器shiroFilterFactoryBean.setSecurityManager(securityManager);Map<String,String> filterMap = new LinkedHashMap<String, String>();filterMap.put("/user/add","authc");filterMap.put("/user/update","authc");shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);return shiroFilterFactoryBean;}
-
编写自定义Login页面
DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>logintitle> 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> <button type="submit">登录button> p> form> body>html>
-
编写跳转的controller
@RequestMapping("/toLogin")public String toLogin(){return "login";}
-
在shiro中配置
//shiroFilterFactoryBean@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); //设置安全管理器 bean.setSecurityManager(defaultWebSecurityManager); //添加shiro的内置过滤器 filterMap.put("/user@Data@NoArgsConstructor@AllArgsConstructor@Alias("User")public class User { private int id; private String name; private String pwd; private String perms;}
-
编写Mapper接口
import com.yang.pojo.User;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;@Repository@Mapperpublic interface UserMapper { public User queryUserByName(String name);}
-
编写Mapper配置文件
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.yang.mapper.UserMapper"> <select id="queryUserByName" parameterType="String" resultType="User"> select * from user where name = #{name} select>mapper>
-
编写UserService 层
import com.yang.pojo.User;public interface UserService { public User queryUserByName(String name);}
import com.yang.mapper.UserMapper;import com.yang.pojo.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper; @Override public User queryUserByName(String name) { return userMapper.queryUserByName(name); }}
-
测试
import com.yang.service.UserService;import com.yang.service.UserServiceImpl;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass ShiroSpringbootApplicationTests { @Autowired UserServiceImpl userService; @Test void contextLoads() { System.out.println(userService.queryUserByName("小明")); }}
-
改造UserRealm
- 连接到数据库进行真实的操作
import com.yang.pojo.User;import com.yang.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.session.Session;import org.apache.shiro.subject.PrincipalCollection;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;//自定义UserRealmpublic class UserRealm extends AuthorizingRealm { @Autowired 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 currentPrincipal = (User)subject.getPrincipal();//拿到user对象 //设置当前用户的权限,从数据库中查询而来 info.addStringPermission(currentPrincipal.getPerms()); return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthorizationInfo"); UsernamePasswordToken userToken=(UsernamePasswordToken) token; //连接真实数据库 User user = userService.queryUserByName(userToken.getUsername()); if(user==null) { return null;//抛出异常 UnknownAccountException } //为了完美,我们在用户登录后应该把信息放到Session中,我们完善下!在执行认证逻辑时候,加入session Subject currentSubject = SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute("loginUser",user); //第一个参数类型principal 当事人;首要的;最主要的 将user对象传递给上面的授权操作 return new SimpleAuthenticationInfo(user,user.getPwd(),""); }}
3.5 用户授权操作
- 使用shiro的过滤器来拦截请求
- 在 ShiroFilterFactoryBean 中添加一个过滤器
//授权过滤器filterMap.put("/user/add","perms[user:add]"); //大家记得注意顺序!
- 当我们实现权限拦截后,shiro会自动跳转到未授权的页面
-
配置一个未授权的提示的页面,增加一个controller提示
@RequestMapping("/noauth")@ResponseBodypublic String noAuth(){return "未经授权不能访问此页面";}
-
在shiroFilterFactoryBean 中配置一个未授权的请求页面
shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
3.6 Shiro授权
- 在UserRealm 中添加授权的逻辑,增加授权的字符串
//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了=>授权doGetAuthorizationInfo"); //给资源进行授权 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //添加资源的授权字符串 //info.addStringPermission("user:add");//硬编码 //拿到当前登录的这个对象 Subject subject = SecurityUtils.getSubject(); User currentPrincipal = (User)subject.getPrincipal();//拿到user对象 //设置当前用户的权限,从数据库中查询而来 info.addStringPermission(currentPrincipal.getPerms()); return info;}
- 在过滤器中,将 update 请求也进行权限拦截下
//拦截LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();//授权 正常情况下,没有授权会跳转到未授权页面filterMap.put("/user/add","perms[user:add]");filterMap.put("/user/update","perms[user:update]");
3.7 整合thymeleaf
- 添加maven依赖
<dependency> <groupId>com.github.theborakompanionigroupId> <artifactId>thymeleaf-extras-shiroartifactId> <version>2.1.0version> dependency>
- 配置一个shiro的Dialect ,在shiro的配置中增加一个Bean
//配置ShiroDialect:方言,用于整合thymeleaf和shiro // 用于 thymeleaf 和 shiro 标签配合使用 @Bean public ShiroDialect getShiroDialect(){ return new ShiroDialect(); }
- 修改前端的配置
<div shiro:hasPermission="user:add"><a th:href="@{/user/add}">adda>div><div shiro:hasPermission="user:update"><a th:href="@{/user/update}">updatea>div>
- 在执行认证逻辑时候,加入session
//为了完美,在用户登录后应该把信息放到Session中,我们完善下!在执行认证逻辑时候,加入session Subject currentSubject = SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute("loginUser",user);
- 前端从session中获取,然后用来判断是否显示登录
<p th:if="${session.loginUser==null}"><a th:href="@{/toLogin}">登录a>p>
3.8 效果展示
来源地址:https://blog.csdn.net/yang2330648064/article/details/128771569
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341