Shiro框架學習03--自定義Realm

1.什麼是Realm?

   當從客服端傳來信息就相當於一把鑰匙,而Realm相當於一扇門,我們要拿着這把鑰匙去打開這扇門,門是怎麼被打開的就需要我們去自定義規則(這些規則就在Reaml中來實現)。

2爲什麼要自定義Realm?

   可以根據自己的業務邏輯來實現不同的驗證。變得更加的靈活。

 

 在此之前,在自己的數據庫中建立一張表。下面代碼中有Db().getUser(name)是用來根據name來查詢密碼的。

   先看一個例子:

        當我們從客服端得到用戶名密碼時,我們需要根據用戶名到數據庫中查詢,並返回該用戶名的密碼,這時我們可以根據自己需要來自定義Realm來實現我們操作,看下面的代碼,都比較簡單。

public class myJbdcRealm implements Realm{

	public String getName() {
		// TODO Auto-generated method stub
		return "jbcdRealm";
	}

	public boolean supports(AuthenticationToken token) {
		// TODO Auto-generated method stub
		return token instanceof UsernamePasswordToken;
	}

	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String  name = (String)token.getPrincipal(); //客戶端傳來的用戶名
		String pwd = new String((char[])token.getCredentials()); //客戶端傳來的密碼
		System.out.println("username:"+name+" password:"+pwd);
		
		//從數據庫得到的密碼
		String password = new Db().getUser(name);
		System.out.println("password:"+password);
		
		//判斷輸入的密碼和數據庫中的密碼是否一致
		if(!pwd.equals(password)){
			throw new IncorrectCredentialsException("密碼錯誤");
		}
		
		//SimpleAuthenticationInfo是Realm的實現類
		SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(name, pwd, this.getName());
		return sai;
	}
}

3.配置shiro.ini文件

[main]
jdbcrealm=com.shiro.realmTest.myJbdcRealm

securityManager.realm=$jdbcrealm

5.Test類,跟前面shiro02文章的測試類一樣。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章