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的匹配規則。總而言之,流行起來的框架隨便看一看都會有很多收獲,希望有一天自己也能寫出這樣的代碼。
