shiro之自定义realm
生活随笔
收集整理的這篇文章主要介紹了
shiro之自定义realm
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:
首先我們先分析怎么實現自定義某些realm,按照以往的方法肯定是實現接口或者繼承某類
查看繼承樹結構
通過debug模式下分析源碼可以得知
AuthenticatingRealm類中的 doGetAuthenticationInfo()方法是實現用戶認證的
AuthorizingRealml類中的doGetAuthorizationInfo()方法是完成用戶授權的
然后在這兩個類中只是聲明了該方法,沒有去實現,接著我們看繼承樹中最根部的SimpleAccountRealm類
我們可以發現,在該類中完成了用戶認證和授權的代碼核心實現
通過以上分析我們可以得出,如果想要自定義realm,就必須繼承AuthorizingRealm類,為什么呢?因為如果繼承AuthenticatingRealm,只能完成用戶認證,無法授權;而繼承了AuthorizingRealm就很方便了,里面既實現了AuthenticatingRealm類中的doGetAuthenticationInfo()方法完成用戶認證,又加入了新的方法doGetAuthorizationInfo()用于完成授權操作
代碼實現(僅僅只進行認證操作)
public class CustomerRealm extends AuthorizingRealm {//授權@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {return null;}//認證@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {String principal = (String) authenticationToken.getPrincipal();if("tom".equals(principal)){//參數1,返回數據庫中的正確的賬戶 //參數2 :密碼 //參數3.提供當前realm的名字SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("tom","123",this.getName());return simpleAuthenticationInfo;}System.out.println(principal);return null;} }測試
public class TestCustomerRealm {public static void main(String[] args) {//創建security managerDefaultSecurityManager securityManager = new DefaultSecurityManager();//設置realmsecurityManager.setRealm(new CustomerRealm());//將安全工具類設置安全管理器SecurityUtils.setSecurityManager(securityManager);//通過安全工具類獲取SubjectSubject subject = SecurityUtils.getSubject();//創建令牌UsernamePasswordToken tom = new UsernamePasswordToken("tom", "123");try {subject.login(tom);}catch (UnknownAccountException e){e.printStackTrace();System.out.println();}catch (IncorrectCredentialsException e){e.printStackTrace();}} }shiro.ini文件
[users] tom=123 jone=456 jane=789測試成功
😘😘😘
總結
以上是生活随笔為你收集整理的shiro之自定义realm的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shiro之第一个程序认证
- 下一篇: shiro认证+授权(使用MD5+sal