初識shiro
Shiro是一個Java安全框架,提供了認證、授權、加密和會話管理功能,可以為任何應用提供安全保障。
使用shiro
shiro記住我, 1.添加shiro相關jar包(使用maven添加依賴)
<!-- shiro begin --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.4</version></dependency><!-- shiro end --><!-- slf4j begin --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.21</version></dependency><!-- slf4j end -->
2.在項目resources下新建一個shiro.ini文件方便測試
[users] zhen=123 jack=jack
3.新建測試文件
package com.zhen.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.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory;public class HelloWorld {public static void main(String[] args) {//讀取配置文件,初始化SecurityManager工廠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("zhen", "123");try {//身份認證 currentUser.login(token);System.out.println("身份認證成功!");} catch (AuthenticationException e) {e.printStackTrace();System.out.println("身份認證失敗!");}//退出 currentUser.logout();}}
?
shiro使用詳解,