shiro整合开发-认证连接数据库


修改realm的doGetAuthenticationInfo,从数据库查询用户信息,realm返回的用户信息中包括 (md5加密后的串和salt),实现让shiro进行散列串的校验。


1.修改doGetAuthenticationInfo从数据库查询用户信息


	//注入SysService来调用数据库的相关数据
	@Autowired
	private SysService sysService;

	//realm的认证方法,从数据库中查询
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		//token是用户输入的
		//获取用户输入的用户名
		String userCode = (String)token.getPrincipal();
		
		SysUser sysUser = null;
		try {
			//根据用户输入的用户名,在数据库中查询该账号
			sysUser = sysService.findSysUserByUserCode(userCode);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//如果sysUser==null证明数据库中没有存在该账号
		if(sysUser == null){
			return null;
		}
		
		//该用户存在,获取密码
		String password = sysUser.getPassword();
		
		//取出盐
		String salt = sysUser.getSalt();
		
		//新建一个ActiveUser,将该用户的数据放进去
		ActiveUser activeUser = new ActiveUser();
		activeUser.setUserid(sysUser.getId());
		activeUser.setUsercode(sysUser.getUsercode());
		activeUser.setUsername(sysUser.getUsername());
		
		//根据用户的id取出菜单
		List<SysPermission> menus = null;
		
		try {
			//取出用户的菜单
			menus = sysService.findMenuListByUserId(activeUser.getUserid());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		//创建新的simpleAuthenticationInfo,用于返回
		SimpleAuthenticationInfo simpleAuthenticationInfo = 
				new SimpleAuthenticationInfo(activeUser, password, ByteSource.Util.bytes(salt), this.getName());
		return simpleAuthenticationInfo;
	}
	



2.设置凭证匹配器,在applicationContext-shiro中进行设置


数据库中存储到的md5的散列值,在realm中需要设置数据库中的散列值它使用散列算法 及散列次数,

让shiro进行散列对比时和原始数据库中的散列值使用的算法 一致。

<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
	<!-- 在realm中注入凭证匹配器 -->
	<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>

<!-- 凭证匹配器 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
	<property name="hashAlgorithmName" value="md5"></property>
	<property name="hashIterations" value="1"></property>
</bean>








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值