Shiro(二)介绍如何实现一个简单的Shiro认证流程,接下来对 密码的比对与加密进行简单的介绍。
Shiro 密码的比对、MD5盐值加密
密码的比对、MD5盐值加密都是通过CrendentialsMatcher(凭证匹配器)来实现的。
一、Shiro认证时的密码比对
在Shiro进行密码比对时,一定会去拿UsernamePasswordToken 和SimpleAuthenticationInfo中封装的密码信息,那么此时要调用UsernamePasswordToken的 getPassword方法,或者调用SimpleAuthenticationInfo的getCredentials方法。
1.在UserNamePasswordkToken 中的 getPassword() 方法中打上断点,往前跟踪一下即可。
2.开启debug模式,点击登录,跟踪发现
SimpleCredentialsMatcher类有一个doCredentialsMatch方法,在该方法中
就进行了密码比对工作:
/**
* This implementation acquires the {@code token}'s credentials
* (via {@link #getCredentials(AuthenticationToken) getCredentials(token)})
* and then the {@code account}'s credentials
* (via {@link #getCredentials(org.apache.shiro.authc.AuthenticationInfo) getCredentials(account)}) and then passes both of
* them to the {@link #equals(Object,Object) equals(tokenCredentials, accountCredentials)} method for equality
* comparison.
*
* @param token the {@code AuthenticationToken} submitted during the authentication attempt.
* @param info the {@code AuthenticationInfo} stored in the system matching the token principal.
* @return {@code true} if the provided token credentials are equal to the stored account credentials,
* {@code false} otherwise
*/
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
Object tokenCredentials = getCredentials(token);
Object accountCredentials = getCredentials(info);
return equals(tokenCredentials, accountCredentials);
}
3.继续跟踪,发现我们自定义Realm的父类方法调用了 CrendebtialsMatcher组件 进行密码比对
/**
* Asserts that the submitted {@code AuthenticationToken}'s credentials match the stored account
* {@code AuthenticationInfo}'s credentials, and if not, throws an {@link AuthenticationException}.
*
* @param token the submitted authentication token
* @param info the AuthenticationInfo corresponding to the given {@code token}
* @throws AuthenticationException if the token's credentials do not match the stored account credentials.
*/
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 {