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的匹配規則。總而言之,流行起來的框架隨便看一看都會有不少收穫,但願有一天本身也能寫出這樣的代碼。
相關文章
相關標籤/搜索