shiro 密码如何验证?

Authentication:身份认证/登录,验证用户是不是拥有相应的身份。
Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情。
这里我们主要分析Authentication过程
一般在登陆方法中我们会这么写:
 
Subject subject =SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);
其中username,paasword为客户端登陆请求传过来的账号密码,现在我们只要知道 token中含有客户端输入的账号密码,那么怎么和数据库中的做验证呢?
再看spring中shiro的一部分xml配置:
MyRealm类:
@Service
public class MyRealm extends AuthorizingRealm {
   @Autowired
   private UserSerivce userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String account= token.getUsername(); 
        User user = userService.getUserByAccount(account);
        return new SimpleAuthenticationInfo(user, user.getCpassword(), getName());
    }
 
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName("SHA-256");
        shaCredentialsMatcher.setHashIterations("1");
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
    上面securityManager是shiro的核心,其realm是我们自己定义的myRealm。doGetAuthorizationInfo跟授权相关我们先不看。大致上可以看出,doGetAuthenticationInfo方法返回的东西跟数据库中实际的用户名和密码有关,setCredentialsMatcher方法跟加密规则有关。    
       回到最开始的三行代码。subject.login(token),入参的token带有用户输入的账号密码,而我们的myRealm的方法返回值有数据库中该账号的密码。那么最后肯定是两者比较来进行认证。所以我们跟下subject.login方法。
DelegatingSubject:
 
public void login(AuthenticationToken token) throws AuthenticationException {
    clearRunAsIdentitiesInternal();
    Subject subject = securityManager.login(this, token);
    ......
}
因为我们的myRealm是在securityManager中,所以在跟下securityManager.login:
DefaultSecurityManager:
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
    AuthenticationInfo info;
    try {
       //看这里
        info = authenticate(token);
    } catch (AuthenticationException ae) {
        try {
            onFailedLogin(token, ae, subject);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info("onFailedLogin method threw an " +
                        "exception.  Logging and propagating original AuthenticationException.", e);
            }
        }
        throw ae; //propagate
    }
 
    Subject loggedIn = createSubject(token, info, subject);
 
    onSuccessfulLogin(token, info, loggedIn);
 
    return loggedIn;
}
前面MyRealm的doGetAuthenticationInfo方法返回的是SimpleAuthenticationInfo,其实是 AuthenticationInfo的子类,所以我再看authenticate()方法,因为使用了代理模式,实际调用在Authenticator类的子类
AbstractAuthenticator:
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
 
    if (token == null) {
        throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
    }
 
    log.trace("Authentication attempt received for token [{}]", token);
 
    AuthenticationInfo info;
    try {
        //看这里
        info = doAuthenticate(token);
        if (info == null) {
            String msg = "No account information found for authentication token [" + token + "] by this " +
                    "Authenticator instance.  Please check that it is configured correctly.";
            throw new AuthenticationException(msg);
        }
    } catch (Throwable t) {
        AuthenticationException ae = null;
        if (t instanceof AuthenticationException) {
            ae = (AuthenticationException) t;
        }
        if (ae == null) {
            //Exception thrown was not an expected AuthenticationException.  Therefore it is probably a little more
            //severe or unexpected.  So, wrap in an AuthenticationException, log to warn, and propagate:
            String msg = "Authentication failed for token submission [" + token + "].  Possible unexpected " +
                    "error? (Typical or expected login exceptions should extend from AuthenticationException).";
            ae = new AuthenticationException(msg, t);
            if (log.isWarnEnabled())
                log.warn(msg, t);
        }
        try {
            notifyFailure(token, ae);
        } catch (Throwable t2) {
            if (log.isWarnEnabled()) {
                String msg = "Unable to send notification for failed authentication attempt - listener error?.  " +
                        "Please check your AuthenticationListener implementation(s).  Logging sending exception " +
                        "and propagating original AuthenticationException instead...";
                log.warn(msg, t2);
            }
        }
 
 
        throw ae;
    }
 
    log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);
 
    notifySuccess(token, info);
 
    return info;
}
又是一个方法返回AuthenticationInfo,再看下去。
ModularRealmAuthenticator:

protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
    assertRealmsConfigured();
    Collection<Realm> realms = getRealms();
    if (realms.size() == 1) {
        //看这里
        return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
    } else {
        return doMultiRealmAuthentication(realms, authenticationToken);
    }
}
 
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
    if (!realm.supports(token)) {
        String msg = "Realm [" + realm + "] does not support authentication token [" +
                token + "].  Please ensure that the appropriate Realm implementation is " +
                "configured correctly or that the realm accepts AuthenticationTokens of this type.";
        throw new UnsupportedTokenException(msg);
    }
    //看这里
    AuthenticationInfo info = realm.getAuthenticationInfo(token);
    if (info == null) {
        String msg = "Realm [" + realm + "] was unable to find account data for the " +
                "submitted AuthenticationToken [" + token + "].";
        throw new UnknownAccountException(msg);
    }
    return info;
}
 
我们就一个realm所以看doSingleRealmAuthentication,这次终于看到我们熟悉的MyRealm里的方法了?不对,还少了个do。继续跟进。
AuthenticatingRealm:
 
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
 
    AuthenticationInfo info = getCachedAuthenticationInfo(token);
    if (info == null) {
        //otherwise not cached, perform the lookup:
        info = doGetAuthenticationInfo(token);
        log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
        if (token != null && info != null) {
            cacheAuthenticationInfoIfPossible(token, info);
        }
    } else {
        log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
    }
 
    if (info != null) {
        assertCredentialsMatch(token, info);
    } else {
        log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
    }
 
    return info;
}
 
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.");
    }
}
      这个方法才是重头。整体逻辑就是,先从缓存根据token取认证信息(AuthenticationInfo),若没有,则调用我们自己实现的MyRealm中的doGetAuthenticationInfo去获取,然后尝试缓存,最后再通过assertCredentialsMatch去验证token和info,assertCredentialsMatch则会根据MyReaml中setCredentialsMatcher我们设置的加密方式去进行相应的验证。
  整个流程的牵涉到的uml图:
 我们在xml配置文件中配置的MyRealm会被放到RealmSecurityManager的reals集合中,也就是说SercurityManager和下图中的AuthenticatingRealm是一对多的关系。
 
 
总结:一路跟踪下来其实学到不少,比如ModularRealmAuthenticator类中如果realm有多个那会走doMultiRealmAuthentication()方法,而ModularRealmAuthenticator类有个authenticationStrategy属性,在doMultiRealmAuthentication()方法中有用到,看名字就知道,使用了策略模式实现了各种realm的匹配规则。总而言之,流行起来的框架随便看一看都会有很多收获,希望有一天自己也能写出这样的代码。
 
 

猜你喜欢

转载自www.cnblogs.com/zuochengsi-9/p/10153874.html