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

来源:互联网 发布:桃子圈微博全数据 编辑:程序博客网 时间:2024/06/02 07:13


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


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


//注入SysService来调用数据库的相关数据@Autowiredprivate 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>








阅读全文
0 0