Apache Shiro是Java的一個安全框架,Shiro可以幫助我們完成:認證、授權、加密、會話管理、與Web集成、緩存等.
簡單的身份驗證
項目目錄:
首先,在shiro.ini里配置了用戶名和密碼
用戶名為 hello 密碼為 123
項目使用了maven
在pom.xml中添加所需要的依賴
SayHello.java
package com.shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.apache.shiro.mgt.SecurityManager; public class SayHello { /** * @return */ public static void main(String[] args) { // 讀取配置文件,初始化SecurityManager工廠 讀取shiro.ini文件 Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini"); // 獲取securityManager實例 SecurityManager securityManager=factory.getInstance(); // 把securityManager實例綁定到SecurityUtils SecurityUtils.setSecurityManager(securityManager); // 得到當前執行的用戶 Subject currentUser=SecurityUtils.getSubject(); // 創建token令牌,用戶名/密碼 UsernamePasswordToken token=new UsernamePasswordToken("hello", "1234"); try{ //身份認證 currentUser.login(token); System.out.println("身份認證成功!sayHello"); }catch(AuthenticationException e){ e.printStackTrace(); System.out.println("身份認證失敗!"); } // 退出 currentUser.logout(); } }
測試:
1), 當用戶名,密碼與shiro.ini中的配置一致時
控制台顯示身份驗證通過
2), 當用戶名,密碼與shiro.ini中的配置不一致的時候
控制台顯示身份驗證失敗,拋出異常
拋出的異常
org.apache.shiro.authc.IncorrectCredentialsException: Submitted credentials for token [org.apache.shiro.authc.UsernamePasswordToken - hello, rememberMe=false] did not match the expected credentials.
did not match the expected credentials. 與預期的憑證不匹配 其實就是用戶名與密碼不對
以上就是一簡單的身份驗證過程,在上面shiro.ini里配置了用戶名與密碼,在實際開發中用戶信息應該是在數據庫中檢索出來的數據,詳見下一站
本篇只是為了記錄自己的學習
學習需沉淀,厚積而薄發
感謝: http://www.java1234.com/