身份验证

 

身份验证,即在应用中谁能证实他就是他本人。通常提供如他们的身份ID一些标识信息来代表他就是他本人,如提供身份证,用户名/密码来证实。java

在shiro中,用户须要提供principals (身份)和credentials(证实)给shiro,从而应用能验证用户身份:mysql

principals:身份,即主体的标识属性,能够是任何东西,如用户名、邮箱等,惟一便可。一个主体能够有多个principals,但只有一个Primary principals,通常是用户名/密码/手机号。git

credentials:证实/凭证,即只有主体知道的安全值,如密码/数字证书等。github

最多见的principals和credentials组合就是用户名/密码了。接下来先进行一个基本的身份认证。web

 

另外两个相关的概念是以前提到的SubjectRealm,分别是主体及验证主体的数据源。sql

 

2.2  环境准备

本文使用Maven构建,所以须要一点Maven知识。首先准备环境依赖: 数据库

Java代码  收藏代码apache

  1. <dependencies>  
  2.     <dependency>  
  3.         <groupId>junit</groupId>  
  4.         <artifactId>junit</artifactId>  
  5.         <version>4.9</version>  
  6.     </dependency>  
  7.     <dependency>  
  8.         <groupId>commons-logging</groupId>  
  9.         <artifactId>commons-logging</artifactId>  
  10.         <version>1.1.3</version>  
  11.     </dependency>  
  12.     <dependency>  
  13.         <groupId>org.apache.shiro</groupId>  
  14.         <artifactId>shiro-core</artifactId>  
  15.         <version>1.2.2</version>  
  16.     </dependency>  
  17. </dependencies>   

添加junit、common-logging及shiro-core依赖便可。api

 

2.3  登陆/退出

一、首先准备一些用户身份/凭据(shiro.ini)缓存

Java代码  收藏代码

  1. [users]  
  2. zhang=123  
  3. wang=123  

此处使用ini配置文件,经过[users]指定了两个主体:zhang/12三、wang/123。

  

二、测试用例(com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest) 

Java代码  收藏代码

  1. @Test  
  2. public void testHelloworld() {  
  3.     //一、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager  
  4.     Factory<org.apache.shiro.mgt.SecurityManager> factory =  
  5.             new IniSecurityManagerFactory("classpath:shiro.ini");  
  6.     //二、获得SecurityManager实例 并绑定给SecurityUtils  
  7.     org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();  
  8.     SecurityUtils.setSecurityManager(securityManager);  
  9.     //三、获得Subject及建立用户名/密码身份验证Token(即用户身份/凭证)  
  10.     Subject subject = SecurityUtils.getSubject();  
  11.     UsernamePasswordToken token = new UsernamePasswordToken("zhang""123");  
  12.   
  13.     try {  
  14.         //四、登陆,即身份验证  
  15.         subject.login(token);  
  16.     } catch (AuthenticationException e) {  
  17.         //五、身份验证失败  
  18.     }  
  19.   
  20.     Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登陆  
  21.   
  22.     //六、退出  
  23.     subject.logout();  
  24. }  
  25.    

2.一、首先经过new IniSecurityManagerFactory并指定一个ini配置文件来建立一个SecurityManager工厂;

2.二、接着获取SecurityManager并绑定到SecurityUtils,这是一个全局设置,设置一次便可;

2.三、经过SecurityUtils获得Subject,其会自动绑定到当前线程;若是在web环境在请求结束时须要解除绑定;而后获取身份验证的Token,如用户名/密码;

2.四、调用subject.login方法进行登陆,其会自动委托给SecurityManager.login方法进行登陆;

2.五、若是身份验证失败请捕获AuthenticationException或其子类,常见的如: DisabledAccountException(禁用的账号)、LockedAccountException(锁定的账号)、UnknownAccountException(错误的账号)、ExcessiveAttemptsException(登陆失败次数过多)、IncorrectCredentialsException (错误的凭证)、ExpiredCredentialsException(过时的凭证)等,具体请查看其继承关系;对于页面的错误消息展现,最好使用如“用户名/密码错误”而不是“用户名错误”/“密码错误”,防止一些恶意用户非法扫描账号库;

2.六、最后能够调用subject.logout退出,其会自动委托给SecurityManager.logout方法退出。

 

从如上代码可总结出身份验证的步骤:

一、收集用户身份/凭证,即如用户名/密码;

二、调用Subject.login进行登陆,若是失败将获得相应的AuthenticationException异常,根据异常提示用户错误信息;不然登陆成功;

三、最后调用Subject.logout进行退出操做。

 

如上测试的几个问题:

一、用户名/密码硬编码在ini配置文件,之后须要改为如数据库存储,且密码须要加密存储;

二、用户身份Token可能不只仅是用户名/密码,也可能还有其余的,如登陆时容许用户名/邮箱/手机号同时登陆。 

 

