Shiro学习总结(3)——Apache Shiro身份认证
身份验证,即在应用中谁能证明他就是他本人。一般提供如他们的身份ID一些标识信息来表明他就是他本人,如提供身份证,用户名/密码来证明。
在shiro中,用户需要提供principals (身份)和credentials(证明)给shiro,从而应用能验证用户身份:
principals:身份,即主体的标识属性,可以是任何东西,如用户名、邮箱等,唯一即可。一个主体可以有多个principals,但只有一个Primary principals,一般是用户名/密码/手机号。
credentials:证明/凭证,即只有主体知道的安全值,如密码/数字证书等。
最常见的principals和credentials组合就是用户名/密码了。接下来先进行一个基本的身份认证。
另外两个相关的概念是之前提到的Subject及Realm,分别是主体及验证主体的数据源。
2.2 环境准备
本文使用Maven构建,因此需要一点Maven知识。首先准备环境依赖:
- </version>
- </version>
- </dependency>
- </dependencies>
添加junit、common-logging及shiro-core依赖即可。
2.3 登录/退出
1、首先准备一些用户身份/凭据(shiro.ini)
此处使用ini配置文件,通过[users]指定了两个主体:zhang/123、wang/123。
2、测试用例(com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest)
- @Test
- public void testHelloworld() {
- //1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
- Factory<org.apache.shiro.mgt.SecurityManager> factory =
- new IniSecurityManagerFactory("classpath:shiro.ini");
- //2、得到SecurityManager实例 并绑定给SecurityUtils
- org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
- SecurityUtils.setSecurityManager(securityManager);
- //3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
- Subject subject = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
- try {
- //4、登录,即身份验证
- subject.login(token);
- } catch (AuthenticationException e) {
- //5、身份验证失败
- }
- Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录
- //6、退出
- subject.logout();
- }
2.1、首先通过new IniSecurityManagerFactory并指定一个ini配置文件来创建一个SecurityManager工厂;
2.2、接着获取SecurityManager并绑定到SecurityUtils,这是一个全局设置,设置一次即可;
2.3、通过SecurityUtils得到Subject,其会自动绑定到当前线程;如果在web环境在请求结束时需要解除绑定;然后获取身份验证的Token,如用户名/密码;
2.4、调用subject.login方法进行登录,其会自动委托给SecurityManager.login方法进行登录;
2.5、如果身份验证失败请捕获AuthenticationException或其子类,常见的如: DisabledAccountException(禁用的帐号)、LockedAccountException(锁定的帐号)、UnknownAccountException(错误的帐号)、ExcessiveAttemptsException(登录失败次数过多)、IncorrectCredentialsException (错误的凭证)、ExpiredCredentialsException(过期的凭证)等,具体请查看其继承关系;对于页面的错误消息展示,最好使用如“用户名/密码错误”而不是“用户名错误”/“密码错误”,防止一些恶意用户非法扫描帐号库;
2.6、最后可以调用subject.logout退出,其会自动委托给SecurityManager.logout方法退出。
从如上代码可总结出身份验证的步骤:
1、收集用户身份/凭证,即如用户名/密码;
2、调用Subject.login进行登录,如果失败将得到相应的AuthenticationException异常,根据异常提示用户错误信息;否则登录成功;
3、最后调用Subject.logout进行退出操作。
如上测试的几个问题:
1、用户名/密码硬编码在ini配置文件,以后需要改成如数据库存储,且密码需要加密存储;
2、用户身份Token可能不仅仅是用户名/密码,也可能还有其他的,如登录时允许用户名/邮箱/手机号同时登录。
2.4 身份认证流程

