SpringBoot12-Shiro
Shiro
12.1概述
12.1.1简介
Apache Shiro是一个强大且易用的Java安全框架
可以完成身份验证、授权、密码和会话管理
Shiro 不仅可以用在 JavaSE 环境中,也可以用在 JavaEE 环境中
官网: http://shiro.apache.org/
12.1.2 功能
Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的;
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
Web Support:Web支持,可以非常容易的集成到Web环境;
Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率;
Concurrency:shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
Testing:提供测试支持;
Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
12.1.3从外部看
应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是Subject;其每个API的含义:
Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者;
SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过SpringMVC,你可以把它看成DispatcherServlet前端控制器;
Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。
也就是说对于我们而言,最简单的一个Shiro应用:
- 应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
- 我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断。
从以上也可以看出,Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入
12.1.4外部架构
Subject:主体,可以看到主体可以是任何可以与应用交互的“用户”;
SecurityManager:相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理。
Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
Realm:可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;
SessionManager:如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器);
SessionDAO:DAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能;
CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的
12.1.5认证流程
用户 提交 身份信息、凭证信息 封装成 令牌 交由 安全管理器 认证
12.2. 快速入门
将案例拷贝:
按照官网提示找到 快速入门案例
GitHub地址:shiro/samples/quickstart/
从GitHub 的文件中可以看出这个快速入门案例是一个 Maven 项目
1.新建一个 Maven 工程,删除其 src 目录,将其作为父工程
2.在父工程中新建一个 Maven 模块
复制快速入门案例 POM.xml 文件中的依赖 (版本号自选)
把快速入门案例中的 resource 下的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
复制一下 shiro.ini
文件
ok需要下载ini插件,如果在setting中无法下载,就去官网下载对应版本的然后导入
12.2.1.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
导入quickstart.java
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);}
}
执行一下main方法:
12.2.2. 分析案例
先分析一些方法混个脸熟
1.通过 SecurityUtils 获取当前执行的用户 Subject
Subject currentUser = SecurityUtils.getSubject();
2.通过 当前用户拿到 Session,shiro的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.logout();
全部代码:
/*** @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);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);}
}
12.3Springboot集成Shiro
-
在刚刚的父项目中新建一个 springboot 模块
-
导入 SpringBoot 和 Shiro 整合包的依赖
<!--SpringBoot 和 Shiro 整合包--><!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring-boot-web-starter</artifactId><version>1.6.0</version></dependency>
下面是编写配置文件
Shiro 三大要素subject -> ShiroFilterFactoryBean ----当前用户
securityManager -> DefaultWebSecurityManager ----管理所有用户
Realm
实际操作中对象创建的顺序 : realm -> securityManager -> subject ----连接数据 -
创建config文件,编写UserRealm.java继承AuthorizingRealm并实现方法
public class UserRealm extends AuthorizingRealm {//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了授权方法");return null;}//认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {System.out.println("执行了认证方法");return null;} }
可以两个方法的功能主要实现了授权和认证,我们添加两个输出一会看看效果
-
在Config文件夹下编写ShiroConfig.java文件,将三大Bean注入到spring中
①根据前面提供的顺序,先编写realm类:
//1:创建realm对象,需要自定义 @Bean(name = "userRealm") public UserRealm userRealm(){return new UserRealm(); }
②创建用户管理,这里需要用到前面创建的realm,因此在realm之后进行编写
//2:创建管理用户需要用到 @Bean public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setRealm(userRealm);return securityManager;}
图示解析:
③创建subject,需要传入一个securityManager,因此最后进行编写(是不是很像套娃)
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean subject = new ShiroFilterFactoryBean();//设置安全管理器bean.setSecurityManager(securityManager);return subject;
}
12.3.1搭建简单测试环境
- 新建一个登录页面
- 新建一个首页
首页上有三个链接,一个登录,一个增加用户,一个删除用户 - 新建一个增加用户页面
- 新建一个删除用户页面
- 编写对应的 Controller
12.3.2实现登录拦截
//添加shiro的内置过滤器/**anon:无需认证就可以访问authc:必须认证才可访问user:必须拥有 记住我才能用perms:拥有对某个资源的权限才能访问role:拥有某个角色权限才能访问**/@Beanpublic ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//设置安全管理器bean.setSecurityManager(securityManager);Map<String, String> filterMap =new LinkedHashMap<String,String>();filterMap.put("/user/add","anon");//表示/user/add这个请求所有人可以访问filterMap.put("/user/update","authc");//表示/user/update这个请求只有登录后可以访问bean.setLoginUrl("/toLogin");bean.setFilterChainDefinitionMap(filterMap);return bean;}
图示解析:
当然在拦截请求中也支持通配符:如拦截指定/user下的所有请求:/user/*
12.3.3实现用户认证
实现用户认证需要去realm类的认证方法中去配置
这里我们先把用户名和密码写死,实际中是要去数据库中去取的
去到UserRealm.java中
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了认证方法");String name="root";String password="123456";UsernamePasswordToken userToken = (UsernamePasswordToken)token;if(!userToken.getUsername().equals(name)){return null;}return new SimpleAuthenticationInfo("",password,"");}
编写Controller中的登录方法:
@RequestMapping("/login")public String login(@RequestParam("username") String username,@RequestParam("password") String password,Model model) {//获取当前的用户Subject subject = SecurityUtils.getSubject();//封装用户的登录数据UsernamePasswordToken token = new UsernamePasswordToken(username, password);try {subject.login(token);//执行登录的方法,如果没有异常return "index";} catch (UnknownAccountException e) {model.addAttribute("msg", "用户名错误");return "login";} catch (IncorrectCredentialsException e) {model.addAttribute("msg", "密码错误");return "login";}}
图示解析:
12.3.4Shiro整合Mybatis
1.首先导入需要的所有的mavem依赖
①mysql-connect ②druid ③log4j ④mybtis-spring-boot-starter
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.22</version>
</dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.21</version>
</dependency>
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
2.编写配置文件application.properties或者application.yaml
3.编写guo文件下的pojo,controller,service,mapper文件夹参考前面的springboot整合mybatis代码哦!
整合完毕的文件目录:
在mapper中添加了一个queryUserByName的方法:
整合完毕后先去测试类中进行测试:
测试结果:
ok到目前为止整合完毕,没有问题,业务都是正常的接下来去之前的用户认证把之前写死的用户改为数据库中的用户
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了认证方法");UsernamePasswordToken userToken = (UsernamePasswordToken)token;User user = userService.queryUserByName(userToken.getUsername());if(user==null){return null;}return new SimpleAuthenticationInfo("",user.getPwd(),"");}
测试一下bingo搞定
12.3.5授权功能的实现
去到ShiroConfig.java中,添加代码,注意要添加在(顺序)
filterMap.put("/user/add","perms[user:add]");
之后我们执行I一下发现登陆后add标签也无权访问
!
当然正常的是要访问无权限页面的
接下来我们去UserRealm中给添加权限,注意不要导错类SimpleAuthorizationInfo
@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了授权方法");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermission("user:add");return info;}
诶,接下来所有用户就都有这个权限了
但是不想让所有用户都有某个权限要怎么实现呢?
首先先去数据表中添加一个权限字段
紧接着去pojo中添加字段,再去手动添加一些用户的权限
ok数据层完毕,接下来要思考,我们想要获取到用户的权限,但是获取用户是在刚刚认证中通过userservice获取的,
在认证里面查到的东西我们怎么放到授权中去呢?
想到了两个:①session ②用户当前对象的属性来取get方法或(点属性)
我们在认证中,最后new了一个SimpleAuthenticationInfo的当前认证对象,之前里面要传递三个参数分别为:
(资源,密码,realmName)
我们把获取到的user传入到资源中去。
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
这样一来,user这个资源就传递到了当前用户subject整体资源中,通过当前subject获取资源来获取到这个user
所以在授权的功能中要先获取subject当前用户
Subject subject = SecurityUtils.getSubject();
然后通过subject获取到资源
User currentUser = (User) subject.getPrincipal();
再给当前用户添加user中对应的权限名,注意方法名是addStringPermission
权限
info.addStringPermission(currentUser.getPerms());
最后返回当前权限info
整体授权代码:
//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了授权方法");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();Subject subject = SecurityUtils.getSubject();User currentUser = (User) subject.getPrincipal();//设置当前用户的权限info.addStringPermission(currentUser.getPerms());return info;}
退出功能就和之前security的logout一样,设置一下退出的路径就可
好现在基本需求都完了,但是想和之前security一样实现没有权限的就不要显示,就需要和thymeleaf结合
12.3.6Shiro和thymeleaf整合
首先要导入shrio和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>
ok接下来就要去前端页面编写标签了,之前在security中用到的是sec,这里用的shiro,当然也要导入命名空间
下面是spring-security的命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
shiro的:
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
前端代码:
<p th:text="${msg}"></p>
<hr>
<a><a th:href="@{/toLogin}">登录</a>
<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>
解释一下就是判断一下当前的用户是否有当前的权限,如果有则显示,没有不显示
登录按钮无权限时显示:
<div shiro:notAuthenticated><a th:href="@{/toLogin}">登录</a>
</div>