目錄:Shiro學(xué)習(xí)總結(jié)(目錄貼)
2.1次询、什么是認(rèn)證
??認(rèn)證是一個(gè)驗(yàn)證用戶是他們本人的過(guò)程。用戶需要提供系統(tǒng)識(shí)別并且信任的身份證或者一些和身份證相同作用的證明瓷叫。
??用戶需要提交
principals
和credentials
給Shiro
從而使應(yīng)用程序來(lái)驗(yàn)證身份屯吊。
-
Principals:
Subject
的身份屬性送巡,可以是任何東西如姓名,用戶名等唯一的東西如電子郵箱/用戶名盒卸。 -
Credentials:只有
Subject
知道的安全的值骗爆,如密碼,數(shù)字憑證等蔽介。
2.2摘投、認(rèn)證流程
- 程序調(diào)用
Subject.login
方法,通過(guò)AuthenticationToken
實(shí)例提交用戶的principals
和credentials
虹蓄。 -
Subject
的實(shí)例(DelegatingSubject
或者子類)委托給Security Manager
犀呼,
Security Manager
調(diào)用securityManager.login(token)
方法負(fù)責(zé)真正的身份驗(yàn)證。 -
Security Manager
委托給Authenticator進(jìn)行身份驗(yàn)證薇组,Authenticator
才是真正的身份驗(yàn)證者外臂,Shiro API中核心的身份認(rèn)證入口點(diǎn),此處可以自定義插入自己的實(shí)現(xiàn)律胀。 -
Authenticator
可能會(huì)委托給相應(yīng)的AuthenticationStrategy
進(jìn)行多Realm
身份驗(yàn)證宋光,默認(rèn)ModularRealmAuthenticator
會(huì)調(diào)用AuthenticationStrategy
進(jìn)行多Realm
身份驗(yàn)證; -
Authenticato
r會(huì)把相應(yīng)的token
傳入Realm
炭菌,從Realm
獲取身份驗(yàn)證信息罪佳,如果沒(méi)有返回/拋出異常表示身份驗(yàn)證失敗了。此處可以配置多個(gè)Realm
黑低,將按照相應(yīng)的順序及策略進(jìn)行訪問(wèn)菇民。
2.3、 Authenticator
??綜上所述投储,SecurityManager
實(shí)現(xiàn)默認(rèn)使用 ModularRealmAuthenticator
實(shí)例第练,ModularRealmAuthenticator
同時(shí)支持單個(gè)和多個(gè)Realm
,如果配置了多個(gè)Realm
玛荞,將于AuthenticationStrategy
來(lái)協(xié)調(diào)工作娇掏。
??如果想SecurityManager
用自定義Authenticator
實(shí)現(xiàn)來(lái)配置,你可以這樣做勋眯,shiro.ini
例如:
authenticator = com.foo.bar.CustomAuthenticator
securityManager.authenticator = $authenticator
在實(shí)踐中婴梧,ModularRealmAuthenticator
支持大多數(shù)的需要。
2.4客蹋、 AuthenticationStrategy
??為應(yīng)用程序配置兩個(gè)或更多Realm
時(shí)塞蹭,ModularRealmAuthenticator
依賴于內(nèi)部AuthenticationStrategy
組件來(lái)確定認(rèn)證成功或失敗。AuthenticationStrategy
是一個(gè)無(wú)狀態(tài)的組件讶坯,在認(rèn)證嘗試期間被查詢4次(這4個(gè)交互所需的任何必要狀態(tài)將作為方法參數(shù)給出):
- 在任何
Realm
被調(diào)用之前 - 在一個(gè)單獨(dú)的
Realm getAuthenticationInfo
方法被調(diào)用之前 - 立即在一個(gè)單獨(dú)的
Realm getAuthenticationInfo
方法被調(diào)用之后 - 在所有
Realm
被調(diào)用之后
//在所有Realm驗(yàn)證之前調(diào)用
AuthenticationInfo beforeAllAttempts(
Collection<? extends Realm> realms, AuthenticationToken token)
throws AuthenticationException;
//在每個(gè)Realm之前調(diào)用
AuthenticationInfo beforeAttempt(
Realm realm, AuthenticationToken token, AuthenticationInfo aggregate)
throws AuthenticationException;
//在每個(gè)Realm之后調(diào)用
AuthenticationInfo afterAttempt(
Realm realm, AuthenticationToken token,
AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t)
throws AuthenticationException;
//在所有Realm之后調(diào)用
AuthenticationInfo afterAllAttempts(
AuthenticationToken token, AuthenticationInfo aggregate)
throws AuthenticationException;
Shiro
有3個(gè)具體AuthenticationStrategy
實(shí)現(xiàn):
AuthenticationStrategy 類 |
描述 |
---|---|
AtLeastOneSuccessfulStrategy |
如果一個(gè)(或多個(gè))Realm 認(rèn)證成功番电,則整體嘗試被認(rèn)為是成功的。如果沒(méi)有任何驗(yàn)證成功,則嘗試失敗漱办。 |
FirstSuccessfulStrategy |
僅使用從第一個(gè)成功驗(yàn)證的Realm 返回的信息这刷。所有進(jìn)一步的領(lǐng)土將被忽略。如果沒(méi)有任何驗(yàn)證成功娩井,則嘗試失敗暇屋。 |
AllSuccessfulStrategy |
所有配置的Realm 都必須成功進(jìn)行身份驗(yàn)證才能成功進(jìn)行整體嘗試。如果任何一個(gè)人未成功認(rèn)證洞辣,則嘗試失敗咐刨。 |
??在ModularRealmAuthenticator
默認(rèn)的AtLeastOneSuccessfulStrategy
實(shí)施,因?yàn)檫@是最常用的策略所需扬霜。但是定鸟,如果想要進(jìn)行配置,可以配置不同的策略:
authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy
??自定義實(shí)現(xiàn)時(shí)一般繼承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy
即可畜挥。
2.5、 Realm認(rèn)證順序
??指出ModularRealmAuthenticator
與Realm實(shí)例交互的迭代順序是非常重要的婴谱。
在ModularRealmAuthenticator
獲取SecurityManager
所配置的Realm
實(shí)例蟹但。在嘗試身份驗(yàn)證時(shí),它將遍歷該集合谭羔,并為每個(gè)Realm
支持提交的對(duì)象AuthenticationToken
調(diào)用Realm
的getAuthenticationInfo
方法华糖。
1. 隱式排序
在shiro.ini
配置如下:
blahRealm = com.company.blah.Realm
fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm
將會(huì)和
securityManager.realms = $blahRealm, $fooRealm, $barRealm
配置(可無(wú))順序一致。
2. 顯式排序
自定義順序
blahRealm = com.company.blah.Realm
fooRealm = com.company.foo.Realm
barRealm = com.company.another.Realm
securityManager.realms = $fooRealm, $barRealm, $blahRealm
2.6瘟裸、代碼示例
項(xiàng)目地址:GitHub
- 構(gòu)建項(xiàng)目環(huán)境客叉,引入
shiro-core
與junit
jar包(maven項(xiàng)目構(gòu)建請(qǐng)百度)。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
- 編寫測(cè)試類
package com.chenjy.shiro.authentication;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;
public class AuthenticationTest {
SimpleAccountRealm realm = new SimpleAccountRealm();
@Before
public void addUser() {
realm.addAccount("Shiro", "1234");
}
@Test
public void testAuthentication() {
//1. 構(gòu)建SecurityManager環(huán)境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
// 1.1 設(shè)置realm
defaultSecurityManager.setRealm(realm);
// 1.2 設(shè)置SecurityManager
SecurityUtils.setSecurityManager(defaultSecurityManager);
//2. 主體提交認(rèn)證
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken("Shiro", "1234");
subject.login(token);
System.out.println("isAuthenticated:" + subject.isAuthenticated());
subject.logout();
System.out.println("isAuthenticated:" + subject.isAuthenticated());
}
}
運(yùn)行結(jié)果為:
isAuthenticated:true
isAuthenticated:false
將用戶名更改為shiro
话告,運(yùn)行結(jié)果為:
org.apache.shiro.authc.UnknownAccountException: Realm [org.apache.shiro.realm.SimpleAccountRealm@61baa894] was unable to find account data for the submitted AuthenticationToken [org.apache.shiro.authc.UsernamePasswordToken - shiro, rememberMe=false].
……
拋出異常
org.apache.shiro.authc.UnknownAccountException
將密碼改為123456
兼搏,運(yùn)行結(jié)果為:
org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - Shiro, rememberMe=false] did not match the expected credentials.
……
拋出異常
org.apache.shiro.authc.IncorrectCredentialsException
以下是對(duì)認(rèn)證相關(guān)內(nèi)容補(bǔ)充(2018-05-26)。
跟隨代碼回顧Shiro
的認(rèn)證過(guò)程:
通過(guò)SecurityUtils.getSubject()獲取Subject實(shí)例subject沙郭,subject調(diào)用 subject.login(token)將AuthenticationToken實(shí)例提交認(rèn)證佛呻。
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken("Shiro", "123456");
subject.login(token);
查看subject.login(token)
的實(shí)現(xiàn)
public void login(AuthenticationToken token) throws AuthenticationException {
clearRunAsIdentitiesInternal();
Subject subject = securityManager.login(this, token);
PrincipalCollection principals;
……
}
可以看出subject.login(token)
將認(rèn)證委托給SecurityManager
,由其實(shí)例調(diào)用login
方法進(jìn)行認(rèn)證病线。在進(jìn)一步查看SecurityManager
認(rèn)證的實(shí)現(xiàn)
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
info = authenticate(token);
} catch (AuthenticationException ae) {
……
}
Subject loggedIn = createSubject(token, info, subject);
onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
return this.authenticator.authenticate(token);
}
不難看出SecurityManager
又將認(rèn)證委托給了Authenticator
吓著,而Authenticator
在驗(yàn)證時(shí)調(diào)用了ModularRealmAuthenticator
doAuthenticate(token)
方法,而doAuthenticate(token)
方法的實(shí)現(xiàn)便是通過(guò)遍歷Realm
獲取用戶的認(rèn)證權(quán)限信息送挑。
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) {
……
}
} catch (Throwable t) {
……
}
log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info);
notifySuccess(token, info);
return info;
}
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)) {
……
}
AuthenticationInfo info = realm.getAuthenticationInfo(token);
if (info == null) {
……
}
return info;
}
而Realm獲取認(rèn)證信息是通過(guò)AuthenticatingRealm
調(diào)用getAuthenticationInfo
方法绑莺,具體的實(shí)現(xiàn)便是與我們代碼中通過(guò)SimpleAccountRealm
設(shè)置的用戶名和密碼進(jìn)行對(duì)比。
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info = getCachedAuthenticationInfo(token);
if (info == null) {
……
} else {
log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
}
……
return info;
}
//SimpleAccountRealm
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
SimpleAccount account = getUser(upToken.getUsername());
if (account != null) {
……
}
return account;
}
在就再一次驗(yàn)證了之前提到過(guò)的Shiro
的認(rèn)證流程
在此分析一下
AuthenticationToken
的結(jié)構(gòu)惕耕,由下圖可看出RememberMeAuthenticationToken
和HostAuthenticationToken
繼承了AuthenticationToken
纺裁。UsernamePasswordToken
實(shí)現(xiàn)了RememberMeAuthenticationToken
和HostAuthenticationToken
。UsernamePasswordToken
之中的方法也如下圖所示
AuthenticationToken體系結(jié)構(gòu)
Shiro默認(rèn)提供的Realm
Shiro默認(rèn)提供的Realm
以后一般繼承AuthorizingRealm
(授權(quán))即可司澎;其繼承了AuthenticatingRealm
(即身份驗(yàn)證)对扶,而且也間接繼承了CachingRealm
(帶有緩存實(shí)現(xiàn))区赵。其中主要默認(rèn)實(shí)現(xiàn)如下:
org.apache.shiro.realm.text.IniRealm
:[users]部分指定用戶名/密碼及其角色;[roles]部分指定角色即權(quán)限信息浪南;
org.apache.shiro.realm.text.PropertiesRealm
:user.username=password,role1,role2
指定用戶名/密碼及其角色笼才;role.role1=permission1,permission2
指定角色及權(quán)限信息;
org.apache.shiro.realm.jdbc.JdbcRealm
:通過(guò)sql查詢相應(yīng)的信息络凿,如select password from users where username = ?
獲取用戶密碼骡送,select password, password_salt from users where username = ?
獲取用戶密碼及鹽;select role_name from user_roles where username = ?
獲取用戶角色絮记;select permission from roles_permissions where role_name = ?
獲取角色對(duì)應(yīng)的權(quán)限信息摔踱;也可以調(diào)用相應(yīng)的api進(jìn)行自定義sql;
關(guān)于更多Realm的信息將在后面的章節(jié)詳細(xì)講解怨愤。在此就不再贅述派敷。
參考文檔: