權限框架 - shiro 自定義realm


上篇文章中是使用的默認realm來實現的簡單登錄,這僅僅只是個demo,真正項目中使用肯定是需要連接數據庫的

首先創建自定義realm文件,如下:

在shiro中注入自定義realm的完全限定類名:

1 [main]
2 # your custom realm path
3 fooRealm=com.lee.shiro.realm.FooRealm
4 # DI such as spring DI
5 securityManager.realms=$fooRealm

自定義realm認證:

 1     /**
 2      *  設置realm的名稱
 3      */
 4     @Override
 5     public void setName(String name) {
 6         super.setName("fooRealm");
 7     }
 8 
 9     /**
10      * 認證
11      */
12     @Override
13     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
14 
15         // token是用戶輸入的相關信息
16         // 從token中取出身份信息, 即用戶的username
17         String username = (String)token.getPrincipal();
18 
19         // 根據用戶名username從數據庫查詢密碼password
20         // 如果查詢不到返回null
21         // String password = userService.queryPwdByUserName(username)
22         
23         // 假設數據庫查詢出來的密碼為如下
24         String password = "1234567";
25 
26         // 如果查詢到返回認證信息AuthenticationInfo
27         SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());
28 
29         return simpleAuthenticationInfo;
30     }

執行認證:

    /**
     * 
     * @Description: 自定義realm
     * 
     * @author leechenxiang
     * @date 2016年6月11日 下午9:07:27
     */
    @Test
    public void testFooRealm() {
        // 創建SecurityManager工廠,通過ini配置文件創建 SecurityManager工廠
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini");
        // 創建SecurityManager
        SecurityManager securityManager = factory.getInstance();
        // 設置SecurityManager到運行環境中,保持單例模式
        SecurityUtils.setSecurityManager(securityManager);
        // 從SecurityUtils里邊創建一個subject
        Subject subject = SecurityUtils.getSubject();
        // 在認證提交前准備token(令牌)
        // 這里的賬號和密碼 將來是由用戶輸入進去
        UsernamePasswordToken token = new UsernamePasswordToken("lee", "123456");
        try {
            // 執行認證提交
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        // 是否認證通過
        boolean isAuthenticated = subject.isAuthenticated();
        System.out.println("是否認證通過:" + isAuthenticated);
    }

done...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM