Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、受權、密碼和會話管理。使用Shiro的易於理解的API,您能夠快速、輕鬆地得到任何應用程序,從最小的移動應用程序到最大的網絡和企業應用程序。數據庫
步驟:apache
3.1.構建基本maven項目安全
3.2.添加必要的maven依賴網絡
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.wfd360.shiro-demo</groupId> 8 <artifactId>shiro-demo</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <dependencies> 11 <dependency> 12 <groupId>org.apache.shiro</groupId> 13 <artifactId>shiro-core</artifactId> 14 <version>1.3.2</version> 15 </dependency> 16 17 </dependencies> 18 19 </project>
3.3.添加帳號信息(模擬數據庫帳號)框架
3.4.helloWord程序maven
1 package com.wfd360.shiro; 2 3 import org.apache.shiro.SecurityUtils; 4 import org.apache.shiro.authc.AuthenticationException; 5 import org.apache.shiro.authc.UsernamePasswordToken; 6 import org.apache.shiro.config.IniSecurityManagerFactory; 7 import org.apache.shiro.mgt.SecurityManager; 8 import org.apache.shiro.subject.Subject; 9 import org.apache.shiro.util.Factory; 10 import org.slf4j.Logger; 11 import org.slf4j.LoggerFactory; 12 13 14 /** 15 * address: www.wfd360.com 16 */ 17 public class HelloShiro { 18 private static Logger logger = LoggerFactory.getLogger(HelloShiro.class); 19 20 public static void main(String[] args) { 21 //IniSecurityManagerFactory方法在1.4.0中被註解標誌爲不建議使用 22 // 讀取配置文件,初始化SecurityManager工廠 23 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); 24 //獲取securityManager 實例 25 SecurityManager securityManager = factory.getInstance(); 26 //把securityManager實例綁定到SecurityUtils 27 SecurityUtils.setSecurityManager(securityManager); 28 //獲得當前執行的用戶 29 Subject subject = SecurityUtils.getSubject(); 30 //認證明體,當前進來的用戶 31 // 建立token令牌,用戶名/密碼 32 UsernamePasswordToken token = new UsernamePasswordToken("jack", "12345"); 33 //身份認證 34 try { 35 subject.login(token); 36 logger.info("登陸成功!"); 37 } catch (AuthenticationException e) { //login的接口函數 38 //void login(AuthenticationToken var1) throws AuthenticationException;因此直接抓AuthenticationException異常便可 / 39 // 身份認證失敗即拋出此異常 40 logger.info("登陸失敗!"); 41 e.printStackTrace(); 42 } 43 //登出 44 subject.logout(); 45 } 46 }
3.5運行main方法測試。ide