Shiro主要功能有认证,受权,加密,会话管理,与Web集成,缓存等. java
新建一个简单的Maven项目,咱们只是使用Junit和shiro-core包.POM最后是以下代码: sql
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.credo</groupId> <artifactId>shiro-study</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version> </dependency> </dependencies> </project>
package org.credo.test; import junit.framework.Assert; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.junit.Test; public class TestHelloShiro { public static final String DEFAULT_INI_RESOURCE_PATH = "classpath:shiro.ini"; @Test public void TestShiroFirst() { // 使用ini文件方式实例化shiro IniSecurityManagerFactory. IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory(DEFAULT_INI_RESOURCE_PATH<span></span>); // 获得SecurityManager实例 并绑定给SecurityUtils SecurityManager securityManager = securityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); //获得Subject Subject shiroSubject = SecurityUtils.getSubject(); //建立用户名/密码身份验证Token(即用户身份/凭证) UsernamePasswordToken normalToken = new UsernamePasswordToken("credo", "123"); try { //登陆,进行身份验证 shiroSubject.login(normalToken); } catch (Exception e) { //登陆失败,打印出错误信息,可自定义 System.out.println(e.getMessage()); } //断言登陆成功 Assert.assertEquals(true, shiroSubject.isAuthenticated()); //登出 shiroSubject.logout(); } }
shiro.ini文件经过[users]指定了两个user:credo/12三、zhaoqian/123,: 数据库
1
2
3
|
[users]
credo=123
zhaoqian=123
|
从外部观察shiro,shiro的结构就是 外部代码--->Subject---->SecurityManager---->Realm apache
知识点: 设计模式
今后咱们就能够理解shiro的处理流程. api
咱们能够更进一步理解,Realm的数据是怎么来的?固然是咱们本身定义的,也就是说,咱们须要本身定义权限,角色,受权方面的数据资源(数据库存储或shiro.ini文件存储). 缓存
shiro的Factory<SecurityManager>是一个工厂模式的应用.咱们追溯源码能够看到其内部的实现. 安全
Factory最底层接口:org.apache.shiro.util.Factory.class app
package org.apache.shiro.util; //应用工厂设计模式的泛型接口 public interface Factory<T> { //返回一个实例 T getInstance(); }
Factory接口声明的getInstance()方法,由其直接子类AbstractFactory实现。
以后AbstractFactory在实现的getInstance()方法中调用了一个新声明的抽象方法,这个方法也是由其直接子类实现的。
这样,从Factory开始,每一个子类都实现父类声明的抽象方法,同时又声明一个新的抽象方法并在实现父类的方法中调用。 框架
经过源码追溯,咱们能够发现有2个类是实现了Factory接口:
接着是org.apache.shiro.config.IniFactorySupport,抽象类public abstract class IniFactorySupport<T> extends AbstractFactory<T>
最终是package org.apache.shiro.config包下的IniSecurityManagerFactory.
IniSecurityManagerFactory类主要是用工厂模式建立基于Ini配置SecurityManager实例.
IniSecurityManagerFactory 是 Factory的子类,DefaultSecurityManager是 SecurityManager的子类。
Factory 与 SecurityManager 及其子类的关系
从上图能够看到整个Shiro的认证流程
一、首先调用Subject.login(token)进行登陆,其会自动委托给Security Manager,调用以前必须经过SecurityUtils. setSecurityManager()设置;Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它须要从Realm获取相应的用户进行比较以肯定用户身份是否合法;也须要从Realm获得用户相应的角色/权限进行验证用户是否能进行操做;能够把Realm当作DataSource,即安全数据源。如咱们以前的ini配置方式将使用org.apache.shiro.realm.text.IniRealm。
org.apache.shiro.realm.Realm接口以下:
1
2
3
|
String getName();//返回一个惟一的Realm名字
booleansupports(AuthenticationToken token);//判断此Realm是否支持此Token
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)throwsAuthenticationException; //根据Token获取认证信息
|
1.咱们先定义一个Realm.
package org.credo.test.realm.single; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.realm.Realm; public class TestMySingleRealm implements Realm{ @Override public String getName() { return "TestMySingleReam"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } @Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName=String.valueOf(token.getPrincipal()); //注意token的Credentials是char[],z主要转换. String passWord=String.valueOf((char[])token.getCredentials()); if(!userName.equals("credo")){ throw new UnknownAccountException("无效的帐户名!"); } if(!passWord.equals("aaa")){ throw new IncorrectCredentialsException("密码错误!"); } return new SimpleAuthenticationInfo(userName, passWord,getName()); } }
2.ini配置文件指定自定义Realm实现(文件名我定义为:shiro-single-realm.ini)
1
2
|
singleRealm=org.credo.test.realm.single.TestMySingleRealm
securityManager.realms=$singleRealm
|
经过$name来引入以前的realm定义
3.Junit测试代码
@Test public void testSingleMyRealm() { IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro-single-realm.ini"); SecurityManager securityManager = securityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject shiroSubject = SecurityUtils.getSubject(); UsernamePasswordToken normalToken = new UsernamePasswordToken("credo", "aaa"); try { shiroSubject.login(normalToken); } catch (UnknownAccountException e) { System.out.println(e.getMessage()); } catch (IncorrectCredentialsException e) { System.out.println(e.getMessage()); } catch (AuthenticationException e) { e.printStackTrace(); } Assert.assertEquals(true, shiroSubject.isAuthenticated()); shiroSubject.logout(); //解除绑定Subject到线程,防止对下次测试形成影响 ThreadContext.unbindSubject(); }
realm A:
package org.credo.test.realm.multi; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.realm.Realm; public class RealmA implements Realm { @Override public String getName() { return "RealmA"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } @Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName=String.valueOf(token.getPrincipal()); //注意token的Credentials是char[],z主要转换. String passWord=String.valueOf((char[])token.getCredentials()); System.out.println("realm A"); if(!userName.equals("credo")){ throw new UnknownAccountException("RealmA--无效的帐户名!"); } if(!passWord.equals("123")){ throw new IncorrectCredentialsException("RealmA--密码错误!"); } System.out.println("pass A"); return new SimpleAuthenticationInfo(userName, passWord,getName()); } }
realmB:
package org.credo.test.realm.multi; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.realm.Realm; public class RealmB implements Realm { @Override public String getName() { return "RealmsB"; } @Override public boolean supports(AuthenticationToken token) { return token instanceof UsernamePasswordToken; } @Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName=String.valueOf(token.getPrincipal()); //注意token的Credentials是char[],z主要转换. String passWord=String.valueOf((char[])token.getCredentials()); System.out.println("realm B"); if(!userName.equals("credo")){ throw new UnknownAccountException("RealmB--无效的帐户名!"); } if(!passWord.equals("aaa")){ throw new IncorrectCredentialsException("RealmB--密码错误!"); } System.out.println("pass B"); return new SimpleAuthenticationInfo(userName, passWord,getName()); } }
@Test public void testMultiMyRealm() { IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro-multi-realm.ini"); SecurityManager securityManager = securityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject shiroSubject = SecurityUtils.getSubject(); UsernamePasswordToken normalToken = new UsernamePasswordToken("credo", "aaa"); try { shiroSubject.login(normalToken); } catch (UnknownAccountException e) { System.out.println(e.getMessage()); } catch (IncorrectCredentialsException e) { System.out.println(e.getMessage()); } catch (AuthenticationException e) { System.out.println(e.getMessage()); } Assert.assertEquals(true, shiroSubject.isAuthenticated()); shiroSubject.logout(); ThreadContext.unbindSubject(); }
测试结果能够发现,只要其中一个realm经过就经过了.执行顺序是按shiro.ini中指定的顺序执行.先A后B.若是有realmC,realmD,但没有指定,不会执行.
之后通常继承AuthorizingRealm(受权)便可;其继承了AuthenticatingRealm(即身份验证),并且也间接继承了CachingRealm(带有缓存实现)。其中主要默认实现以下:
Authenticator的职责是验证用户账号,是Shiro API中身份验证核心的入口点:
package org.apache.shiro.authc; public interface Authenticator { /** * @throws AuthenticationException if there is any problem during the authentication process. * See the specific exceptions listed below to as examples of what could happen * in order to accurately handle these problems and to notify the user in an * appropriate manner why the authentication attempt failed. Realize an * implementation of this interface may or may not throw those listed or may * throw other AuthenticationExceptions, but the list shows the most common ones. * @see ExpiredCredentialsException * @see IncorrectCredentialsException * @see ExcessiveAttemptsException * @see LockedAccountException * @see ConcurrentAccessException * @see UnknownAccountException */ public AuthenticationInfo authenticate(AuthenticationToken authenticationToken) throws AuthenticationException; }
ModularRealmAuthenticator默认使用AtLeastOneSuccessfulStrategy策略。
自定义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便可
测试案例:
修改shiro.ini
authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator securityManager.authenticator=$authenticator allSuccessfulStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategy securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy realmA=org.credo.test.realm.multi.RealmA realmB=org.credo.test.realm.multi.RealmB securityManager.realms=$realmA,$realmB
RealmB的getAuthenticationInfo方法返回值修改成:return new SimpleAuthenticationInfo(userName+"@qq.com", passWord,getName());
其余不变,RealmA也不变.但验证过程用户名和密码都写正确的"credo","123"
@Test public void testAuthenticator() { IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro-multi-realm.ini"); SecurityManager securityManager = securityManagerFactory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject shiroSubject = SecurityUtils.getSubject(); UsernamePasswordToken normalToken = new UsernamePasswordToken("credo", "aaa"); try { shiroSubject.login(normalToken); } catch (UnknownAccountException e) { System.out.println(e.getMessage()); } catch (IncorrectCredentialsException e) { System.out.println(e.getMessage()); } catch (AuthenticationException e) { System.out.println(e.getMessage()); } // 获得一个PrincipalCollection,包含全部成功的. PrincipalCollection principalCollection = shiroSubject.getPrincipals(); for(Object obj:principalCollection){ System.out.println(obj.toString()); } Assert.assertEquals(2, principalCollection.asList().size()); Assert.assertEquals(true, shiroSubject.isAuthenticated()); shiroSubject.logout(); } @After public void tearDown() throws Exception { ThreadContext.unbindSubject(); }
1
2
3
4
5
6
|
realm A
pass A
realm B
pass B
credo
credo@qq.com
|
包含credo和credo@qq.com,两个都经过了验证.都有两个信息.
学习资料参考以及部分文章的Copy: