4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密

调用自定义Realm之后
    执行方法:doGetAuthenticationInfo()方法后返回AuthenticationInfo
Realm是shiro中进行认证和授权的组件,自带了几种实现。自定义Realm继承AuthorizingRealm,分别实现认证和授权的方法
    doGetAuthenticationInfo(AuthenticationToken token)是认证的方法,当用户登陆的时候会调用
    doGetAuthorizationInfo(AuthenticationToken token)是授权的方法,在拦截器中进行权限校验的时候会调用。
 
1.密码比对:在认证的方法中doGetAuthenticationInfo(AuthenticationToken token)把获取到的账号密码封装到SimpleAuthenticationInfo对象中返回。密码的比对:通过 AuthenticatingRealm 的 credentialsMatcher 属性来进行的密码的比对,默认的凭证匹配器是SimpleCredentialsMatcher。
代码:
1.自定义Realm的doGetAuthenticationInfo()方法返回SimpleAuthenticationInfo给父类AuthenticatingRealmgetAuthenticationInfo()
2.然后调用assertCredentialsMatch()方法,这里可以看到默认的凭证匹配器是SimpleCredentialsMatcher。
3.之后调用凭证匹配器中的doCredentialsMatch(token, info)方法,在此方法中比对账号密码,凭证匹配器我们可以再spring.xml中自定义realm的bean节点下配置
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
 
2.密码加密
数据库中保存密码一般来说为了安全会使用加密方式进行加密,加密过后存储Shiro中。
如何把一个字符串加密为 MD5? 配置当前 Realm 的 credentialsMatcher 属性. 直接使用 HashedCredentialsMatcher 对象, 并设置加密算法即可。
具体步骤:就是在spring.xml文件中,注入自定义realm中的bean节点中添加
<property name="credentialsMatcher">
    <!--凭证匹配器-->
    <bean  class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!--指定加密算法,指定之后前台传的参数就会自定按照指定的加密算法加密-->
        <property name="hashAlgorithmName" value="MD5"/>
        <!-- 指定循环加密次数 -->
        <property name="hashIterations" value="1024"/>
    </bean>
</property>
步骤同上
只不过凭证匹配器是配置文件中配置的HashedCredentialsMatcher类
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
 
调用HashedCredentialsMatcher凭证匹配器中的doCredentialsMatch(token, info)方法
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
 
对比凭证匹配器中的doCredentialsMatch(token, info)方法,可以看到区别是在获取密码的时候
加密代码:
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
 
具体区分可见:默认的凭证匹配器和加密的凭证匹配器
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密
3.盐值加密
自定义realm的doGetAuthenticationInfo()方法返回的对象使用最复杂的构造方法
//SimpleAuthenticationInfo info = new  SimpleAuthenticationInfo(principal, credentials,realmName);
//使用盐值加密,一般盐值是唯一的
ByteSource credentialsSalt =  ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = null;
info = new SimpleAuthenticationInfo(principal,  credentials, credentialsSalt, realmName);
return info;
源码流程:
4.Shiro认证流程2_密码比对,MD5加密,MD5盐值加密