Shiro的使用方法參見(jiàn)跟我學(xué)shiro
Shiro的驗(yàn)證過(guò)程分析如下:
獲取SecurityManager 并綁定給SecurityUtils
- 通過(guò)xml配置
<bean id="myShiroRealm" class="com.wechat.ztsoft.shiro.realm.MyRealm">
<!--密碼匹配算法-->
<property name="credentialsMatcher" ref="credentialsMatcher"/>
<!--授權(quán)信息緩存-->
<property name="authorizationCachingEnabled" value="true"/>
<property name="authorizationCacheName" value="authorizationCache"/>
</bean>
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myShiroRealm"/>
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="cacheManger" />
</bean>
<!-- 相當(dāng)于調(diào)用SecurityUtils.setSecurityManager(securityManager) -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
<property name="arguments" ref="securityManager"/>
</bean>
獲取Subject并創(chuàng)建用戶憑證
- 獲取Subject奥此,SecurityUtils.getSubject
public static Subject getSubject() {
Subject subject = ThreadContext.getSubject();
if (subject == null) {
subject = (new Subject.Builder()).buildSubject();
ThreadContext.bind(subject);
}
return subject;
}
- 函數(shù)內(nèi)第一行函數(shù)凿歼,通過(guò)線程本地變量綁定Subject到當(dāng)前線程;具體參見(jiàn)ThreadContext類,其定義了一個(gè)靜態(tài)線程本地變量:
private static final ThreadLocal<Map<Object, Object>> resources = new InheritableThreadLocalMap<Map<Object, Object>>();
- 調(diào)用其getSubjec函數(shù)幕屹,最終調(diào)用該類內(nèi)的靜態(tài)函數(shù)getValue:
public static Object get(Object key) {
if (log.isTraceEnabled()) {
String msg = "get() - in thread [" + Thread.currentThread().getName() + "]";
log.trace(msg);
}
Object value = getValue(key);
if ((value != null) && log.isTraceEnabled()) {
String msg = "Retrieved value of type [" + value.getClass().getName() + "] for key [" +
key + "] " + "bound to thread [" + Thread.currentThread().getName() + "]";
log.trace(msg);
}
return value;
}
//get內(nèi)部調(diào)用了getValue函數(shù)
private static Object getValue(Object key) {
return resources.get().get(key);
}
- 其調(diào)用了ThreadLocal變量,然后獲取其Map類型的值矿酵,然后從中獲取該Key對(duì)應(yīng)的對(duì)象婴梧。
結(jié)束后回到SecurityUtils中,若該線程仍沒(méi)有綁定subject辨绊,可看到會(huì)新建一個(gè)subject對(duì)象奶栖,具體創(chuàng)建方法為:
subject = (new Subject.Builder()).buildSubject();
- 調(diào)用綁定的securityManager對(duì)象創(chuàng)建subject,
public Subject buildSubject() {
return this.securityManager.createSubject(this.subjectContext);
}
- 綁定的SecurityManager實(shí)現(xiàn)類為DefaultWebSecurityManager门坷,故調(diào)用其實(shí)現(xiàn)的createSubject方法創(chuàng)建
public DefaultWebSecurityManager() {
super();
((DefaultSubjectDAO) this.subjectDAO).setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());
this.sessionMode = HTTP_SESSION_MODE;
//設(shè)置subject工廠類為DefaultWebSubjectFactory
setSubjectFactory(new DefaultWebSubjectFactory());
setRememberMeManager(new CookieRememberMeManager());
setSessionManager(new ServletContainerSessionManager());
}
- DefaultWebSecurityManager類調(diào)用其父類DefaultSecurityManager實(shí)現(xiàn)的createSubject
protected Subject createSubject(AuthenticationToken token, AuthenticationInfo info, Subject existing) {
SubjectContext context = createSubjectContext();
context.setAuthenticated(true);
context.setAuthenticationToken(token);
context.setAuthenticationInfo(info);
if (existing != null) {
context.setSubject(existing);
}
return createSubject(context);
}
- 最終調(diào)用DefaultSecurityManager的createSubject(SubjectContext subjectContext)方法
public Subject createSubject(SubjectContext subjectContext) {
//create a copy so we don't modify the argument's backing map:
SubjectContext context = copy(subjectContext);
context = ensureSecurityManager(context);
context = resolveSession(context);
context = resolvePrincipals(context);
/ /此處為關(guān)鍵
Subject subject = doCreateSubject(context);
save(subject);
return subject;
}
- 關(guān)鍵創(chuàng)建代碼調(diào)用了doCreateSubject方法
protected Subject doCreateSubject(SubjectContext context) {
return getSubjectFactory().createSubject(context);
}
- 其調(diào)用了前面設(shè)置的DefaultWebSubjectFactory工程類的createSubject方法宣鄙,其返回了一個(gè)Subject的實(shí)現(xiàn)類WebDelegatingSubject的對(duì)象
public Subject createSubject(SubjectContext context) {
if (!(context instanceof WebSubjectContext)) {
return super.createSubject(context);
}
WebSubjectContext wsc = (WebSubjectContext) context;
SecurityManager securityManager = wsc.resolveSecurityManager();
Session session = wsc.resolveSession();
boolean sessionEnabled = wsc.isSessionCreationEnabled();
PrincipalCollection principals = wsc.resolvePrincipals();
boolean authenticated = wsc.resolveAuthenticated();
String host = wsc.resolveHost();
ServletRequest request = wsc.resolveServletRequest();
ServletResponse response = wsc.resolveServletResponse();
return new WebDelegatingSubject(principals, authenticated, host, session, sessionEnabled,
request, response, securityManager);
}
- 接下來(lái)將新建的subject,綁定到線程變量中默蚌,具體方法如下:
public static void bind(Subject subject) {
if (subject != null) {
put(SUBJECT_KEY, subject);
}
}
//實(shí)際調(diào)用put方法
public static void put(Object key, Object value) {
if (key == null) {
throw new IllegalArgumentException("key cannot be null");
}
if (value == null) {
remove(key);
return;
}
//將subject對(duì)象插入到map對(duì)象中
resources.get().put(key, value);
if (log.isTraceEnabled()) {
String msg = "Bound value of type [" + value.getClass().getName() + "] for key [" +
key + "] to thread " + "[" + Thread.currentThread().getName() + "]";
log.trace(msg);
}
}
- 創(chuàng)建用戶憑證
UsernamePasswordToken token = new UsernamePasswordToken("wang", "123456");
### 執(zhí)行登錄驗(yàn)證
- 調(diào)用Subject.login(token )冻晤,實(shí)際調(diào)用WebDelegatingSubject的login方法,WebDelegatingSubject未覆蓋login方法绸吸,調(diào)用其父類的鼻弧,即DelegatingSubject的login方法:
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
Subject subject = securityManager.login(this, token);
PrincipalCollection principals;
String host = null;
if (subject instanceof DelegatingSubject) {
DelegatingSubject delegating = (DelegatingSubject) subject;
//we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
principals = delegating.principals;
host = delegating.host;
} else {
principals = subject.getPrincipals();
}
if (principals == null || principals.isEmpty()) {
String msg = "Principals returned from securityManager.login( token ) returned a null or " +
"empty value. This value must be non null and populated with one or more elements.";
throw new IllegalStateException(msg);
}
this.principals = principals;
this.authenticated = true;
if (token instanceof HostAuthenticationToken) {
host = ((HostAuthenticationToken) token).getHost();
}
if (host != null) {
this.host = host;
}
Session session = subject.getSession(false);
if (session != null) {
this.session = decorate(session);
} else {
this.session = null;
}
}
- 其委托給SecurityManager執(zhí)行l(wèi)ogin
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;
}
- 調(diào)用了父類AuthenticatingSecurityManager的authenticate方法;回去看XML配置模塊锦茁,我們配置實(shí)現(xiàn)獲取認(rèn)證信息和授權(quán)信息的Realm攘轩,設(shè)置完成后調(diào)用afterRealmsSet方法,AuthenticatingSecurityManager覆蓋了該方法蜻势,如下
protected void afterRealmsSet() {
super.afterRealmsSet();
if (this.authenticator instanceof ModularRealmAuthenticator) {
((ModularRealmAuthenticator) this.authenticator).setRealms(getRealms());
}
}
- 將Realm賦值給實(shí)際Authenticator撑刺,AuthenticatingSecurityManager中的Authenticator為ModularRealmAuthenticator實(shí)現(xiàn)類鹉胖,發(fā)現(xiàn)Authenticator的子類AbstractAuthenticator實(shí)現(xiàn)了authenticate方法握玛,并把實(shí)際執(zhí)行代碼用占位符doAuthenticate留待子類去實(shí)現(xiàn),我們進(jìn)入ModularRealmAuthenticator查看其doAuthenticate方法
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);
}
}
- 可以看到分位一個(gè)或多個(gè)Realm兩張情況甫菠,我們以一個(gè)Realm為例分析
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);
}
//關(guān)鍵代碼 通過(guò)realm獲取認(rèn)證信息挠铲,此處我們自己實(shí)現(xiàn)realm,根據(jù)邏返回認(rèn)證信息類寂诱,如SimpleAuthenticationInfo
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;
}
- 回過(guò)頭看需要我們自己實(shí)現(xiàn)的Realm子類拂苹,繼承AuthorizingRealm,其繼承自AuthenticatingRealm痰洒,實(shí)現(xiàn)doGetAuthorizationInfo及doGetAuthenticationInfo函數(shù)
進(jìn)入AuthenticatingRealm查看其getAuthenticationInfo函數(shù)
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;
}
可以看到核心既是我們需要實(shí)現(xiàn)的doGetAuthenticationInfo函數(shù)瓢棒,獲取認(rèn)證信息浴韭,然后進(jìn)行驗(yàn)證assertCredentialsMatch,使用CredentialsMatcher進(jìn)行實(shí)際驗(yàn)證,我們可以自己實(shí)現(xiàn)CredentialsMatcher接口進(jìn)行驗(yàn)證
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.");
}
}
- 貼出我自己的驗(yàn)證器脯宿,帶防止多次試探密碼的功能
···
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
private Cache<String, AtomicInteger> passwordRetryCache;
public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
passwordRetryCache = cacheManager.getCache("passwordRetryCache");
}
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String)token.getPrincipal();
//retry count + 1
AtomicInteger retryCount = passwordRetryCache.get(username);
if(retryCount == null) {
retryCount = new AtomicInteger(0);
passwordRetryCache.put(username, retryCount);
}
if(retryCount.incrementAndGet() > 8) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
}
boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
}
···
- 回頭看assertCredentialsMatch函數(shù)念颈,校驗(yàn)失敗后,拋出IncorrectCredentialsException異常连霉,然后AuthenticatingSecurityManager的login拋該異常榴芳,登錄失敗
到此,shiro的驗(yàn)證過(guò)程結(jié)束跺撼,其他的一些細(xì)節(jié)窟感,有興趣的可以去研究源碼。