身份驗證,即在應用中誰能證明他就是他本人。一般提供如他們的身份 ID 一些標識信息來表明他就是他本人,如提供身份證,用戶名 / 密碼來證明。
在 shiro 中,用戶需要提供 principals
(身份)和 credentials
(證明)給 shiro,從而應用能驗證用戶身份:
principals:身份,即主體的標識屬性,可以是任何東西,如用戶名、郵箱等,唯一即可。一個主體可以有多個 principals
,但只有一個 Primary principals
,一般是用戶名 / 密碼 / 手機號。
credentials:證明 / 憑證,即只有主體知道的安全值,如密碼 / 數字證書等。
最常見的 principals
和 credentials
組合就是用戶名 / 密碼了。接下來先進行一個基本的身份認證。
另外兩個相關的概念是之前提到的 Subject
及 Realm
,分別是主體及驗證主體的數據源。
本文使用 Maven
構建,因此需要一點 Maven
知識。首先準備環(huán)境依賴:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
添加 junit
、common-logging
及 shiro-core
依賴即可。
1、首先準備一些用戶身份 / 憑據(shiro.ini)
[users]
zhang=123
wang=123
此處使用 ini 配置文件,通過 [users] 指定了兩個主體:zhang/123、wang/123。
2、測試用例(com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest)
@Test
public void testHelloworld() {
//1、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2、得到SecurityManager實例 并綁定給SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及創(chuàng)建用戶名/密碼身份驗證Token(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
try {
//4、登錄,即身份驗證
subject.login(token);
} catch (AuthenticationException e) {
//5、身份驗證失敗
}
Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登錄
//6、退出
subject.logout();
}
首先通過 new IniSecurityManagerFactory
并指定一個 ini
配置文件來創(chuàng)建一個 SecurityManager
工廠;
接著獲取 SecurityManager
并綁定到 SecurityUtils
,這是一個全局設置,設置一次即可;
通過 SecurityUtils
得到 Subject
,其會自動綁定到當前線程;如果在 web 環(huán)境在請求結束時需要解除綁定;然后獲取身份驗證的 Token
,如用戶名 / 密碼;
調用 subject.login
方法進行登錄,其會自動委托給 SecurityManager.login
方法進行登錄;
如果身份驗證失敗請捕獲 AuthenticationException
或其子類,常見的如: DisabledAccountException
(禁用的帳號)、LockedAccountException
(鎖定的帳號)、UnknownAccountException
(錯誤的帳號)、ExcessiveAttemptsException
(登錄失敗次數過多)、IncorrectCredentialsException
(錯誤的憑證)、ExpiredCredentialsException
(過期的憑證)等,具體請查看其繼承關系;對于頁面的錯誤消息展示,最好使用如
“用戶名 / 密碼錯誤” 而不是 “用戶名錯誤”/“密碼錯誤”,防止一些惡意用戶非法掃描帳號庫;
subject.logout
退出,其會自動委托給 SecurityManager.logout
方法退出。從如上代碼可總結出身份驗證的步驟:
收集用戶身份 / 憑證,即如用戶名 / 密碼;
調用 Subject.login
進行登錄,如果失敗將得到相應的 AuthenticationException
異常,根據異常提示用戶錯誤信息;否則登錄成功;
Subject.logout
進行退出操作。如上測試的幾個問題:
用戶名 / 密碼硬編碼在 ini
配置文件,以后需要改成如數據庫存儲,且密碼需要加密存儲;
Token
可能不僅僅是用戶名 / 密碼,也可能還有其他的,如登錄時允許用戶名 / 郵箱 / 手機號同時登錄。
流程如下:
Subject.login(token)
進行登錄,其會自動委托給 Security Manager
,調用之前必須通過 SecurityUtils.setSecurityManager()
設置;SecurityManager
負責真正的身份驗證邏輯;它會委托給 Authenticator
進行身份驗證;Authenticator
才是真正的身份驗證者,Shiro API
中核心的身份認證入口點,此處可以自定義插入自己的實現;Authenticator
可能會委托給相應的 AuthenticationStrategy
進行多 Realm
身份驗證,默認 ModularRealmAuthenticator
會調用 AuthenticationStrategy
進行多 Realm
身份驗證;Authenticator
會把相應的 token
傳入 Realm
,從 Realm
獲取身份驗證信息,如果沒有返回 / 拋出異常表示身份驗證成功了。此處可以配置多個 Realm
,將按照相應的順序及策略進行訪問。Realm:域,Shiro
從 Realm
獲取安全數據(如用戶、角色、權限),就是說 SecurityManager
要驗證用戶身份,那么它需要從 Realm
獲取相應的用戶進行比較以確定用戶身份是否合法;也需要從 Realm
得到用戶相應的角色 / 權限進行驗證用戶是否能進行操作;可以把 Realm
看成 DataSource
,即安全數據源。如我們之前的 ini
配置方式將使用 org.apache.shiro.realm.text.IniRealm
。
org.apache.shiro.realm.Realm
接口如下:
String getName(); //返回一個唯一的Realm名字
boolean supports(AuthenticationToken token); //判斷此Realm是否支持此Token
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException; //根據Token獲取認證信息
單 Realm
配置
1、自定義 Realm
實現(com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1):
public class MyRealm1 implements Realm {
@Override
public String getName() {
return "myrealm1";
}
@Override
public boolean supports(AuthenticationToken token) {
//僅支持UsernamePasswordToken類型的Token
return token instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal(); //得到用戶名
String password = new String((char[])token.getCredentials()); //得到密碼
if(!"zhang".equals(username)) {
throw new UnknownAccountException(); //如果用戶名錯誤
}
if(!"123".equals(password)) {
throw new IncorrectCredentialsException(); //如果密碼錯誤
}
//如果身份認證驗證成功,返回一個AuthenticationInfo實現;
return new SimpleAuthenticationInfo(username, password, getName());
}
}
2、ini
配置文件指定自定義 Realm
實現 (shiro-realm.ini)
\#聲明一個realm
myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
\#指定securityManager的realms實現
securityManager.realms=$myRealm1
通過 $name
來引入之前的 realm
定義
3、測試用例請參考 com.github.zhangkaitao.shiro.chapter
2.LoginLogoutTest
的 testCustomRealm
測試方法,只需要把之前的 shiro.ini
配置文件改成 shiro-realm.ini
即可。
多 Realm
配置
1、ini
配置文件(shiro-multi-realm.ini)
\#聲明一個realm
myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2
\#指定securityManager的realms實現
securityManager.realms=$myRealm1,$myRealm2
securityManager
會按照 realms
指定的順序進行身份認證。此處我們使用顯示指定順序的方式指定了 Realm
的順序,如果刪除 “securityManager.realms=$myRealm1,$myRealm2”,那么securityManager
會按照 realm
聲明的順序進行使用(即無需設置 realms
屬性,其會自動發(fā)現),當我們顯示指定 realm
后,其他沒有指定 realm
將被忽略,如
“securityManager.realms=$myRealm1”,那么 myRealm2
不會被自動設置進去。
2、測試用例請參考 com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest 的 testCustomMultiRealm 測試方法。
Shiro
默認提供的 Realm
以后一般繼承 AuthorizingRealm
(授權)即可;其繼承了 AuthenticatingRealm
(即身份驗證),而且也間接繼承了 CachingRealm
(帶有緩存實現)。其中主要默認實現如下:
org.apache.shiro.realm.text.IniRealm:[users] 部分指定用戶名 / 密碼及其角色;[roles] 部分指定角色即權限信息;
org.apache.shiro.realm.text.PropertiesRealm: user.username=password,role1,role2 指定用戶名 / 密碼及其角色;role.role1=permission1,permission2 指定角色及權限信息;
org.apache.shiro.realm.jdbc.JdbcRealm:通過 sql 查詢相應的信息,如 “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 = ?” 獲取角色對應的權限信息;也可以調用相應的 api 進行自定義 sql;
JDBC Realm 使用
1、數據庫及依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.23</version>
</dependency>
本文將使用 mysql 數據庫及 druid 連接池;
2、到數據庫 shiro 下建三張表:users
(用戶名 / 密碼)、user_roles
(用戶 / 角色)、roles_permissions
(角色 / 權限),具體請參照 shiro-example-chapter2/sql/shiro.sql;并添加一個用戶記錄,用戶名 / 密碼為 zhang/123;
3、ini
配置(shiro-jdbc-realm.ini)
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.alibaba.druid.pool.DruidDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/shiro
dataSource.username=root
\#dataSource.password=
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
setter
方法進行賦值 com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest
的 testJDBCRealm
方法,和之前的沒什么區(qū)別。Authenticator 的職責是驗證用戶帳號,是 Shiro API 中身份驗證核心的入口點:
public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)
throws AuthenticationException;
如果驗證成功,將返回 AuthenticationInfo
驗證信息;此信息中包含了身份及憑證;如果驗證失敗將拋出相應的 AuthenticationException
實現。
SecurityManager
接口繼承了 Authenticator
,另外還有一個 ModularRealmAuthenticator
實現,其委托給多個 Realm
進行驗證,驗證規(guī)則通過 AuthenticationStrategy
接口指定,默認提供的實現:
FirstSuccessfulStrategy
:只要有一個 Realm
驗證成功即可,只返回第一個 Realm
身份驗證成功的認證信息,其他的忽略;
AtLeastOneSuccessfulStrategy/
:只要有一個 Realm
驗證成功即可,和 FirstSuccessfulStrategy
不同,返回所有 Realm
身份驗證成功的認證信息;
AllSuccessfulStrategy
:所有 Realm
驗證成功才算成功,且返回所有 Realm
身份驗證成功的認證信息,如果有一個失敗就失敗了。
ModularRealmAuthenticator
默認使用 AtLeastOneSuccessfulStrategy
策略。
假設我們有三個 realm
:
myRealm1
: 用戶名 / 密碼為 zhang/123 時成功,且返回身份 / 憑據為 zhang/123;
myRealm2
: 用戶名 / 密碼為 wang/123 時成功,且返回身份 / 憑據為 wang/123;
myRealm3
: 用戶名 / 密碼為 zhang/123 時成功,且返回身份 / 憑據為 zhang@163.com/123,和 myRealm1 不同的是返回時的身份變了;
1、ini 配置文件 (shiro-authenticator-all-success.ini)
\#指定securityManager的authenticator實現
authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
securityManager.authenticator=$authenticator
\#指定securityManager.authenticator的authenticationStrategy
allSuccessfulStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategy
securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy
myRealm1=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1
myRealm2=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm2
myRealm3=com.github.zhangkaitao.shiro.chapter2.realm.MyRealm3
securityManager.realms=$myRealm1,$myRealm3
2、測試代碼(com.github.zhangkaitao.shiro.chapter2.AuthenticatorTest)
private void login(String configFile) {
//1、獲取SecurityManager
工廠,此處使用Ini
配置文件初始化SecurityManager
Factory<org.apache.shiro.mgt.SecurityManager> factory =
new IniSecurityManagerFactory(configFile);
//2、得到SecurityManager
實例 并綁定給SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject
及創(chuàng)建用戶名/密碼身份驗證Token
(即用戶身份/憑證)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
subject.login(token);
}
AllSuccessfulStrategy
成功: @Test
public void testAllSuccessfulStrategyWithSuccess() {
login("classpath:shiro-authenticator-all-success.ini");
Subject subject = SecurityUtils.getSubject();
//得到一個身份集合,其包含了Realm
驗證成功的身份信息
PrincipalCollection principalCollection = subject.getPrincipals();
Assert.assertEquals(2, principalCollection.asList().size());
}
即 PrincipalCollection
包含了 zhang 和 zhang@163.com 身份信息。
AllSuccessfulStrategy
失?。?/li>
@Test(expected = UnknownAccountException.class)
public void testAllSuccessfulStrategyWithFail() {
login("classpath:shiro-authenticator-all-fail.ini");
Subject subject = SecurityUtils.getSubject();
}
shiro-authenticator-all-fail.ini
與 shiro-authenticator-all-success.ini
不同的配置是使用了 securityManager.realms=$myRealm1,$myRealm2
;即 myRealm
驗證失敗。
對于 AtLeastOneSuccessfulStrategy
和 FirstSuccessfulStrategy
的區(qū)別,請參照 testAtLeastOneSuccessfulStrategyWithSuccess
和 testFirstOneSuccessfulStrategyWithSuccess
測試方法。唯一不同點一個是返回所有驗證成功的 Realm
的認證信息;另一個是只返回第一個驗證成功的 Realm
的認證信息。
自定義 AuthenticationStrategy
實現,首先看其 API
:
//在所有Realm驗證之前調用
AuthenticationInfo beforeAllAttempts(
Collection<? extends Realm> realms, AuthenticationToken token)
throws AuthenticationException;
//在每個Realm之前調用
AuthenticationInfo beforeAttempt(
Realm realm, AuthenticationToken token, AuthenticationInfo aggregate)
throws AuthenticationException;
//在每個Realm之后調用
AuthenticationInfo afterAttempt(
Realm realm, AuthenticationToken token,
AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t)
throws AuthenticationException;
//在所有Realm之后調用
AuthenticationInfo afterAllAttempts(
AuthenticationToken token, AuthenticationInfo aggregate)
throws AuthenticationException;
因為每個 AuthenticationStrategy
實例都是無狀態(tài)的,所有每次都通過接口將相應的認證信息傳入下一次流程;通過如上接口可以進行如合并 / 返回第一個驗證成功的認證信息。
自定義實現時一般繼承 org.apache.shiro.authc.pam.AbstractAuthenticationStrategy
即可,具體可以參考代碼 com.github.zhangkaitao.shiro.chapter
2.authenticator.strategy
包下 OnlyOneAuthenticatorStrategy
和 AtLeastTwoAuthenticatorStrategy
。
更多建議: