1. 程式人生 > >Apache shiro叢集實現 (三)shiro身份認證(Shiro Authentication)

Apache shiro叢集實現 (三)shiro身份認證(Shiro Authentication)

<span style="font-size:18px;">package com.api6.shiro.demo1;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
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.Assert;
import org.junit.Test;
public class ShiroSimpleTest {
	private static Log log = LogFactory.getLog(ShiroSimpleTest.class);
	 	@Test
	    public void testLogin() {
	 		//1.獲取SecurityManager工廠,載入shiro.Ini配置檔案初始化SecurityManager
	 		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
	 		//2.獲取SecurityManager例項
	 		SecurityManager securityManager = factory.getInstance();
	 		//3.將SecurityManager例項,繫結到SecurityUtils。
	 		SecurityUtils.setSecurityManager(securityManager);
	 		
	 		//4.使用最常見的使用者名稱密碼的方式,建立token
	 		UsernamePasswordToken token = new UsernamePasswordToken("zhao", "111");
	 		//5.設定記住我
	 		token.setRememberMe(true);
	 		//6.獲取Subject物件
	 		Subject currentUser = SecurityUtils.getSubject();
	 		
	 		try {
	 			//7.傳入上一步驟建立的token物件,登入,即進行身份驗證操作。
		 		currentUser.login(token);
	 			} catch ( UnknownAccountException uae ) { 
	 				//使用者名稱未知...
	 				log.info("使用者不存在");
	 			} catch ( IncorrectCredentialsException ice ) {
	 				//憑據不正確,例如密碼不正確 ...
	 				log.info("密碼不正確");
	 			} catch ( LockedAccountException lae ) { 
	 				//使用者被鎖定,例如管理員把某個使用者禁用...
	 				log.info("使用者被禁用");
	 			} catch ( ExcessiveAttemptsException eae ) {
	 				//嘗試認證次數多餘系統指定次數 ...
	 				log.info("請求次數過多,使用者被鎖定");
	 			} catch ( AuthenticationException ae ) {
	 			//其他未指定異常
	 				log.info("未知錯誤,無法完成登入");
	 			}
	 			//未丟擲異常,程式正常向下執行。
	 			Assert.assertEquals(true, currentUser.isAuthenticated());
	    }
}</span>