二智哀、Shiro認(rèn)證

目錄:Shiro學(xué)習(xí)總結(jié)(目錄貼)

2.1次询、什么是認(rèn)證

Shiro Authentication

??認(rèn)證是一個(gè)驗(yàn)證用戶是他們本人的過(guò)程。用戶需要提供系統(tǒng)識(shí)別并且信任的身份證或者一些和身份證相同作用的證明瓷叫。
??用戶需要提交principalscredentialsShiro從而使應(yīng)用程序來(lái)驗(yàn)證身份屯吊。

  • PrincipalsSubject的身份屬性送巡,可以是任何東西如姓名,用戶名等唯一的東西如電子郵箱/用戶名盒卸。
  • Credentials:只有Subject知道的安全的值骗爆,如密碼,數(shù)字憑證等蔽介。

2.2摘投、認(rèn)證流程

認(rèn)證流程圖
  1. 程序調(diào)用Subject.login方法,通過(guò)AuthenticationToken實(shí)例提交用戶的principalscredentials虹蓄。
  2. Subject的實(shí)例(DelegatingSubject或者子類)委托給Security Manager犀呼,
    Security Manager調(diào)用securityManager.login(token)方法負(fù)責(zé)真正的身份驗(yàn)證。
  3. Security Manager委托給Authenticator進(jìn)行身份驗(yàn)證薇组,Authenticator才是真正的身份驗(yàn)證者外臂,Shiro API中核心的身份認(rèn)證入口點(diǎn),此處可以自定義插入自己的實(shí)現(xiàn)律胀。
  4. Authenticator可能會(huì)委托給相應(yīng)的AuthenticationStrategy進(jìn)行多Realm身份驗(yàn)證宋光,默認(rèn)ModularRealmAuthenticator會(huì)調(diào)用AuthenticationStrategy進(jìn)行多Realm身份驗(yàn)證;
  5. Authenticator會(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)用RealmgetAuthenticationInfo方法华糖。

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

  1. 構(gòu)建項(xiàng)目環(huán)境客叉,引入shiro-corejunitjar包(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>
  1. 編寫測(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)惕耕,由下圖可看出RememberMeAuthenticationTokenHostAuthenticationToken繼承了AuthenticationToken纺裁。UsernamePasswordToken實(shí)現(xiàn)了RememberMeAuthenticationTokenHostAuthenticationTokenUsernamePasswordToken之中的方法也如下圖所示

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.PropertiesRealmuser.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ì)講解怨愤。在此就不再贅述派敷。

參考文檔:

  1. Apache Shiro Reference Documentation
  2. 跟我學(xué)Shiro
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市撰洗,隨后出現(xiàn)的幾起案子篮愉,更是在濱河造成了極大的恐慌,老刑警劉巖差导,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件试躏,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡设褐,警方通過(guò)查閱死者的電腦和手機(jī)颠蕴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)助析,“玉大人犀被,你說(shuō)我怎么就攤上這事⊥饧剑” “怎么了弱判?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)锥惋。 經(jīng)常有香客問(wèn)我昌腰,道長(zhǎng),這世上最難降的妖魔是什么膀跌? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任遭商,我火速辦了婚禮,結(jié)果婚禮上捅伤,老公的妹妹穿的比我還像新娘劫流。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布祠汇。 她就那樣靜靜地躺著仍秤,像睡著了一般。 火紅的嫁衣襯著肌膚如雪可很。 梳的紋絲不亂的頭發(fā)上诗力,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音我抠,去河邊找鬼苇本。 笑死,一個(gè)胖子當(dāng)著我的面吹牛菜拓,可吹牛的內(nèi)容都是我干的瓣窄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼纳鼎,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼俺夕!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起贱鄙,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤劝贸,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后贰逾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體悬荣,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡菠秒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年疙剑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片践叠。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡言缤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出禁灼,到底是詐尸還是另有隱情管挟,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布弄捕,位于F島的核電站僻孝,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏守谓。R本人自食惡果不足惜穿铆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望斋荞。 院中可真熱鬧荞雏,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至筑辨,卻和暖如春俺驶,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背挖垛。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工痒钝, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人痢毒。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓送矩,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親哪替。 傳聞我的和親對(duì)象是個(gè)殘疾皇子栋荸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

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