Shiro 登錄認(rèn)證源碼詳解

文章轉(zhuǎn)載自:http://blog.csdn.net/w1196726224/article/details/53560385

Apache Shiro 是一個(gè)強(qiáng)大且靈活的 Java 開(kāi)源安全框架,擁有登錄認(rèn)證、授權(quán)管理、企業(yè)級(jí)會(huì)話管理和加密等功能,相比 spring Security 來(lái)說(shuō)要更加的簡(jiǎn)單。
本文主要介紹 Shiro 的登錄認(rèn)證(Authentication)功能,主要從 Shiro 設(shè)計(jì)的角度去看這個(gè)登錄認(rèn)證的過(guò)程。
一、Shiro 總覽
首先,我們思考整個(gè)認(rèn)證過(guò)程的業(yè)務(wù)邏輯:
獲取用戶輸入的用戶名,密碼;
從服務(wù)器數(shù)據(jù)源中獲取相應(yīng)的用戶名和密碼;
判斷密碼是否匹配,決定是否登錄成功。

我們現(xiàn)在來(lái)看看 Shiro 是如何設(shè)計(jì)這個(gè)過(guò)程的:

圖中包含三個(gè)重要的 Shiro 概念:Subject
、SecurityManager
、Realm
。接下來(lái),分別介紹這三者有何用:
Subject:表示“用戶”,表示當(dāng)前執(zhí)行的用戶。Subject
實(shí)例全部都綁定到了一個(gè) SecurityManager
上,當(dāng)和 Subject
交互時(shí),它是委托給 SecurityManager
去執(zhí)行的。
SecurityManager:Shiro 結(jié)構(gòu)的心臟,協(xié)調(diào)它內(nèi)部的安全組件(如登錄,授權(quán),數(shù)據(jù)源等)。當(dāng)整個(gè)應(yīng)用配置好了以后,大多數(shù)時(shí)候都是直接和 Subject
的 API 打交道。
Realm:數(shù)據(jù)源,也就是抽象意義上的 DAO 層。它負(fù)責(zé)和安全數(shù)據(jù)交互(比如存儲(chǔ)在數(shù)據(jù)庫(kù)的賬號(hào)、密碼,權(quán)限等信息),包括獲取和驗(yàn)證。Shiro 支持多個(gè) Realm,但是至少也要有一個(gè)。Shiro 自帶了很多開(kāi)箱即用的 Reams,比如支持 LDAP、關(guān)系數(shù)據(jù)庫(kù)(JDBC)、INI 和 properties 文件等。但是很多時(shí)候我們都需要實(shí)現(xiàn)自己的 Ream 去完成獲取數(shù)據(jù)和判斷的功能。

登錄驗(yàn)證的過(guò)程就是:Subject
執(zhí)行 login
方法,傳入登錄的「用戶名」和「密碼」,然后SecurityManager
將這個(gè) login
操作委托給內(nèi)部的登錄模塊,登錄模塊就調(diào)用 Realm
去獲取安全的「用戶名」和「密碼」,然后對(duì)比,一致則登錄,不一致則登錄失敗。
Shiro 詳細(xì)結(jié)構(gòu)

ShiroArchitecture

二、Shiro 登錄示例
代碼來(lái)自 Shiro 官網(wǎng)教程。Shiro 配置 INI 文件:

----------------------------------------------------------------------------# Users and their (optional) assigned roles# username = password, role1, role2, ..., roleN# ----------------------------------------------------------------------------[users]wang=123

1
2
3
4
5
6

1
2
3
4
5
6

