shiro自定义Realm
1.1?自定義Realm
上邊的程序使用的是shiro自帶的IniRealm,IniRealm從ini配置文件中讀取用戶的信息,大部分情況下需要從系統(tǒng)的數(shù)據(jù)庫中讀取用戶信息,所以需要自定義realm。分享牛系列,分享牛專欄,分享牛。
1.1.1?shiro提供的realm
?
?
最基礎(chǔ)的是Realm接口,CachingRealm負責(zé)緩存處理,AuthenticationRealm負責(zé)認證,AuthorizingRealm負責(zé)授權(quán),通常自定義的realm繼承AuthorizingRealm。
1.1.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從數(shù)據(jù)庫中查詢//....//如果查詢不到則返回nullif(!username.equals("zhang")){//這里模擬查詢不到return null;}//獲取從數(shù)據(jù)庫查詢出來的用戶密碼 String password = "123";//這里使用靜態(tài)數(shù)據(jù)模擬。。//返回認證信息由父類AuthenticatingRealm進行認證SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, getName());return simpleAuthenticationInfo;}} // 授權(quán)@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {// 獲取身份信息String username = (String) principals.getPrimaryPrincipal();// 根據(jù)身份信息從數(shù)據(jù)庫中查詢權(quán)限數(shù)據(jù)//....這里使用靜態(tài)數(shù)據(jù)模擬List<String> permissions = new ArrayList<String>();permissions.add("user:create");permissions.add("user.delete");//將權(quán)限信息封閉為AuthorizationInfoSimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();for(String permission:permissions){simpleAuthorizationInfo.addStringPermission(permission);}return simpleAuthorizationInfo;}1.1.3?shiro-realm.ini
[main]
#自定義 realm
customRealm=cn.shareniu.shiro.authentication.realm.CustomRealm1
#將realm設(shè)置到securityManager
securityManager.realms=$customRealm
?
思考:這里為什么不用配置[users]了??
shiro-permission.ini中的[roles]為什么不需要了??
1.1.4?測試代碼
測試代碼同入門程序,將ini的地址修改為shiro-realm.ini。
分別模擬賬號不存在、密碼錯誤、賬號和密碼正確進行測試。
?分享牛原創(chuàng)(尊重原創(chuàng) 轉(zhuǎn)載對的時候第一行請注明,轉(zhuǎn)載出處來自分享牛http://blog.csdn.net/qq_30739519) java架構(gòu)師交流群 523988350
總結(jié)
以上是生活随笔為你收集整理的shiro自定义Realm的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ThreadLocal_OSIV模式_F
- 下一篇: 使用js技术使字体闪烁