9、密碼比較

在realm中 認證成功後會返回 return new SimpleAuthenticationInfo(username,md5, getName());算法

在這裏插入圖片描述

認證成功成功拿到 info 放下執行到 assertCredentialsMatch(token,info);spring

在這裏插入圖片描述

public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
 
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
    CredentialsMatcher cm = getCredentialsMatcher();
    if (cm != null) {
        if (!cm.doCredentialsMatch(token, info)) {
            //not successful - throw an exception to indicate this:
            String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
            throw new IncorrectCredentialsException(msg);
        }
    } else {
        throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
                "credentials during authentication.  If you do not wish for credentials to be examined, you " +
                "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
    }
}
 
}
 
複製代碼

cm.doCredentialsMatch(token, info) 這裏能夠使用默認的密碼比較器 或者使用自定義的密碼比較apache

在這裏插入圖片描述

我這裏是自定義 密碼校驗 很簡單就是繼承上面圖中的類 畫橫線的過期了 實現doCredentialsMatch 方法markdown

public class Md5HashCredentialsMatcher extends SimpleCredentialsMatcher {

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token,
                                      AuthenticationInfo info) {

        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;

        //注意token.getPassword()拿到的是一個char[],不能直接用toString(),它底層實現不是咱們想的直接字符串,只能強轉
        Object tokenCredentials = Encrypt.md5(String.valueOf(usertoken.getPassword()), usertoken.getUsername());
        Object accountCredentials = getCredentials(info);

        //將密碼加密與系統加密後的密碼校驗,內容一致就返回true,不一致就返回false
        return equals(tokenCredentials, accountCredentials);
    }


}
複製代碼

而後在spring-shiro.xml 中配置一下app

<bean id="myRealm" class="spring.shiro.realm.MyRealm">
        <property name="credentialsMatcher" ref="md5Matcher"/>
        <!--<property name="credentialsMatcher" ref="md5hash"/>-->
    </bean>

    <bean id="md5hash" class="spring.shiro.matcher.Md5HashCredentialsMatcher"/>

    <bean id="md5Matcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!-- 加密算法的名稱 -->
        <property name="hashAlgorithmName" value="MD5"/>
        <!-- 配置加密的次數 -->
        <property name="hashIterations" value="1024"/>
    </bean>


    <bean id="sha1Matcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!-- 加密算法的名稱 -->
        <property name="hashAlgorithmName" value="SHA1"/>
        <!-- 配置加密的次數 -->
        <property name="hashIterations" value="1024"/>
    </bean>

複製代碼
相關文章
相關標籤/搜索