測(cè)試 main 方法:
public static void main(String[] args) { log.info("My First Apache Shiro Application"); //1.從 Ini 配置文件中獲取 SecurityManager 工廠 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2.獲取 SecurityManager 實(shí)例 SecurityManager securityManager = factory.getInstance(); //3.將 SecurityManager 實(shí)例綁定給 SecurityUtils SecurityUtils.setSecurityManager(securityManager); //4.獲取當(dāng)前登錄用戶 Subject currentUser = SecurityUtils.getSubject(); //5.判斷是否登錄,如果未登錄,則登錄 if (!currentUser.isAuthenticated()) { //6.創(chuàng)建用戶名/密碼驗(yàn)證Token(Web 應(yīng)用中即為前臺(tái)獲取的用戶名/密碼) UsernamePasswordToken token = new UsernamePasswordToken("wang", "123"); try { //7.執(zhí)行登錄,如果登錄未成功,則捕獲相應(yīng)的異常 currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

三、登錄邏輯詳解
Shiro 登錄過(guò)程主要涉及到 Subject.login
方法,接下來(lái)我們將通過(guò)查看源碼來(lái)分析整個(gè)登錄過(guò)程。
創(chuàng)建 AuthenticationToken
接口的實(shí)例 token,比如例子中的 UsernamePasswordToken
,包含了登錄的用戶名和密碼;
獲取當(dāng)前用戶 Subject
,然后調(diào)用 Subject.login(AuthenticationToken)
方法;
Subject
將 login
代理給 SecurityManager
的 login()

**3.1 創(chuàng)建AuthenticationToken
**
第一步是創(chuàng)建 AuthenticationToken
接口的身份 token,比如例子中的 UsernamePasswordToken
。
package org.apache.shiro.authc;public interface AuthenticationToken extends Serializable { // 獲取“用戶名” Object getPrincipal(); // 獲取“密碼” Object getCredentials();}
1
2
3
4
5
6
7
8

1
2
3
4
5
6
7
8

3.2 獲取當(dāng)前用戶并執(zhí)行登錄
獲取的 Subject
當(dāng)前用戶是我們平時(shí)打交道最多的接口,有很多方法,但是這里我們只分析 login
方法。
package org.apache.shiro.subject;public interface Subject { void login(AuthenticationToken token) throws AuthenticationException;}
1
2
3
4
5
6
7

1
2
3
4
5
6
7

login
方法接受一個(gè) AuthenticationToken
參數(shù),如果登錄失敗則拋出 AuthenticationException
異常,可通過(guò)判斷異常類型來(lái)知悉具體的錯(cuò)誤類型。
接下來(lái),分析 Subject
接口的實(shí)現(xiàn)類 DelegatingSubject
是如何實(shí)現(xiàn) login
方法的:
public void login(AuthenticationToken token) throws AuthenticationException { clearRunAsIdentitiesInternal(); // 代理給SecurityManager Subject subject = securityManager.login(this, token); ...}
1
2
3
4
5
6

1
2
3
4
5
6

3.3 SecurityManager 接口
前面說(shuō)過(guò),整個(gè) Shiro 安全框架的心臟就是 SecurityManager,我們看這個(gè)接口都有哪些方法:
package org.apache.shiro.mgt;public interface SecurityManager extends Authenticator, Authorizer, SessionManager { Subject login(Subject subject, AuthenticationToken authenticationToken) throws AuthenticationException; void logout(Subject subject); Subject createSubject(SubjectContext context);}
1
2
3
4
5
6
7
8
9
10

1
2
3
4
5
6
7
8
9
10

SecurityManager 包含很多內(nèi)置的模塊來(lái)完成功能,比如登錄(Authenticator
),權(quán)限驗(yàn)證(Authorizer
)等。這里我們看到 SecurityManager 接口繼承了 Authenticator
登錄認(rèn)證的接口:
package org.apache.shiro.authc;public interface Authenticator { public AuthenticationInfo authenticate(AuthenticationToken authenticationToken) throws AuthenticationException;}
1
2
3
4
5
6
7

1
2
3
4
5
6
7

那么,SecurityManager
的實(shí)現(xiàn)都是怎樣來(lái)實(shí)現(xiàn) Authenticator
接口的呢?答案是:使用了組合。SecurityManager 都擁有一個(gè) Authenticator
的屬性,這樣**調(diào)用 SecurityManager.authenticate
** 的時(shí)候,是委托給內(nèi)部的 Authenticator
屬性去執(zhí)行的。

SecurityManager

3.4 SecurityManager.login 的實(shí)現(xiàn)
// DefaultSecurityManager.javapublic 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;}// AuthenticatingSecurityManager.java/** * Delegates to the wrapped {@link org.apache.shiro.authc.Authenticator Authenticator} for authentication. */public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { return this.authenticator.authenticate(token);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

調(diào)用自己的 authenticate
方法執(zhí)行登錄;
在 authenticate
方法中代理給 Authenticator
接口類型的屬性去真正執(zhí)行 authenticate(token)
方法。

3.5 Authenticator 登錄模塊
Authenticator
接口如下:
package org.apache.shiro.authc;public interface Authenticator { public AuthenticationInfo authenticate(AuthenticationToken authenticationToken) throws AuthenticationException;}
1
2
3
4
5
6
7

1
2
3
4
5
6
7

其實(shí)現(xiàn)類有 AbstractAuthenticator
和 ModularRealmAuthenticator

Authenticator

下面來(lái)看看如何實(shí)現(xiàn)的 authenticate
方法:
// AbstractAuthenticator.javapublic final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info; try { // 調(diào)用doAuthenticate方法 info = doAuthenticate(token); if (info == null) { ... } } catch (Throwable t) { ... } ...}// ModularRealmAuthenticator.javaprotected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException { assertRealmsConfigured(); Collection<Realm> realms = getRealms(); if (realms.size() == 1) { // Realm唯一時(shí) return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); } else { return doMultiRealmAuthentication(realms, authenticationToken); }}protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) { if (!realm.supports(token)) { ... } // 調(diào)用Realm的getAuthenticationInfo方法獲取AuthenticationInfo信息 AuthenticationInfo info = realm.getAuthenticationInfo(token); if (info == null) { ... } return info;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

從源碼中可以看出,最后會(huì)調(diào)用 Realm
的 getAuthenticationInfo(AuthenticationToken)
方法。
3.6 Realm 接口
Realm 相當(dāng)于數(shù)據(jù)源,功能是通過(guò) AuthenticationToken
獲取數(shù)據(jù)源中的安全數(shù)據(jù),這個(gè)過(guò)程中可以拋出異常,告訴 shiro 登錄失敗。
package org.apache.shiro.realm;public interface Realm { // 獲取 shiro 唯一的 realm 名稱 String getName(); // 是否支持給定的 AuthenticationToken 類型 boolean supports(AuthenticationToken token); // 獲取 AuthenticationInfo AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;}
1
2
3
4
5
6
7
8
9
10
11
12
13

1
2
3
4
5
6
7
8
9
10
11
12
13

Shiro 自帶了很多開(kāi)箱即用的 Realm 實(shí)現(xiàn),具體的類圖如下:

Realm

3.7 總結(jié)
到此,我們把整個(gè) Shiro 的登錄認(rèn)證流程分析了一遍。
創(chuàng)建 AuthenticationToken
,然后調(diào)用 Subject.login
方法進(jìn)行登錄認(rèn)證;
Subject
委托給 SecurityManager
;
SecurityManager
委托給 Authenticator
接口;
Authenticator
接口調(diào)用 Realm
獲取登錄信息。

整個(gè)過(guò)程中,如果登錄失敗,就拋出異常,是使用異常來(lái)進(jìn)行邏輯控制的。
四、登錄密碼的存儲(chǔ)
頁(yè)面使用 Https 協(xié)議;
頁(yè)面?zhèn)魉兔艽a時(shí)要先加密后再傳輸,最好是不可逆的加密算法(MD5,SHA2);
后端存儲(chǔ)時(shí)要結(jié)合鹽(隨機(jī)數(shù))一起加密存儲(chǔ);
使用不可逆的加密算法,而且可以加密多次;
把加密后的密碼和鹽一起存儲(chǔ)到數(shù)據(jù)庫(kù);

五、學(xué)習(xí) Shiro 源碼感悟
從整體去思考框架的實(shí)現(xiàn),帶著業(yè)務(wù)邏輯去看實(shí)現(xiàn)邏輯;
不要摳細(xì)節(jié),要看抽象,學(xué)習(xí)其實(shí)現(xiàn)方法;
首先看官方文檔,官方文檔一般會(huì)從整體設(shè)計(jì)方面去說(shuō)明,遇到具體的接口再去看Javadoc文檔;
結(jié)合類圖等工具方便理解;

六、參考
Apache Shiro
跟我學(xué)Shiro目錄貼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容