Shiro入门 - 通过自定义Realm连数数据库进行认证(md5+salt形式)

时间:2023-03-09 01:26:39
Shiro入门 - 通过自定义Realm连数数据库进行认证(md5+salt形式)

shiro-realm-md5.ini

[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=2

#将凭证设置到realm
myRealmMD5=test.shiro.MyRealmMd5
myRealmMD5.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealmMD5

MyRealmMd5.java

/**
 * 认证
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    String account = (String) token.getPrincipal();

    //根据取到的account到数据库中查询是否存在
    //此时数据库密码是密文存在,pwd="36f2dfa24d0a9fa97276abbe13e596fc",salt = "qwerty"

    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getAccount(), user.getPwd, ByteSource.Util.bytes(user.getSalt), this.getName());
    return info;
}

测试代码

/**
 * 通过自定义Realm+md5+salt加密对数据库中的账号密码进行认证
 */
@Test
public void testMyRealmMD5(){
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm-md5.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("admin", "111111");
    subject.login(token);
    System.out.println("认证状态:"+subject.isAuthenticated());
    subject.logout();
    System.out.println("认证状态:"+subject.isAuthenticated());
}

测试结果

认证状态:true
认证状态:false