接着上一篇來說,我直接把上一篇的代碼複製過來
package com.study.shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
public class Test_shiro {
@Test
public void testLogin() throws Exception{
// 1.創建SecurityManager工廠對象,加載配置文件,創建
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通過工廠對象,創建Securitymanage對象
SecurityManager securityManager = factory.getInstance();
// 3.將securitymanage綁定到當前運行環境中,讓系統隨時隨地的都可以訪問securityManager對象
SecurityUtils.setSecurityManager(securityManager);
// 4:創建當前登錄的主體,注意;此時主體沒有經過認證
Subject subject = SecurityUtils.getSubject();
// 5:綁定主體登錄的身份、憑證,即賬號密碼
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","123");
try {
// 6.主體登錄
subject.login(token);
}catch (IncorrectCredentialsException incorrectCredentialsException){
System.out.println("密碼錯誤!");
}catch (UnknownAccountException UnknownAccountException){
System.out.println("用戶名錯誤!");
}
// 7:判斷是否登錄成功
System.out.println("驗證是否登錄1:" + subject.isAuthenticated());
// 8:登出
subject.logout();
System.out.println("驗證是否登錄2:" + subject.isAuthenticated());
}
}
當頁面把需要驗證的用戶名,密碼傳入到後臺後
通過org.apache.shiro.authc.UsernamePasswordToken;生成token;
// 5:綁定主體登錄的身份、憑證,即賬號密碼
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","123");
然後調用subject的login方法。
subject.logout();
我採用debug方式走了下。首先是進入logout()方法:
我們繼續走,
進入下面的方法,繼續走
我們再進入這個doAuthenticate方法看看
最後判斷了這個集合的大小等於一的時候進入doSingleReamAuthentication方法,傳入集合的第一個realm,和token。
看看傳入的realm裏面有什麼
總的看
1.調用subject.login()方法進行登錄,其會自動委託給securityManager.login方法進行登錄;
2.security通過Authenticator(認證器)進行認證;
3.Authenticator的實現ModularReamAuthenticator調用realm從ini配置文件取用戶真實的賬號和密碼,這裏使用的是iniRealm(shiro自帶,相當於數據源);
4.IniRealm先根據token中的賬號去ini中找賬號,如果找不到則給ModularRealmAuthenticator返回null,如果找到匹配密碼,匹配密碼成功則認證通過;
5.最後通用Subject.logout 進行退出操作。