流程如下:
1、首先调用Subject.login(token)进行登录,其会自动委托给Security Manager,调用之前必须通过SecurityUtils. setSecurityManager()设置;
2、SecurityManager负责真正的身份验证逻辑;它会委托给Authenticator进行身份验证;
3、Authenticator才是真正的身份验证者,Shiro API中核心的身份认证入口点,此处可以自定义插入自己的实现;
4、Authenticator可能会委托给相应的AuthenticationStrategy进行多Realm身份验证,默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证;
5、Authenticator会把相应的token传入Realm,从Realm获取身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处可以配置多个Realm,将按照相应的顺序及策略进行访问。
2.5 Realm
Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。如我们之前的ini配置方式将使用org.apache.shiro.realm.text.IniRealm。
org.apache.shiro.realm.Realm接口如下:
- String getName(); //返回一个唯一的Realm名字
- boolean supports(AuthenticationToken token); //判断此Realm是否支持此Token
- AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
- throws AuthenticationException; //根据Token获取认证信息
单Realm配置
1、自定义Realm实现(com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1):
- public class MyRealm1 implements Realm {
- @Override
- public String getName() {
- return "myrealm1";
- }
- @Override
- public boolean supports(AuthenticationToken token) {
- //仅支持UsernamePasswordToken类型的Token
- return token instanceof UsernamePasswordToken;
- }
- @Override
- public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- String username = (String)token.getPrincipal(); //得到用户名
- String password = new String((char[])token.getCredentials()); //得到密码
- if(!"zhang".equals(username)) {
- throw new UnknownAccountException(); //如果用户名错误
- }
- if(!"123".equals(password)) {
- throw new IncorrectCredentialsException(); //如果密码错误
- }
- //如果身份认证验证成功,返回一个AuthenticationInfo实现;
- return new SimpleAuthenticationInfo(username, password, getName());
- }
- }
2、ini配置文件指定自定义Realm实现(shiro-realm.ini)
- #声明一个realm
- myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
- #指定securityManager的realms实现
- securityManager.realms=$myRealm1
通过$name来引入之前的realm定义
3、测试用例请参考com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testCustomRealm测试方法,只需要把之前的shiro.ini配置文件改成shiro-realm.ini即可。
多Realm配置
1、ini配置文件(shiro-multi-realm.ini)
- #声明一个realm
- myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
- myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2
- #指定securityManager的realms实现
- securityManager.realms=$myRealm1,$myRealm2
securityManager会按照realms指定的顺序进行身份认证。此处我们使用显示指定顺序的方式指定了Realm的顺序,如果删除“securityManager.realms=$myRealm1,$myRealm2”,那么securityManager会按照realm声明的顺序进行使用(即无需设置realms属性,其会自动发现),当我们显示指定realm后,其他没有指定realm将被忽略,如“securityManager.realms=$myRealm1”,那么myRealm2不会被自动设置进去。
2、测试用例请参考com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testCustomMultiRealm测试方法。
Shiro默认提供的Realm

