1.什麼情況下需要用到驗證策略?
當有多個Realm時,就需要根據自己的需求來提供相應的驗證策略.
2.shiro有哪些驗證策略?
(1)FirstSuccessfulStrategy 只要有一個驗證成功即可,返回第一個驗證成功的Realm的身份信息,其他的忽略
(2)AtLeastOneSuccessfulStrategy 只要有一個 Realm 驗證成功即可,和 FirstSuccessfulStrategy 不同,返回所有 Realm 身份驗證成功的認證信息
(3)AllSuccessfulStrategy 所有的驗證成功纔算成功,並返回所有驗證成功的身份信息。
3.看shiro.ini配置(配置兩個Realm)
[main]
myRealm1=com.mymaven.shirotest01.myRealm1
myRealm2=com.mymaven.shirotest01.myRealm2
securityManager.realms=$myRealm1,$myRealm2
#指定securityManager的authenticator的實現
authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
#注入認證策略
authenticationStrategy=org.apache.shiro.authc.pam.FirstSuccessfulStrategy
authenticator.authenticationStrategy=$authenticationStrategy
#注入securityManager.authenticator的認證策略
securityManager.authenticator.authenticationStrategy=$authenticationStrategy
4.自定義的Realm類(myRealm1和myRealm2的代碼差不多,就貼一個就行了)
public class myRealm1 implements Realm{
//獲取token的認證信息
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String name = (String) token.getPrincipal(); //得到用戶名
String password = new String((char[])token.getCredentials()); //得到密碼
//相當於和從數據庫中查詢來的用戶名比較
if(!"zhang".equals(name)){
throw new UnknownAccountException(); //用戶名錯誤
}
//相當於和從數據庫中查詢來的密碼比較
if(!"123".equals(password)){
throw new IncorrectCredentialsException(); //密碼錯誤
}
return new SimpleAuthenticationInfo(name, password,getName());
}
//返回唯一的Realm的名字
public String getName() {
return "myRealm";
}
//判斷Realm是否支持token
public boolean supports(AuthenticationToken token) {
//僅支持UsernamePasswordToken類型的token
return token instanceof UsernamePasswordToken;
}
}
5.test類跟前面文章一樣