1. 程式人生 > >003 Shiro的認證

003 Shiro的認證

ica 麻煩 們的 color subject one 賬號 交互 ogg

一 . 概述

  認證:簡單說就是登錄,用戶攜帶賬號和密碼信息通過Subject對象與shiro進行交互,看用戶的身份憑證是否正確.

  本節需要演示認證的流程.


二 .搭建環境

  本次使用ini充當Realm對象,使用IniSecurityManager充當SecurityManager對象,這個在後面我們都會重寫進行定制的,這裏只是簡單介紹流程.

  我們的ini文件的內容:

[users]
trek=123

這個ini文件之中,定義了一個賬號為trek,密碼為123的用戶.


三 .流程代碼

    //實現shiro的認證過程
//1---------------創建SecurityManager-----------------
//創建SecurityManager SecurityManager securityManager = new IniSecurityManagerFactory("classpath:shiro.ini").createInstance(); //將當前的SecurityManager設置到當前的環境之中 SecurityUtils.setSecurityManager(securityManager); //2-----創建Subject對象 //下面實現的是一個登陸的功能 //獲取Subkect,相當與一個Currentuser
Subject currentUser = SecurityUtils.getSubject(); //3----封裝token對象 //創建認證需要的token UsernamePasswordToken token = new UsernamePasswordToken("trek","123"); //4-調用login()方法 //實現登錄功能 try { currentUser.login(token); } catch (AuthenticationException e) { logger.info(
"認證失敗,賬號為{},密碼為{}",token.getUsername(),new String(token.getPassword())); throw new AuthenticationException(); } logger.info("認證成功!!");

上面的代碼描述的流程

[1]創建SecurityManager對象

[2]獲取Subject獨享

[3]用戶賬號和密碼信息封裝為token對象,這裏使用最為常用的UsernameAndPassword對象.

[4]調用Subject的login()方法

[5]4中調用login()會有兩種情況發生,正常執行,說明認證成功(賬號和密碼都是對的),拋出異常,說明認證失敗.


四 .認證失敗的異常AuthenticationException

技術分享圖片

從上圖之中我們可以看到.shiro定義了很多的認證異常,

如,賬號不存在(UnknownAccountException),密碼不正確(IncorrectCredentialsException).

我們可以使用這些異常表示在認證過程之中出現的問題,這樣免去了我們自定義異常的麻煩.


五 . 總結

  認證的過程十分簡單,創建完環境對象之後,調用Subject的login()方法就可以了.

  認證成功,login()方法就會正常執行,否則就會出現異常,我們通過捕獲異常就可以知道到底出現了什麽認證問題.

003 Shiro的認證