1. 程式人生 > >Shiro入門6:自定義realm查詢資料庫進行認證

Shiro入門6:自定義realm查詢資料庫進行認證

在學習自定義Realm的時候很多人都會有這個問題:

為什麼要用Realm?自定義Realm有什麼作用?

將來實際開發需要realm從資料庫查詢資訊

Realm是什麼?

關於Realm的作用及解釋,


如何實現Realm?

實現AuthorizingRealm【一般自定義Realm實現這個類】

CustomRealm.java

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 自定義Realm
 * @author CatScan
 *
 */
public class CustomRealm extends AuthorizingRealm{
	final String realmName="customRealm";
	
	
	//設定realmName
	@Override
	public void setName(String name) {
		super.setName(realmName);
	}
	
	
	
	//用於認證
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		// 第一步從token中取出使用者傳送過來的身份資訊
 		String str = (String) token.getPrincipal();
		
		//第二步根據使用者輸入的帳號從資料庫查詢
		//...
		String pwd = "11111";
		
		
		//如果查詢不到返回null
		//如果查詢到,返回認證資訊:AuthenticationInfo
		
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(str, pwd, this.getName());
		
		return simpleAuthenticationInfo;
	}

	
	
	//用於授權
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		return null;
	}
}


需要什麼配置ini檔案?

需要在shiro-realm.ini中配置realm注入到SecurityManager中

shiro-realm.ini

[main]

#自定義realm
customRealm = cn.marer.shiro.realm.CustomRealm

#將realm設定到securityManager,相當於Spring中的注入
securityManager.realms = $customRealm


測試方法

下面這個只是測試方法,在這裡我就不發詳細的測試類了,測試類裡面有上一章節我發過的Shiro的HelloWorld,還是使用Junit測試。

//自定義realm
	@Test
	public void testCustomRealm(){
		//建立securityManager工廠,通過Ini配置檔案建立securityManager工廠
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
		
		//建立SecurityManager
		SecurityManager sm = factory.getInstance();
		
		//將securityManager設定到當前的環境中
		SecurityUtils.setSecurityManager(sm);
		
		//從SecurityUtils裡面建立一個subject
		Subject subject = SecurityUtils.getSubject();
		
		//在認證提交前,需要準備token(令牌)
		//這裡的將來的使用者和密碼是由使用者輸入進去的
		UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "11111");
		
		try {
			//執行認證提交
			subject.login(token);
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		
		//是否認證通過
		boolean isAuthenticated = subject.isAuthenticated();
		
		System.out.println("是否認證通過:" + isAuthenticated);
		
		
		//退出操作
		subject.logout();
		
		//是否認證通過
		isAuthenticated = subject.isAuthenticated();
		
		System.out.println("是否認證通過:" + isAuthenticated);
		
		
	}


好了,自定義Realm就寫到這,下節會給大家發一下自定義Realm對雜湊(MD5)的支援