2.4  身份认证流程

流程以下:

一、首先调用Subject.login(token)进行登陆,其会自动委托给Security Manager,调用以前必须经过SecurityUtils. setSecurityManager()设置;

二、SecurityManager负责真正的身份验证逻辑;它会委托给Authenticator进行身份验证;

三、Authenticator才是真正的身份验证者,Shiro API中核心的身份认证入口点,此处能够自定义插入本身的实现;

四、Authenticator可能会委托给相应的AuthenticationStrategy进行多Realm身份验证,默认ModularRealmAuthenticator会调用AuthenticationStrategy进行多Realm身份验证;

五、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接口以下: 

Java代码  收藏代码

  1. String getName(); //返回一个惟一的Realm名字  
  2. boolean supports(AuthenticationToken token); //判断此Realm是否支持此Token  
  3. AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)  
  4.  throws AuthenticationException;  //根据Token获取认证信息  

 

Realm配置

一、自定义Realm实现(com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1):  

Java代码  收藏代码

  1. public class MyRealm1 implements Realm {  
  2.     @Override  
  3.     public String getName() {  
  4.         return "myrealm1";  
  5.     }  
  6.     @Override  
  7.     public boolean supports(AuthenticationToken token) {  
  8.         //仅支持UsernamePasswordToken类型的Token  
  9.         return token instanceof UsernamePasswordToken;   
  10.     }  
  11.     @Override  
  12.     public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  13.         String username = (String)token.getPrincipal();  //获得用户名  
  14.         String password = new String((char[])token.getCredentials()); //获得密码  
  15.         if(!"zhang".equals(username)) {  
  16.             throw new UnknownAccountException(); //若是用户名错误  
  17.         }  
  18.         if(!"123".equals(password)) {  
  19.             throw new IncorrectCredentialsException(); //若是密码错误  
  20.         }  
  21.         //若是身份认证验证成功,返回一个AuthenticationInfo实现;  
  22.         return new SimpleAuthenticationInfo(username, password, getName());  
  23.     }  
  24. }   

 

二、ini配置文件指定自定义Realm实现(shiro-realm.ini)  

Java代码  收藏代码

  1. #声明一个realm  
  2. myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1  
  3. #指定securityManager的realms实现  
  4. securityManager.realms=$myRealm1   

经过$name来引入以前的realm定义

 

三、测试用例请参考com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testCustomRealm测试方法,只须要把以前的shiro.ini配置文件改为shiro-realm.ini便可。

 

Realm配置

一、ini配置文件(shiro-multi-realm.ini)  

Java代码  收藏代码

  1. #声明一个realm  
  2. myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1  
  3. myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2  
  4. #指定securityManager的realms实现  
  5. securityManager.realms=$myRealm1,$myRealm2   

securityManager会按照realms指定的顺序进行身份认证。此处咱们使用显示指定顺序的方式指定了Realm的顺序,若是删除“securityManager.realms=$myRealm1,$myRealm2”,那么securityManager会按照realm声明的顺序进行使用(即无需设置realms属性,其会自动发现),当咱们显示指定realm后,其余没有指定realm将被忽略,如“securityManager.realms=$myRealm1”,那么myRealm2不会被自动设置进去。

 

二、测试用例请参考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使用

一、数据库及依赖

Java代码  收藏代码

  1. <dependency>  
  2.     <groupId>mysql</groupId>  
  3.     <artifactId>mysql-connector-java</artifactId>  
  4.     <version>5.1.25</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>com.alibaba</groupId>  
  8.     <artifactId>druid</artifactId>  
  9.     <version>0.2.23</version>  
  10. </dependency>   

本文将使用mysql数据库及druid链接池; 

 

二、到数据库shiro下建三张表:users(用户名/密码)、user_roles(用户/角色)、roles_permissions(角色/权限),具体请参照shiro-example-chapter2/sql/shiro.sql;并添加一个用户记录,用户名/密码为zhang/123;

 

三、ini配置(shiro-jdbc-realm.ini) 

Java代码  收藏代码

  1. jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm  
  2. dataSource=com.alibaba.druid.pool.DruidDataSource  
  3. dataSource.driverClassName=com.mysql.jdbc.Driver  
  4. dataSource.url=jdbc:mysql://localhost:3306/shiro  
  5. dataSource.username=root  
  6. #dataSource.password=  
  7. jdbcRealm.dataSource=$dataSource  
  8. securityManager.realms=$jdbcRealm   

一、变量名=全限定类名会自动建立一个类实例

二、变量名.属性=值 自动调用相应的setter方法进行赋值

三、$变量名 引用以前的一个对象实例 

四、测试代码请参照com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testJDBCRealm方法,和以前的没什么区别。

 

2.6  Authenticator及AuthenticationStrategy

