shiro + MD5

輸入圖片說明

1 CustomRealmMD5.javajava

package com.shi.realm;

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;
import org.apache.shiro.util.ByteSource;

public class CustomRealmMD5 extends AuthorizingRealm{

	//設置realm的名字
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}
	
	
	/**
	 * 用於認證
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//1 從token中取出身份信息(token是用戶輸入的)
		String userCode=(String) token.getPrincipal();//或者帳號
		
		//2 根據用戶輸入的userCode從數據庫查詢
		//...  模擬數據庫中取出的密碼是"123456"
		String password_db="588043b2413a9a1e26a623f58606f148";
		//鹽
		String salt="sjsii";
		
		//3 若是 查詢不到返回null
		if(!"zhangsan".equals(userCode)){
			return null;
		}
		
		//若是查詢到 返回認證信息AuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo
			(userCode, password_db,ByteSource.Util.bytes(salt) , this.getName());
		
		return simpleAuthenticationInfo;
	}
	
	/**
	 * 用於受權
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

}

2 shiro-realm-md5.ini 文件算法

[main]
#定義憑證匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次數 默認爲1
credentialsMatcher.hashIterations=1

#將憑證器映射到realm 至關於DI(依賴注入)
customRealm=com.shi.realm.CustomRealmMD5
customRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$customRealm

測試代碼數據庫

// 3  自定義CustomRealm +MD5  測試 
		@Test
		public void testCustomRealmMD5(){
			//1 建立securityManager工廠,經過ini配置文件建立securityManage工廠
			Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro-realm-MD5.ini");
			
			//2 建立SecurityManager
			SecurityManager securityManager=factory.getInstance();
			
			//3 將SecurityManager設置當前的運行環境中
			SecurityUtils.setSecurityManager(securityManager);
			
			//4 從SecurityUtils裏邊建立一個subject
			Subject subject=SecurityUtils.getSubject();
			
			//5 在認證提交前準備token(令牌)
			UsernamePasswordToken token =new UsernamePasswordToken("zhangsan", "123456");
			
			try {
				//6 執行認證提交
				subject.login(token);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//是否定證經過
			boolean isAuthenticated=subject.isAuthenticated();
			System.out.println("是否定證經過:"+isAuthenticated);
			
			subject.logout();
			//是否定證經過
			boolean isAuthenticated2=subject.isAuthenticated();
			System.out.println("是否定證經過:"+isAuthenticated2);
		}
相關文章
相關標籤/搜索