Apache Shiro安全框架單獨實例

一、什麼是Shiro安全框架

    shrio是一個強大而靈活的開源安全框架,它主要處理身份驗證,授權,會話管理和加密。

  • 身份驗證:有時稱爲“登錄”,即驗證用戶的身份。

  • 授權:訪問控制的過程,即確定“誰”有權訪問“什麼”。

  • 會話管理:即使在非Web或EJB應用程序中,也可以管理用戶特定的會話。

  • 加密:使用加密算法保持數據安全,同時仍然易於使用。

    支持特性:

  • Web支持:Shiro的Web支持API有助於開發者輕鬆保護Web應用程序。
  • 緩存:緩存是Apache Shiro API的第一層,可確保安全操作保持快速有效。
  • 併發性:Apache Shiro的併發功能支持多線程應用程序。
  • 測試:測試支持可幫助您編寫單元測試和集成測試,並確保您的代碼將按預期進行保護。
  • “運行方式”(Run As):允許用戶採用其他用戶的身份(如果允許),有時在管理方案中很有用。
  • “記住我”:在整個會話中記住用戶的身份,因此他們僅在必要時登錄。

二、編寫shiro基本代碼

1.引入相關環境

         引入shiro-core和slf4j-api相關jar包,shiro使用slf4j記錄日誌。

        <dependency>
		    <groupId>org.slf4j</groupId>
		    <artifactId>slf4j-api</artifactId>
		    <version>1.7.25</version>
		</dependency>
        <dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-core</artifactId>
			<version>1.2.2</version>
		</dependency>

2.創建ini文件

src/main/resources/shiro.ini

# ini文件配置
# -----------------------------------------------------------------------------
# 用戶信息格式
# username[用戶名] = password[密碼], role1[角色1], role2[角色2], ..., role[角色n]
# -----------------------------------------------------------------------------
[users]
root = 123456, admin
guest = 123456, rolea
user1 = 12345, roleb

# -----------------------------------------------------------------------------
# 定義角色相關權限
# roleName[角色名] = perm1[權限範圍], perm2, ..., permN
# *類似與通配符,代表當前範圍內的任何操作
# -----------------------------------------------------------------------------
[roles]
admin = *
rolea = book:bug
roleb = book:add,book:delete

3.參考程序

package demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * [用戶、角色、權限都是字符串]
 * 
 * 
 * */
public class Test {
    //創建當前類的日誌對象
	private static final transient Logger log=LoggerFactory.getLogger(Test.class);

	public static void main(String[] args) {
        //創建一個factory,指向ini文件,classpath代表src/main/resourse目錄
		Factory<SecurityManager> fac=new  IniSecurityManagerFactory("classpath:shiro.ini");
		SecurityManager manager=fac.getInstance();
		SecurityUtils.setSecurityManager(manager);
		
		log.info("環境初始化完成");
		
		Subject currentUser=SecurityUtils.getSubject();
		//System.out.println(currentUser);
		
		Session session=currentUser.getSession();
		session.setAttribute("message", "this is shiro");
		System.out.println(session.getAttribute("message"));
		//當前用戶是否已經驗證
		System.out.println(currentUser.isAuthenticated());
		
		if(currentUser.isAuthenticated()) {
			System.out.println("已登錄");
		}
		else {
			UsernamePasswordToken token =new UsernamePasswordToken("user1", "12345");
			//token.setRememberMe(true);
			try {
				currentUser.login(token);
				System.out.println("登錄成功");
			} catch (UnknownAccountException e) {
				System.out.println("用戶不存在");
			}catch (IncorrectCredentialsException e) {
				System.out.println("密碼錯誤");
			}
			
		}
		if(currentUser.hasRole("admin")) {
			System.out.println("歡迎管理員");
		}
		if(currentUser.isPermitted("book:bug")) {
			System.out.println("允許購買書籍");
		}
		if(currentUser.isPermitted("book:add")) {
			System.out.println("允許增加書籍");
		}
		if(currentUser.isPermitted("book:delete")) {
			System.out.println("允許刪除書籍");
		}
		currentUser.logout();
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章