Authenticator的职责是验证用户账号,是Shiro API中身份验证核心的入口点: 

Java代码  收藏代码

  1. public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)  
  2.             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不一样的是返回时的身份变了;

 

一、ini配置文件(shiro-authenticator-all-success.ini) 

Java代码  收藏代码

  1. #指定securityManager的authenticator实现  
  2. authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator  
  3. securityManager.authenticator=$authenticator  
  4.   
  5. #指定securityManager.authenticator的authenticationStrategy  
  6. allSuccessfulStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategy  
  7. securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy  

Java代码  收藏代码

  1. myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1  
  2. myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2  
  3. myRealm3=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm3  
  4. securityManager.realms=$myRealm1,$myRealm3  

 

二、测试代码(com.github.zhangkaitao.shiro.chapter2.AuthenticatorTest)

2.一、首先通用化登陆逻辑 

Java代码  收藏代码

  1. private void login(String configFile) {  
  2.     //一、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager  
  3.     Factory<org.apache.shiro.mgt.SecurityManager> factory =  
  4.             new IniSecurityManagerFactory(configFile);  
  5.   
  6.     //二、获得SecurityManager实例 并绑定给SecurityUtils  
  7.     org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();  
  8.     SecurityUtils.setSecurityManager(securityManager);  
  9.   
  10.     //三、获得Subject及建立用户名/密码身份验证Token(即用户身份/凭证)  
  11.     Subject subject = SecurityUtils.getSubject();  
  12.     UsernamePasswordToken token = new UsernamePasswordToken("zhang""123");  
  13.   
  14.     subject.login(token);  
  15. }  

 

2.二、测试AllSuccessfulStrategy成功:    

Java代码  收藏代码

  1. @Test  
  2. public void testAllSuccessfulStrategyWithSuccess() {  
  3.     login("classpath:shiro-authenticator-all-success.ini");  
  4.     Subject subject = SecurityUtils.getSubject();  
  5.   
  6.     //获得一个身份集合,其包含了Realm验证成功的身份信息  
  7.     PrincipalCollection principalCollection = subject.getPrincipals();  
  8.     Assert.assertEquals(2, principalCollection.asList().size());  
  9. }   

即PrincipalCollection包含了zhang和zhang@163.com身份信息。

 

2.三、测试AllSuccessfulStrategy失败:

Java代码  收藏代码

  1.     @Test(expected = UnknownAccountException.class)  
  2.     public void testAllSuccessfulStrategyWithFail() {  
  3.         login("classpath:shiro-authenticator-all-fail.ini");  
  4.         Subject subject = SecurityUtils.getSubject();  
  5. }   

shiro-authenticator-all-fail.ini与shiro-authenticator-all-success.ini不一样的配置是使用了securityManager.realms=$myRealm1,$myRealm2;即myRealm验证失败。

 

对于AtLeastOneSuccessfulStrategy和FirstSuccessfulStrategy的区别,请参照testAtLeastOneSuccessfulStrategyWithSuccess和testFirstOneSuccessfulStrategyWithSuccess测试方法。惟一不一样点一个是返回全部验证成功的Realm的认证信息;另外一个是只返回第一个验证成功的Realm的认证信息。

 

自定义AuthenticationStrategy实现,首先看其API:

Java代码  收藏代码

  1. //在全部Realm验证以前调用  
  2. AuthenticationInfo beforeAllAttempts(  
  3. Collection<? extends Realm> realms, AuthenticationToken token)   
  4. throws AuthenticationException;  
  5. //在每一个Realm以前调用  
  6. AuthenticationInfo beforeAttempt(  
  7. Realm realm, AuthenticationToken token, AuthenticationInfo aggregate)   
  8. throws AuthenticationException;  
  9. //在每一个Realm以后调用  
  10. AuthenticationInfo afterAttempt(  
  11. Realm realm, AuthenticationToken token,   
  12. AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t)  
  13. throws AuthenticationException;  
  14. //在全部Realm以后调用  
  15. AuthenticationInfo afterAllAttempts(  
  16. AuthenticationToken token, AuthenticationInfo aggregate)   
  17. throws AuthenticationException;   

由于每一个AuthenticationStrategy实例都是无状态的,全部每次都经过接口将相应的认证信息传入下一次流程;经过如上接口能够进行如合并/返回第一个验证成功的认证信息。

 

自定义实现时通常继承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy便可,具体能够参考代码com.github.zhangkaitao.shiro.chapter2.authenticator.strategy包下OnlyOneAuthenticatorStrategy 和AtLeastTwoAuthenticatorStrategy。

 

到此基本的身份验证就搞定了,对于AuthenticationToken 、AuthenticationInfo和Realm的详细使用后续章节再陆续介绍。

 

示例源代码:https://github.com/zhangkaitao/shiro-example;可加群134755960探讨Spring/Shiro技术。