Authentication(验证)机制:
1.获取提交识别属性(用户名……)与验证属性(密码……)。
2.实现验证过程。
3.验证成功通过,不成功返回。
一、获取信息案例:
//Example using most common scenario of username/password pair:
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//”Remember Me” built-in:
token.setRememberMe(true);
案例用到常见的用户名/密码验证机制,UsernamePasswordToken是 org.apache.shiro.authc.AuthenticationToken接口的实现类。AuthenticationToken接口是实现验证的基础接口,且与信息获取过程无关。
本例的setRememberMe(true)方法表示,Shiro启动记忆模块。
二、验证过程案例:
Subject currentUser = SecurityUtils.getSubject();
currentUser.login(token);
案例调用login方法对用户信息进行有效性验证。
三、返回结果案例:
try {
currentUser.login(token);
} catch ( UnknownAccountException uae ) { ...
} catch ( IncorrectCredentialsException ice ) { ...
} catch ( LockedAccountException lae ) { ...
} catch ( ExcessiveAttemptsException eae ) { ...
} ... catch your own ...
} catch ( AuthenticationException ae ) {
//unexpected error?
}
//No problems, continue on as expected...
验证成功,可以进行下一步操作;验证失败,Shiro提供了不同层级的验证失败返回结果集。
Remembered和Authenticated
Remembered:已记住,系统记忆用户信息,查看敏感信息时仍需验证。
Authenticated:已验证,系统已验证,拥有用户所有权限。
Layout案例
currentUser.logout(); //removes all identifying information and invalidates their session too.
案例中调用Shiro的logout方法来退出,Shiro将删除用户保存信息,包括相关Session,但不包含cookie。cookie是保存在本地的内容,所以Shiro的建议是在退出重定向时完成cookie的清理。
Authentication的内部实现过程
![](http://shiro.apache.org/assets/images/ShiroAuthenticationSequence.png)
1.应用调用subject的login方法请求验证;
2.subject初始化,授权securityManager,调用securityManager的login方法验证,验证正式开始;
3.securityManager接收到subject的信息和授权,调用内部Authenticator的authenticator(token)方法。多数情况下,这里就是ModularRealmAuthenticator的验证,可以拥有多个,也可以是一个。
4.如果ModularRealmAuthenticator有多个,则会自动开启一个AuthenticationStrategy。
5.每个配置的Relam都会去匹配条件,如果符合,则调用Relam的getAuthenticationInfo方法。
Authenticator
单一Relam案例:
[main]
...
authenticator = com.foo.bar.CustomAuthenticator
securityManager.authenticator = $authenticator
可以自定义Relam。
AuthenticationStrategy
是一个Shiro内置的Relam管理容器,当拥有多个Relam时,需要由它来管理。主要的作用就是将验证状态进行整合处理。
AuthenticationStrategy是一个无状态的组件,验证时产生四次尝试:
1.在所有Relam执行之前;
2.在每个Relam的 getAuthenticationInfo方法执行之前;
3.在每个Relam的 getAuthenticationInfo方法执行之后;
4.在所有Relam执行之后。
AuthenticationStrategy有三种实现处理类:
1.AtLeastOneSuccessfulStrategy 至少一个成功,即是成功。全部失败,则失败。
2.FirstSuccessfulStrategy 第一个成功,则成功,其余忽略。
3.AllSuccessfulStrategy 全部成功则成功,否则失败。
默认情况下,是按第一种情况处理。定制案例(shiro.ini):
[main]
...
authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy
...
如需实现自定义的AuthenticationStrategy,则需要实现org.apache.shiro.authc.pam.AbstractAuthenticationStrategy,这个类会自动捆绑聚合Relam返回的结果集。
Relam的处理顺序与其引用的顺序一致,案例:
blahRealm = com.company.blah.Realm
...
fooRealm = com.company.foo.Realm
...
barRealm = com.company.another.Realm
securityManager.realms = $fooRealm, $barRealm, $blahRealm
...
案例中blahRelam将在最后进行匹配执行。在此处进行relam引用,相当于在代码中,对realms赋值,所以不需要在代码中进行另外的处理。与别的配置方式不同的是,此处如果定义多个Relam,但是只引用一个的话,验证时只会处理一个Relam。