shiro + MD5

2019-07-31 18:11:32 浏览数 (2)

1 CustomRealmMD5.java

代码语言:javascript复制
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 文件

代码语言:javascript复制
[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

测试代码

代码语言:javascript复制
// 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);
		}

0 人点赞