Shiro工作過(guò)程分析

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é)窟感,有興趣的可以去研究源碼。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末歉井,一起剝皮案震驚了整個(gè)濱河市柿祈,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌酣难,老刑警劉巖谍夭,帶你破解...
    沈念sama閱讀 222,104評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異憨募,居然都是意外死亡紧索,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門菜谣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)珠漂,“玉大人,你說(shuō)我怎么就攤上這事尾膊∠蔽#” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,697評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵冈敛,是天一觀的道長(zhǎng)待笑。 經(jīng)常有香客問(wèn)我,道長(zhǎng)抓谴,這世上最難降的妖魔是什么暮蹂? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,836評(píng)論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮癌压,結(jié)果婚禮上仰泻,老公的妹妹穿的比我還像新娘。我一直安慰自己滩届,他們只是感情好集侯,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,851評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般棠枉。 火紅的嫁衣襯著肌膚如雪浓体。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,441評(píng)論 1 310
  • 那天辈讶,我揣著相機(jī)與錄音汹碱,去河邊找鬼。 笑死荞估,一個(gè)胖子當(dāng)著我的面吹牛咳促,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播勘伺,決...
    沈念sama閱讀 40,992評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼跪腹,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了飞醉?” 一聲冷哼從身側(cè)響起冲茸,我...
    開(kāi)封第一講書(shū)人閱讀 39,899評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎缅帘,沒(méi)想到半個(gè)月后轴术,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钦无,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,529評(píng)論 3 341
  • 正文 我和宋清朗相戀三年逗栽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片失暂。...
    茶點(diǎn)故事閱讀 40,664評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡彼宠,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出弟塞,到底是詐尸還是另有隱情凭峡,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評(píng)論 5 350
  • 正文 年R本政府宣布决记,位于F島的核電站摧冀,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏系宫。R本人自食惡果不足惜索昂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,025評(píng)論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望笙瑟。 院中可真熱鬧楼镐,春花似錦癞志、人聲如沸往枷。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,511評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)错洁。三九已至秉宿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間屯碴,已是汗流浹背描睦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,611評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留导而,地道東北人忱叭。 一個(gè)月前我還...
    沈念sama閱讀 49,081評(píng)論 3 377
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像今艺,于是被迫代替她去往敵國(guó)和親韵丑。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,675評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理虚缎,服務(wù)發(fā)現(xiàn)撵彻,斷路器,智...
    卡卡羅2017閱讀 134,707評(píng)論 18 139
  • 文章轉(zhuǎn)載自:http://blog.csdn.net/w1196726224/article/details/53...
    wangzaiplus閱讀 3,402評(píng)論 0 3
  • *以下僅是部分關(guān)鍵代碼 應(yīng)用程序根據(jù)用戶的身份和憑證(principals和credentials)來(lái)構(gòu)造出Aut...
    抓兔子的貓閱讀 2,548評(píng)論 0 0
  • 天未黑湖藍(lán)不見(jiàn)白鴿飛起一片片黃沙發(fā)如黑瀑白皙的手為異鄉(xiāng)鋪上綠被 透明的泉水彩光折疊霓虹燈熄滅遠(yuǎn)處昏黃的窗漆紅的門內(nèi)...
    插班生君閱讀 145評(píng)論 2 2
  • 我走過(guò)的路不多 因總在其中徘徊实牡、又徘徊 有時(shí)打赤腳疾走 有時(shí)醉酒 總覺(jué)得這些陌生已經(jīng)看透 也就不必再心存念想 在遇...
    羊念閱讀 181評(píng)論 0 0