shrio初体验(2)Realm
Realm:域,Shiro從從Realm獲取安全數(shù)據(jù)(如用戶、角色、權(quán)限),就是說SecurityManager要驗證用戶身份,那么它需要從Realm獲取相應的用戶進行比較以確定用戶身份是否合法;也需要從Realm得到用戶相應的角色/權(quán)限進行驗證用戶是否能進行操作;可以把Realm看成DataSource,即安全數(shù)據(jù)源。如我們之前的ini配置方式將使用org.apache.shiro.realm.text.IniRealm。
?
org.apache.shiro.realm.Realm接口如下:?
Java代碼???
單Realm配置
1、自定義Realm實現(xiàn)(com.github.zhangkaitao.shiro.chapter2.realm.MyRealm1):??
Java代碼???
2、ini配置文件指定自定義Realm實現(xiàn)(shiro-realm.ini)??
Java代碼??通過$name來引入之前的realm定義
?
3、測試用例請參考com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testCustomRealm測試方法,只需要把之前的shiro.ini配置文件改成shiro-realm.ini即可。
?
多Realm配置
1、ini配置文件(shiro-multi-realm.ini)??
Java代碼??securityManager會按照realms指定的順序進行身份認證。此處我們使用顯示指定順序的方式指定了Realm的順序,如果刪除“securityManager.realms=$myRealm1,$myRealm2”,那么securityManager會按照realm聲明的順序進行使用(即無需設(shè)置realms屬性,其會自動發(fā)現(xiàn)),當我們顯示指定realm后,其他沒有指定realm將被忽略,如“securityManager.realms=$myRealm1”,那么myRealm2不會被自動設(shè)置進去。
?
2、測試用例請參考com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testCustomMultiRealm測試方法。
?
Shiro默認提供的Realm
?
?
以后一般繼承AuthorizingRealm(授權(quán))即可;其繼承了AuthenticatingRealm(即身份驗證),而且也間接繼承了CachingRealm(帶有緩存實現(xiàn))。其中主要默認實現(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:通過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 = ?”獲取角色對應的權(quán)限信息;也可以調(diào)用相應的api進行自定義sql;
?
JDBC Realm使用
1、數(shù)據(jù)庫及依賴
Java代碼??本文將使用mysql數(shù)據(jù)庫及druid連接池;?
?
2、到數(shù)據(jù)庫shiro下建三張表:users(用戶名/密碼)、user_roles(用戶/角色)、roles_permissions(角色/權(quán)限),具體請參照shiro-example-chapter2/sql/shiro.sql;并添加一個用戶記錄,用戶名/密碼為zhang/123;
?
3、ini配置(shiro-jdbc-realm.ini)?
Java代碼??1、變量名=全限定類名會自動創(chuàng)建一個類實例
2、變量名.屬性=值?自動調(diào)用相應的setter方法進行賦值
3、$變量名?引用之前的一個對象實例?
4、測試代碼請參照com.github.zhangkaitao.shiro.chapter2.LoginLogoutTest的testJDBCRealm方法,和之前的沒什么區(qū)別。
轉(zhuǎn)載于:https://www.cnblogs.com/LvLoveYuForever/p/6207998.html
總結(jié)
以上是生活随笔為你收集整理的shrio初体验(2)Realm的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Jquery的事件操作和文档操作
- 下一篇: Python进阶03 模块