shiro教程(2)- shiro介绍
shiro教程系列
shiro教程(3)-shiro授權
1?shiro介紹?
1.1?什么是shiro
Shiro是apache旗下一個開源框架,它將軟件系統的安全認證相關的功能抽取出來,實現用戶身份認證,權限授權、加密、會話管理等功能,組成了一個通用的安全認證框架。
1.2?為什么要學shiro
既然shiro將安全認證相關的功能抽取出來組成一個框架,使用shiro就可以非常快速的完成認證、授權等功能的開發,降低系統成本。
shiro使用廣泛,shiro可以運行在web應用,非web應用,集群分布式應用中越來越多的用戶開始使用shiro。
java領域中spring security(原名Acegi)也是一個開源的權限管理框架,但是spring security依賴spring運行,而shiro就相對獨立,最主要是因為shiro使用簡單、靈活,所以現在越來越多的用戶選擇shiro。
1.3?Shiro架構
?
1.3.1?Subject
Subject即主體,外部應用與subject進行交互,subject記錄了當前操作用戶,將用戶的概念理解為當前操作的主體,可能是一個通過瀏覽器請求的用戶,也可能是一個運行的程序。 Subject在shiro中是一個接口,接口中定義了很多認證授相關的方法,外部程序通過subject進行認證授,而subject是通過SecurityManager安全管理器進行認證授權
1.3.2?SecurityManager?
SecurityManager即安全管理器,對全部的subject進行安全管理,它是shiro的核心,負責對所有的subject進行安全管理。通過SecurityManager可以完成subject的認證、授權等,實質上SecurityManager是通過Authenticator進行認證,通過Authorizer進行授權,通過SessionManager進行會話管理等。
SecurityManager是一個接口,繼承了Authenticator, Authorizer, SessionManager這三個接口。
1.3.3?Authenticator
Authenticator即認證器,對用戶身份進行認證,Authenticator是一個接口,shiro提供ModularRealmAuthenticator實現類,通過ModularRealmAuthenticator基本上可以滿足大多數需求,也可以自定義認證器。
1.3.4?Authorizer
Authorizer即授權器,用戶通過認證器認證通過,在訪問功能時需要通過授權器判斷用戶是否有此功能的操作權限。
1.3.5?realm
Realm即領域,相當于datasource數據源,securityManager進行安全認證需要通過Realm獲取用戶權限數據,比如:如果用戶身份數據在數據庫那么realm就需要從數據庫獲取用戶身份信息。
注意:不要把realm理解成只是從數據源取數據,在realm中還有認證授權校驗的相關的代碼。
1.3.6?sessionManager
sessionManager即會話管理,shiro框架定義了一套會話管理,它不依賴web容器的session,所以shiro可以使用在非web應用上,也可以將分布式應用的會話集中在一點管理,此特性可使它實現單點登錄。
1.3.7?SessionDAO
SessionDAO即會話dao,是對session會話操作的一套接口,比如要將session存儲到數據庫,可以通過jdbc將會話存儲到數據庫。
1.3.8?CacheManager
CacheManager即緩存管理,將用戶權限數據存儲在緩存,這樣可以提高性能。
1.3.9?Cryptography
Cryptography即密碼管理,shiro提供了一套加密/解密的組件,方便開發。比如提供常用的散列、加/解密等功能。
1.4?shiro的jar包
與其它java開源框架類似,將shiro的jar包加入項目就可以使用shiro提供的功能了。shiro-core是核心包必須選用,還提供了與web整合的shiro-web、與spring整合的shiro-spring、與任務調度quartz整合的shiro-quartz等,下邊是shiro各jar包的maven坐標。
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-quartz</artifactId><version>1.2.3</version></dependency>也可以通過引入shiro-all包括shiro所有的包:<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-all</artifactId><version>1.2.3</version></dependency>參考lib目錄 :
?
2?shiro認證
2.1 認證流程
2.2?入門程序(用戶登陸和退出)
2.2.1?創建java工程
jdk版本:1.7.0_72
eclipse:elipse-indigo
2.2.2?加入shiro-core的Jar包及依賴包
?
2.2.3?log4j.properties日志配置文件
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
?
2.2.4?shiro.ini
通過Shiro.ini配置文件初始化SecurityManager環境。
配置 eclipse支持ini文件編輯:
在eclipse配置后,在classpath創建shiro.ini配置文件,為了方便測試將用戶名和密碼配置的shiro.ini配置文件中:
[users]
zhang=123
lisi=123
2.2.5?認證代碼
// 用戶登陸、用戶退出@Testpublic void testLoginLogout() {// 構建SecurityManager工廠,IniSecurityManagerFactory可以從ini文件中初始化SecurityManager環境Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");// 通過工廠創建SecurityManagerSecurityManager securityManager = factory.getInstance();// 將securityManager設置到運行環境中SecurityUtils.setSecurityManager(securityManager);// 創建一個Subject實例,該實例認證要使用上邊創建的securityManager進行Subject subject = SecurityUtils.getSubject();// 創建token令牌,記錄用戶認證的身份和憑證即賬號和密碼UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");try {// 用戶登陸subject.login(token);} catch (AuthenticationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 用戶認證狀態Boolean isAuthenticated = subject.isAuthenticated();System.out.println("用戶認證狀態:" + isAuthenticated);// 用戶退出subject.logout();isAuthenticated = subject.isAuthenticated();System.out.println("用戶認證狀態:" + isAuthenticated);}2.2.6?認證執行流程
1、?創建token令牌,token中有用戶提交的認證信息即賬號和密碼
2、?執行subject.login(token),最終由securityManager通過Authenticator進行認證
3、 Authenticator的實現ModularRealmAuthenticator調用realm從ini配置文件取用戶真實的賬號和密碼,這里使用的是IniRealm(shiro自帶)
4、?IniRealm先根據token中的賬號去ini中找該賬號,如果找不到則給ModularRealmAuthenticator返回null,如果找到則匹配密碼,匹配密碼成功則認證通過。
2.2.7?常見的異常
UnknownAccountException
賬號不存在異常如下:
org.apache.shiro.authc.UnknownAccountException: No account found for user。。。。
IncorrectCredentialsException
當輸入密碼錯誤會拋此異常,如下:
org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - zhangsan, rememberMe=false] did not match the expected credentials.
更多如下:
DisabledAccountException(帳號被禁用)
LockedAccountException(帳號被鎖定)
ExcessiveAttemptsException(登錄失敗次數過多)
ExpiredCredentialsException(憑證過期)等
2.3?自定義Realm
上邊的程序使用的是Shiro自帶的IniRealm,IniRealm從ini配置文件中讀取用戶的信息,大部分情況下需要從系統的數據庫中讀取用戶信息,所以需要自定義realm。
2.3.1?shiro提供的realm
最基礎的是Realm接口,CachingRealm負責緩存處理,AuthenticationRealm負責認證,AuthorizingRealm負責授權,通常自定義的realm繼承AuthorizingRealm。
2.3.2?自定義Realm
public class CustomRealm1 extends AuthorizingRealm {@Overridepublic String getName() {return "customRealm1";}//支持UsernamePasswordToken@Overridepublic boolean supports(AuthenticationToken token) {return token instanceof UsernamePasswordToken;}//認證@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//從token中 獲取用戶身份信息String username = (String) token.getPrincipal();//拿username從數據庫中查詢//....//如果查詢不到則返回nullif(!username.equals("zhang")){//這里模擬查詢不到return null;}//獲取從數據庫查詢出來的用戶密碼String password = "123";//這里使用靜態數據模擬。。//返回認證信息由父類AuthenticatingRealm進行認證SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());return simpleAuthenticationInfo;}//授權@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {// TODO Auto-generated method stubreturn null;}}2.3.3?shiro-realm.ini
[main]#自定義 realmcustomRealm=com.sihai.shiro.authentication.realm.CustomRealm1#將realm設置到securityManagersecurityManager.realms=$customRealm2.3.4?測試代碼
測試代碼同入門程序,將ini的地址修改為shiro-realm.ini。
分別模擬賬號不存在、密碼錯誤、賬號和密碼正確進行測試。
2.4?散列算法
散列算法一般用于生成一段文本的摘要信息,散列算法不可逆,將內容可以生成摘要,無法將摘要轉成原始內容。散列算法常用于對密碼進行散列,常用的散列算法有MD5、SHA。
一般散列算法需要提供一個salt(鹽)與原始內容生成摘要信息,這樣做的目的是為了安全性,比如:111111的md5值是:96e79218965eb72c92a549dd5a330112,拿著“96e79218965eb72c92a549dd5a330112”去md5破解網站很容易進行破解,如果要是對111111和salt(鹽,一個隨機數)進行散列,這樣雖然密碼都是111111加不同的鹽會生成不同的散列值。
2.4.1?例子
//md5加密,不加鹽String password_md5 = new Md5Hash("111111").toString();System.out.println("md5加密,不加鹽="+password_md5);//md5加密,加鹽,一次散列String password_md5_sale_1 = new Md5Hash("111111", "eteokues", 1).toString();System.out.println("password_md5_sale_1="+password_md5_sale_1);String password_md5_sale_2 = new Md5Hash("111111", "uiwueylm", 1).toString();System.out.println("password_md5_sale_2="+password_md5_sale_2);//兩次散列相當于md5(md5())//使用SimpleHashString simpleHash = new SimpleHash("MD5", "111111", "eteokues",1).toString();System.out.println(simpleHash);2.4.2?在realm中使用
實際應用是將鹽和散列后的值存在數據庫中,自動realm從數據庫取出鹽和加密后的值由shiro完成密碼校驗。
2.4.2.1?自定義realm
@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//用戶賬號String username = (String) token.getPrincipal();//根據用戶賬號從數據庫取出鹽和加密后的值//..這里使用靜態數據//如果根據賬號沒有找到用戶信息則返回null,shiro拋出異常“賬號不存在”//按照固定規則加密碼結果 ,此密碼 要在數據庫存儲,原始密碼 是111111,鹽是eteokuesString password = "cb571f7bd7a6f73ab004a70322b963d5";//鹽,隨機數,此隨機數也在數據庫存儲String salt = "eteokues";//返回認證信息SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt),getName());return simpleAuthenticationInfo;}2.4.2.2?realm配置
配置shiro-cryptography.ini
[main]#定義憑證匹配器credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher#散列算法credentialsMatcher.hashAlgorithmName=md5#散列次數credentialsMatcher.hashIterations=1#將憑證匹配器設置到realmcustomRealm=com.sihai.shiro.authentication.realm.CustomRealm2customRealm.credentialsMatcher=$credentialsMatchersecurityManager.realms=$customRealm?
2.4.2.3?測試代碼
測試代碼同上個章節,注意修改ini路徑。
總結
以上是生活随笔為你收集整理的shiro教程(2)- shiro介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝桥杯-最大的算式(java)
- 下一篇: shiro教程(3)-shiro授权