身份驗證,即在應用中誰能證實他就是他本人。通常提供如他們的身份ID一些標識信息來代表他就是他本人,如提供身份證,用戶名/密碼來證實。java
在shiro中,用戶須要提供principals (身份)和credentials(證實)給shiro,從而應用能驗證用戶身份:mysql
principals:身份,即主體的標識屬性,能夠是任何東西,如用戶名、郵箱等,惟一便可。一個主體能夠有多個principals,但只有一個Primary principals,通常是用戶名/密碼/手機號。web
credentials:證實/憑證,即只有主體知道的安全值,如密碼/數字證書等。sql
最多見的principals和credentials組合就是用戶名/密碼了。接下來先進行一個基本的身份認證。數據庫
另外兩個相關的概念是以前提到的Subject及Realm,分別是主體及驗證主體的數據源。apache
1. 環境準備
本文使用Maven構建,所以須要一點Maven知識。首先準備環境依賴: api
Java代碼緩存
- <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依賴便可。安全
2. 登陸/退出
一、首先準備一些用戶身份/憑據(shiro.ini)ide
Java代碼
- [users]
- jack=111
- tom=222
此處使用ini配置文件,經過[users]指定了兩個主體:jack/1十一、tom/222。
二、測試用例
Java代碼
- @Test
- public void test() {
- //一、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
- Factory<org.apache.shiro.mgt.SecurityManager> factory =
- new IniSecurityManagerFactory("classpath:shiro.ini");
- //二、獲得SecurityManager實例 並綁定給SecurityUtils
- org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
- SecurityUtils.setSecurityManager(securityManager);
- //三、獲得Subject及建立用戶名/密碼身份驗證Token(即用戶身份/憑證)
- Subject subject = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken("jack", "111");
-
- try {
- //四、登陸,即身份驗證
- subject.login(token);
- } catch (AuthenticationException e) {
- //五、身份驗證失敗
- }
-
- Assert.assertEquals(true, subject.isAuthenticated()); //斷言用戶已經登陸
-
- //六、退出
- subject.logout();
- }
-
2.一、首先經過new IniSecurityManagerFactory並指定一個ini配置文件來建立一個SecurityManager工廠;
2.二、接着獲取SecurityManager並綁定到SecurityUtils,這是一個全局設置,設置一次便可;
2.三、經過SecurityUtils獲得Subject,其會自動綁定到當前線程;若是在web環境在請求結束時須要解除綁定;而後獲取身份驗證的Token,如用戶名/密碼;
2.四、調用subject.login方法進行登陸,其會自動委託給SecurityManager.login方法進行登陸;
2.五、若是身份驗證失敗請捕獲AuthenticationException或其子類,常見的如:
DisabledAccountException(禁用的賬號)、LockedAccountException(鎖定的賬號)、UnknownAccountException(錯誤的賬號)、ExcessiveAttemptsException(登陸失敗次數過多)、IncorrectCredentialsException (錯誤的憑證)、ExpiredCredentialsException(過時的憑證)等,具體請查看其繼承關係;對於頁面的錯誤消息展現,最好使用如「用戶名/密碼錯誤」而不是「用戶名錯誤」/「密碼錯誤」,防止一些惡意用戶非法掃描賬號庫;
2.六、最後能夠調用subject.logout退出,其會自動委託給SecurityManager.logout方法退出。
從如上代碼可總結出身份驗證的步驟:
一、收集用戶身份/憑證,即如用戶名/密碼;
二、調用Subject.login進行登陸,若是失敗將獲得相應的AuthenticationException異常,根據異常提示用戶錯誤信息;不然登陸成功;
三、最後調用Subject.logout進行退出操做。
如上測試的幾個問題:
一、用戶名/密碼硬編碼在ini配置文件,之後須要改爲如數據庫存儲,且密碼須要加密存儲;
二、用戶身份Token可能不只僅是用戶名/密碼,也可能還有其餘的,如登陸時容許用戶名/郵箱/手機號同時登陸。
3. 身份認證流程
![](http://static.javashuo.com/static/loading.gif)
流程以下:
一、首先調用Subject.login(token)進行登陸,其會自動委託給Security Manager,調用以前必須經過SecurityUtils. setSecurityManager()設置;
二、SecurityManager負責真正的身份驗證邏輯;它會委託給Authenticator進行身份驗證;
三、Authenticator纔是真正的身份驗證者,Shiro API中核心的身份認證入口點,此處能夠自定義插入本身的實現;
四、Authenticator可能會委託給相應的AuthenticationStrategy進行多Realm身份驗證,默認ModularRealmAuthenticator會調用AuthenticationStrategy進行多Realm身份驗證;
五、Authenticator會把相應的token傳入Realm,從Realm獲取身份驗證信息,若是沒有返回/拋出異常表示身份驗證失敗了。此處能夠配置多個Realm,將按照相應的順序及策略進行訪問。
4. Realm
Realm:域,Shiro從從Realm獲取安全數據(如用戶、角色、權限),就是說SecurityManager要驗證用戶身份,那麼它須要從Realm獲取相應的用戶進行比較以肯定用戶身份是否合法;也須要從Realm獲得用戶相應的角色/權限進行驗證用戶是否能進行操做;能夠把Realm當作DataSource,即安全數據源。如以前的ini配置方式將使用org.apache.shiro.realm.text.IniRealm。
org.apache.shiro.realm.Realm接口以下:
Java代碼
- String getName(); //返回一個惟一的Realm名字
- boolean supports(AuthenticationToken token); //判斷此Realm是否支持此Token
- AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws
- AuthenticationException; //根據Token獲取認證信息
單Realm配置
一、自定義Realm實現:
Java代碼
- public class MyRealm implements Realm {
- @Override
- public String getName() {
- return "myrealm";
- }
- @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(!"jack".equals(username)) {
- throw new UnknownAccountException(); //若是用戶名錯誤
- }
- if(!"111".equals(password)) {
- throw new IncorrectCredentialsException(); //若是密碼錯誤
- }
- //若是身份認證驗證成功,返回一個AuthenticationInfo實現;
- return new SimpleAuthenticationInfo(username, password, getName());
- }
- }
二、ini配置文件指定自定義Realm實現(shiro-realm.ini)
Java代碼
- #聲明一個realm
- myRealm=com.shiro.realm.MyRealm
- #指定securityManager的realms實現
- securityManager.realms=$myRealm
經過$name來引入以前的realm定義
多Realm配置
一、ini配置文件(shiro-multi-realm.ini)
Java代碼
- #聲明一個realm
- myRealmA=com.shiro.realm.MyRealmA
- myRealmB=com.shiro.realm.MyRealmB
- #指定securityManager的realms實現
- securityManager.realms=$myRealmA,$myRealmB
securityManager會按照realms指定的順序進行身份認證。此處咱們使用顯示指定順序的方式指定了Realm的順序,若是刪除「securityManager.realms=$myRealmA,$myRealmB」,那麼securityManager會按照realm聲明的順序進行使用(即無需設置realms屬性,其會自動發現),當咱們顯示指定realm後,其餘沒有指定realm將被忽略,如「securityManager.realms=$myRealmA」,那麼myRealmB不會被自動設置進去。
Shiro默認提供的Realm
![](http://static.javashuo.com/static/loading.gif)
之後通常繼承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使用
一、數據庫及依賴
Java代碼
- <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鏈接池;
二、到數據庫shiro下建三張表:users(用戶名/密碼)、user_roles(用戶/角色)、roles_permissions(角色/權限),具體請參照shiro-example-chapter2/sql/shiro.sql;並添加一個用戶記錄,用戶名/密碼爲:jack/111;
三、ini配置(shiro-jdbc-realm.ini)
Java代碼
- 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方法進行賦值
三、$變量名 引用以前的一個對象實例
5. Authenticator及AuthenticationStrategy
Authenticator的職責是驗證用戶賬號,是Shiro API中身份驗證核心的入口點:
Java代碼
- public AuthenticationInfo authenticate(AuthenticationToken authenticationToken)
- throws AuthenticationException;
若是驗證成功,將返回AuthenticationInfo驗證信息;此信息中包含了身份及憑證;若是驗證失敗將拋出相應的AuthenticationException實現。
SecurityManager接口繼承了Authenticator,另外還有一個ModularRealmAuthenticator實現,其委託給多個Realm進行驗證,驗證規則經過AuthenticationStrategy接口指定,默認提供的實現:
FirstSuccessfulStrategy:只要有一個Realm驗證成功便可,只返回第一個Realm身份驗證成功的認證信息,其餘的忽略;
AtLeastOneSuccessfulStrategy:只要有一個Realm驗證成功便可,和FirstSuccessfulStrategy不一樣,返回全部Realm身份驗證成功的認證信息;
AllSuccessfulStrategy:全部Realm驗證成功纔算成功,且返回全部Realm身份驗證成功的認證信息,若是有一個失敗就失敗了。
ModularRealmAuthenticator默認使用AtLeastOneSuccessfulStrategy策略。
假設咱們有三個realm:
myRealmA: 用戶名/密碼爲jack/111時成功,且返回身份/憑據爲jack/111;
myRealmB: 用戶名/密碼爲tom/222時成功,且返回身份/憑據爲tom/222;
myRealmC: 用戶名/密碼爲jack/111時成功,且返回身份/憑據爲jack@sina.com/111,和myRealmA不一樣的是返回時的身份變了;
一、ini配置文件(shiro-authenticator-all-success.ini)
Java代碼
- #指定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
Java代碼
- myRealmA=com.shiro.realm.MyRealmA
- myRealmB=com.shiro.realm.MyRealmB
- myRealmC=com.shiro.realm.MyRealmC
- securityManager.realms=$myRealmA,$myRealmC
二、測試代碼
2.一、首先通用化登陸邏輯
Java代碼
- private void login(String configFile) {
- //一、獲取SecurityManager工廠,此處使用Ini配置文件初始化SecurityManager
- Factory<org.apache.shiro.mgt.SecurityManager> factory =
- new IniSecurityManagerFactory(configFile);
-
- //二、獲得SecurityManager實例 並綁定給SecurityUtils
- org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
- SecurityUtils.setSecurityManager(securityManager);
-
- //三、獲得Subject及建立用戶名/密碼身份驗證Token(即用戶身份/憑證)
- Subject subject = SecurityUtils.getSubject();
- UsernamePasswordToken token = new UsernamePasswordToken("jack", "111");
- subject.login(token);
- }
2.二、測試AllSuccessfulStrategy成功:
Java代碼
- @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包含了jack和jack@sina.com身份信息。
2.三、測試AllSuccessfulStrategy失敗:
Java代碼
- @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=$myRealmA,$myRealmB;即myRealm驗證失敗。
對於AtLeastOneSuccessfulStrategy和FirstSuccessfulStrategy的惟一不一樣點,一個是返回全部驗證成功的Realm的認證信息;另外一個是隻返回第一個驗證成功的Realm的認證信息。
自定義AuthenticationStrategy實現,首先看其API:
Java代碼
- //在全部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實例都是無狀態的,全部每次都經過接口將相應的認證信息傳入下一次流程;經過如上接口能夠進行如合併/返回第一個驗證成功的認證信息。
自定義實現時通常繼承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy便可。