以后一般继承AuthorizingRealm(授权)即可;其继承了AuthenticatingRealm(即身份验证),而且也间接继承了CachingRealm(带有缓存实现)。其中主要默认实现如下:
org.apache.shiro.realm.text.IniRealm:[users]部分指定用户名/密码及其角色;[roles]部分指定角色即权限信息;
org.apache.shiro.realm.text.PropertiesRealm: user.username=password,role1,role2指定用户名/密码及其角色;role.role1=permission1,permission2指定角色及权限信息;
org.apache.shiro.realm.jdbc.JdbcRealm:通过sql查询相应的信息,如“select password from users where username = ?”获取用户密码,“select password, password_salt from users where username = ?”获取用户密码及盐;“select role_name from user_roles
where username = ?”获取用户角色;“select permission from roles_permissions where role_name = ?”获取角色对应的权限信息;也可以调用相应的api进行自定义sql;
JDBC Realm使用
1、数据库及依赖
- </version>
- </version>
- </dependency>
本文将使用MySQL数据库及druid连接池;
2、到数据库shiro下建三张表:users(用户名/密码)、user_roles(用户/角色)、roles_permissions(角色/权限),具体请参照shiro-example-chapter2/sql/shiro.sql;并添加一个用户记录,用户名/密码为zhang/123;
3、ini配置(shiro-jdbc-realm.ini)
- jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
- dataSource=com.alibaba.druid.pool.DruidDataSource
- dataSource.driverClassName=com.mysql.jdbc.Driver
- dataSource.url=jdbc:mysql://localhost:3306/shiro
- dataSource.username=root
- #dataSource.password=
- jdbcRealm.dataSource=$dataSource
- securityManager.realms=$jdbcRealm
1、变量名=全限定类名会自动创建一个类实例
2、变量名.属性=值 自动调用相应的setter方法进行赋值
3、$变量名 引用之前的一个对象实例
4、测试代码请参照com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testJDBCRealm方法,和之前的没什么区别。
2.6 Authenticator及AuthenticationStrategy
Authenticator的职责是验证用户帐号,是Shiro API中身份验证核心的入口点:
- public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)
- throws AuthenticationException;
如果验证成功,将返回AuthenticationInfo验证信息;此信息中包含了身份及凭证;如果验证失败将抛出相应的AuthenticationException实现。
SecurityManager接口继承了Authenticator,另外还有一个ModularRealmAuthenticator实现,其委托给多个Realm进行验证,验证规则通过AuthenticationStrategy接口指定,默认提供的实现:
FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功的认证信息,其他的忽略;
AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份验证成功的认证信息;
AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
ModularRealmAuthenticator默认使用AtLeastOneSuccessfulStrategy策略。
假设我们有三个realm:
myRealm1: 用户名/密码为zhang/123时成功,且返回身份/凭据为zhang/123;
myRealm2: 用户名/密码为wang/123时成功,且返回身份/凭据为wang/123;
myRealm3: 用户名/密码为zhang/123时成功,且返回身份/凭据为zhang@163.com/123,和myRealm1不同的是返回时的身份变了;
1、ini配置文件(shiro-authenticator-all-success.ini)
- #指定securityManager的authenticator实现
- authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
- securityManager.authenticator=$authenticator
- #指定securityManager.authenticator的authenticationStrategy
- allSuccessfulStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategy
- securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy
- myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
- myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2
- myRealm3=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm3
- securityManager.realms=$myRealm1,$myRealm3
2、测试代码(com.github.zhangkaitao.shiro.chapter2.AuthenticatorTest)
2.1、首先通用化登录逻辑
- private void login(String configFile) {
- //1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
- Factory<org.apache.shiro.mgt.SecurityManager> factory =
- new IniSecurityManagerFactory(configFile);
- //2、得到SecurityManager实例 并绑定给SecurityUtils
- org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
- SecurityUtils.setSecurityManager(securityManager);
- //3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
- Subject subject = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
- subject.login(token);
- }
2.2、测试AllSuccessfulStrategy成功:
- , principalCollection.asList().size());
- }
即PrincipalCollection包含了zhang和zhang@163.com身份信息。
2.3、测试AllSuccessfulStrategy失败:
- @Test(expected = UnknownAccountException.class)
- public void testAllSuccessfulStrategyWithFail() {
- login("classpath:shiro-authenticator-all-fail.ini");
- Subject subject = SecurityUtils.getSubject();
- }
shiro-authenticator-all-fail.ini与shiro-authenticator-all-success.ini不同的配置是使用了securityManager.realms=$myRealm1,$myRealm2;即myRealm验证失败。
对于AtLeastOneSuccessfulStrategy和FirstSuccessfulStrategy的区别,请参照testAtLeastOneSuccessfulStrategyWithSuccess和testFirstOneSuccessfulStrategyWithSuccess测试方法。唯一不同点一个是返回所有验证成功的Realm的认证信息;另一个是只返回第一个验证成功的Realm的认证信息。
自定义AuthenticationStrategy实现,首先看其API:
- //在所有Realm验证之前调用
- AuthenticationInfo beforeAllAttempts(
- Collection<? extends Realm> realms, AuthenticationToken token)
- throws AuthenticationException;
- //在每个Realm之前调用
- AuthenticationInfo beforeAttempt(
- Realm realm, AuthenticationToken token, AuthenticationInfo aggregate)
- throws AuthenticationException;
- //在每个Realm之后调用
- AuthenticationInfo afterAttempt(
- Realm realm, AuthenticationToken token,
- AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t)
- throws AuthenticationException;
- //在所有Realm之后调用
- AuthenticationInfo afterAllAttempts(
- AuthenticationToken token, AuthenticationInfo aggregate)
- throws AuthenticationException;
因为每个AuthenticationStrategy实例都是无状态的,所有每次都通过接口将相应的认证信息传入下一次流程;通过如上接口可以进行如合并/返回第一个验证成功的认证信息。
自定义实现时一般继承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy即可,具体可以参考代码com.github.zhangkaitao.shiro.chapter2.authenticator.strategy包下OnlyOneAuthenticatorStrategy 和AtLeastTwoAuthenticatorStrategy。
到此基本的身份验证就搞定了,对于AuthenticationToken 、AuthenticationInfo和Realm的详细使用后续章节再陆续介绍。
Shiro学习总结(3)——Apache Shiro身份认证的更多相关文章
- Shiro学习笔记总结,附加" 身份认证 "源码案例(一)
Shiro学习笔记总结 内容介绍: 一.Shiro介绍 二.subject认证主体 三.身份认证流程 四.Realm & JDBC reaml介绍 五.Shiro.ini配置介绍 六.源码案例 ...
- [shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证
本文地址:http://blog.csdn.net/sushengmiyan/article/details/39933993 shiro官网:http://shiro.apache.org/ shi ...
- 【shiro】shiro学习笔记1 - 初识shiro
[TOC] 认证流程 st=>start: Start e=>end: End op1=>operation: 构造SecurityManager环境 op2=>operati ...
- 【Shiro】三、Apache Shiro认证
配置好并获取到SecurityManager,代表Shiro正常运行起来了,可以使用Shiro的其它功能. 1.认证流程(API的使用流程) 认证的数据: Principals:标识 ·识别Subje ...
- Shiro学习(一)——Shiro简介
Apache Shiro是Java的一个安全框架.目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可能没有Spring Security做的功能强大 ...
- shiro学习(四、shiro集成spring+springmvc)
依赖:spring-context,spring-MVC,shiro-core,shiro-spring,shiro-web 实话实说:web.xml,spring,springmvc配置文件好难 大 ...
- 【Shiro】二、Apache Shiro配置
1.配置 使用配置获得SecurityManager,SecurityManager是核心,配置好并获取到SecurityManager,Shiro就算正式运行起来了. 两种方式:通过ini文件:通过 ...
- 【Shiro】一、Apache Shiro简介
一.Apache Shiro简介 1.简介 一个安全性框架 特点:功能丰富.使用简单.运行独立 核心功能: Authentication(认证):你是谁? Authorization(授权):谁能干什 ...
- Shiro报错-[org.apache.shiro.mgt.AbstractRememberMeManager] - There was a failure while trying to retrieve remembered principals.
2017-04-08 11:55:33,010 WARN [org.apache.shiro.mgt.AbstractRememberMeManager] - There was a failure ...
- Shiro学习(21)授予身份及切换身份
在一些场景中,比如某个领导因为一些原因不能进行登录网站进行一些操作,他想把他网站上的工作委托给他的秘书,但是他不想把帐号/密码告诉他秘书,只是想把工作委托给他:此时和我们可以使用Shiro的RunAs ...
随机推荐
- 基于Verilog语言的可维护性设计技术
[注]本文内容主体部分直接翻译参考文献[1]较多内容,因此本文不用于任何商业目的,也不会发表在任何学术刊物上,仅供实验室内部交流和IC设计爱好者交流之用. “曲意而使人喜,不若直节而使人忌:无善而致人 ...
- spring xml配置文件根元素(文件头文件)说明
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- MVC:一个View显示多个Model(多个Model你可以使用ViewBag或ViewData , 或者:Model["myInfo"] as)
MVC:一个View显示多个Model 多个Model你可以使用ViewBag或ViewData , 或者:Model["myInfo"] as. 比如: Tuple<str ...
- cf 865 B. Ordering Pizza
B. Ordering Pizza It's another Start[c]up finals, and that means there is pizza to order for the ons ...
- Linux 桌面的 Dock 类程序
1.Cairo-Dock是一个Dock类软件,它支持OpenGL.提供动画及视觉效果的插件.新的Applet.重写配置面板.新增主题等功能. 2.Docky是从GNOME Do项目剥离出来的一个Doc ...
- js中split,splice,slice方法之间的差异。
首先我们先来林格斯双击翻译一下: split 劈开, 使分裂: splice 接合; 使结合: slice 切成薄片, 切: 我先是这么区分的:这三个方法最后一个字母是t的是字符串方法,是e的 ...
- angularjs input使用ng-model双向绑定无效bug解决
一.问题描述 当我们给input双向绑定变量的时候,使用ng-model有时候会出现无效的情况 二.解决办法 将绑定的变量写成对象的形式 控制器定义变量: $scope.inputText = {va ...
- Redis 数据持久化的方案的实现
原文:Redis 数据持久化的方案的实现 版权声明:m_nanle_xiaobudiu https://blog.csdn.net/m_nanle_xiaobudiu/article/details/ ...
- Linux学习总结(5)——CentOS常用的目录文件操作命令
CentOS常用的目录文件操作命令 一.路径操作的CentOS常用命令 cd pwd NO1. 显示当前路径 [root@rehat root]# pwd NO2. 返回用户主目录 [roo ...
- redis练习手册<二>快速入门
Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案. Redis从它的许多竞争继承来的三个主要特点: Redis数据库完全在内存中,使用磁盘仅用 ...