Shiro初識
Apache Shiro是一個強大易用的Java安全框架,
提供了認證、授權、加密和會話管理功能,可爲任何應用提供安全保障,
從命令行應用、移動應用到大型網絡及企業應用
認證:用戶身份識別,常被稱爲用戶"登錄"
授權:訪問控制
密碼加密:保護或隱藏數據防止被偷竊
會話管理:每用戶相關的時間敏感的狀態
Shiro:還支持一些輔助特性,
如
Web應用安全、
單元測試
多線程,它們的存在強化了上面提到的四個要素
maven Jar
http://mvnrepository.com/
項目體系圖
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.matrix.shiro</groupId>
<artifactId>ShiroTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ShiroTest</name>
<description>ShiroTest</description>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
</dependencies>
</project>
shiro.ini
[users]
matrix=123456
Jack=123456
Shiro HelloWorld
package com.matrix.shiro;
import org.apache.shiro.SecurityUtils;
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("matrix","123456");
try{
// 登錄
currentUser.login(token);
System.out.println("身份認證成功!");
}catch(Exception e){
e.printStackTrace();
System.out.println("身份認證失敗!");
}
// 退出
currentUser.logout();
}
}
運行結果