1. 程式人生 > 其它 >Shiro安全框架簡介

Shiro安全框架簡介

1.Shiro安全框架簡介

1.1 Shiro 概述

Shiro是apache旗下一個開源安全框架(http://shiro.apache.org/),它將軟體系統的安全認證相關的功能抽取出來,實現使用者身份認證,許可權授權,加密,會話管理等功能,組成了一個通用的安全認證框架,使用shiro就可以非常快速的完成認證,授權等功能的開發,降低系統成本.
使用者在進行資源訪問時,要求系統要對使用者進行許可權控制,其具體流程圖如下:

1.2 Shiro 概要架構

在概念層面,Shiro架構包含三個主要的理念,如圖:

其中:

  1. Subject : 主體物件,負責提交使用者認證和授權資訊.
  2. SecurityManager : 安全管理器,負責認證,授權等業務的實現.
  3. Realm : 領域物件, 負責從資料層獲取業務資料.

1.3 Shiro詳細架構

Shiro框架進行許可權觀看時,要涉及到的一些核心物件,主要包括:認證管理物件,授權管理物件,會話管理物件,快取管理物件,加密管理物件以及Realm管理物件(領域物件:負責處理認證和授權領域的資料訪問)等,其局架構如圖:

其中:

  • Subject(主體) : 與軟體互動的一個特定的實體(使用者,第三方服務等);
  • SecurityManager(安全管理器) : Shiro 的核心,用來協調管理元件工作.
  • Authentication(認證管理器) : 負責執行認證操作.
  • Authorizer (授權管理器) : 負責授權檢測.
  • SessionManager(會話管理) : 負責建立並管理使用者 Session 生命週期,提供一個強有力的 Session 體驗.
  • SessionDAO : 代表 SessionManager 執行 Session 持久(CRUD) 動作,它允許任何儲存的資料掛接到 session 管理基礎上.
  • CacheManager(快取管理器) : 提供建立快取例項和管理快取生命週期的功能.
  • Cryptography (加密管理器) : 提供了加密方式的設計及管理.
  • Realms (領域物件) ; 是shiro和你的應用程式安全資料之間的橋樑.

2. Shiro框架認證攔截實現(filter)

2.1 Shiro基本環境配置

2.1.1 新增shiro依賴

實用spring整合shiro時,需要在pom.xml中新增如下依賴:

<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-spring</artifactId>
   <version>1.5.3</version>
</dependency>

2.1.2 Shiro核心物件配置

基於SpringBoot 實現的專案中,沒有提供shiro的自動化配置,需要我們自己配置。
第一步: 建立SpringShiroConfig配置類,程式碼如下:

package com.cy.pj.common.config;
/**@Configuration 註解描述的類為一個配置物件,
 * 此物件也會交給spring管理
 */
@Configuration
public class SpringShiroConfig {
 
}

第二步:在Shiro配置類中新增SecurityManager配置(這裡一定要使用org.apache.shiro.mgt.SecurityManager這個介面物件),程式碼如下:

@Bean
public SecurityManager securityManager() {
		 DefaultWebSecurityManager sManager=new DefaultWebSecurityManager();
		 return sManager;
}

第三步: 在Shiro配置類中新增ShiroFilterFactoryBean物件的配置,通過此物件設定資源匿名訪問,認證訪問等,程式碼如下:

@Bean
public ShiroFilterFactoryBean shiroFilterFactory (SecurityManager securityManager) {
		 ShiroFilterFactoryBean sfBean=new ShiroFilterFactoryBean();
		 sfBean.setSecurityManager(securityManager);
		 //定義map指定請求過濾規則(哪些資源允許匿名訪問,哪些必須認證訪問)
		 LinkedHashMap<String,String> map= new LinkedHashMap<>();
		 //靜態資源允許匿名訪問:"anon"
		 map.put("/bower_components/**","anon");
		 map.put("/build/**","anon");
		 map.put("/dist/**","anon");
		 map.put("/plugins/**","anon");
		 //除了匿名訪問的資源,其他都要認證("authc")後訪問
		 map.put("/**","authc");
		 sfBean.setFilterChainDefinitonMap(map);
		 return sfBean;

其配置過程中,物件關係如下圖

2.2 Shiro登陸頁面呈現

2.2.1 服務端Controller實現

  • 業務描述及設計實現
    當服務端攔截到使用者請求以後,判定此請求是否已經被認證,假如沒有認證應該先跳轉到登入頁面。
  • 關鍵程式碼分析及實現.
    第一步:在PageController中新增一個呈現登入頁面的方法,關鍵程式碼如下
@RequestMapping("doLoginUI")
public String doLoginUI(){
		return "login";
}

第二步:修改SpringShiroConfig類中shiroFilterFactorybean的配置,新增登陸url的設定。關鍵程式碼見sfBean.setLoginUrl("/doLoginUI")部分。

@Bean
	public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
		//1.建立ShiroFilterFactoryBean物件
		//1.1 構建物件
		ShiroFilterFactoryBean fBean=new ShiroFilterFactoryBean();
		//1.2設定安全認證授權物件
		fBean.setSecurityManager(securityManager);
		//1.3設定登陸頁面
		fBean.setLoginUrl("/doLogin");
		//2.設定過濾規則
		LinkedHashMap<String,String> map= new LinkedHashMap<>();
		//靜態資源允許匿名訪問(例如專案static目錄下的資源):"anon"表示匿名
		map.put("/bower_components/**","anon");
		map.put("/modules/**","anon");
		map.put("/dist/**","anon");
		map.put("/plugins/**","anon");
		map.put("/user/doLogin","anon");
		map.put("/doIndexUI","anon");
		map.put("/doLogout","logout");
		//除了匿名訪問的資源,其它都要認證("authc")後訪問
		//map.put("/**","authc");
		map.put("/**","user");//當記住我時,不需要認證
		fBean.setFilterChainDefinitionMap(map);
		return fBean;
	}

2.2.2 客戶端頁面實現

  • 業務描述及設計實現。
    在/templates/pages/新增一個login.html頁面,然後將專案部署到web伺服器,並啟動測試執行.
  • 關鍵程式碼分析及實現。
$(function () {
    $('input').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%' // optional
    });
    $(".btn").click(doLogin);
  });
  function doLogin(){
	  var params={
		 username:$("#usernameId").val(),
		 password:$("#passwordId").val(),
		 isRememberMe:$("#rememberId").prop("checked"),
	  }
	  var url="user/doLogin";
	  console.log("params",params);
	  $.post(url,params,function(result){
		  console.log("login.result",result);
		  if(result.state==1){
			//跳轉到indexUI對應的頁面
			location.href="doIndexUI?t="+Math.random();
		  }else{
			$(".login-box-msg").html(result.message); 
		  }
		  return false;//防止重新整理時重複提交
	  });
  }

3. Shiro框架認證業務實現

3.1 認證流程分析

身份認證即判定使用者是否是系統的合法使用者,使用者訪問系統資源時的認證(對使用者身份資訊的認證)

其中認證流程分析如下:

  1. 系統呼叫subject的login方法將使用者資訊提交給SecurityManager
  2. SecurityManager將認證操作委託給認證器物件Authenticator
  3. Authenticator將使用者輸入的身份資訊傳遞給Realm.
  4. Realm訪問資料獲取使用者資訊然後對資訊進行封裝並返回.
  5. Authenticator 對 realm返回的資訊進行身份認證.

3.2 認證服務端實現

3.2.1 核心業務分析

認證業務API處理流程分析,如圖

3.2.2 Service 介面及實現

  • 業務描述及設計實現。
    本模組的業務在Realm型別的物件中進行實現,我們編寫Realm時,要繼承AuthorizingRealm 並重寫相關方法,完成認證及授權業務的獲取及封裝.

  • 關鍵程式碼分析及實現。
    第一步:定義ShiroUserRealm類,關鍵程式碼如下:

/**
 * 基於此物件獲取使用者認證和授權資訊並進行封裝
 * @author 54643
 */
@Component
public class ShiroUserRealm extends AuthorizingRealm {
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleMenuDao sysRoleMenuDao;
	@Autowired
	private SysMenuDao sysMenuDao;
	

	/**
	 * 負責授權資訊的獲取和封裝
	 * 為了提高授權效能,還可以將使用者授權資訊進行快取,具體快取物件
	 * 底層使用的是SoftHashMap(軟引用),這個容器的key為當前的使用者身份(存什麼什麼當key,(user,//principal身份,) )
	 * doGetAuthorizationInfo的返回值作為value儲存到softHashMap中
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//1.獲取登入使用者資訊,例如使用者id
		SysUser user = (SysUser)principals.getPrimaryPrincipal();
		Integer userId = user.getId();
		//2.基於使用者id獲取使用者擁有的角色(sys_user_roles)
		List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(userId);
		if (roleIds==null||roleIds.size()==0) {
			throw new AuthorizationException();
		}
		//3.基於角色id獲取選單id(sys_role_menus)
		List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
		if(menuIds==null||menuIds.size()==0)
			throw new AuthorizationException();
		//4.基於選單id獲取選單授權標識(permission)
		List<String> permissions = sysMenuDao.findPermissions(menuIds);
		if (permissions==null||permissions.size()==0) {
			throw new AuthorizationException();
		}
		//5.對許可權標識資訊進行封裝
		Set<String> stringPermissions = new HashSet<>();
		for (String per : permissions) {
			if (!StringUtil.isEmpty(per)) {
				stringPermissions.add(per);
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(stringPermissions);
		return info;
	}

	/**
	 * 通過此方法完成認證資料的獲取及封裝,系統底層會將認證資料傳遞認證管理器,由
	 * 認證管理器完成認證操作
	 * 負責認證資訊的獲取和封裝
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 1.獲取使用者輸入的使用者名稱
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		String username = upToken.getUsername();
		//2.基於用於名獲取使用者物件
		SysUser user = sysUserDao.findUserByUserName(username);
		//3.判定使用者物件是否存在
		if (user==null)throw new UnknownAccountException();
		//4.判定使用者是否有效(是否被鎖定)
		if (user.getValid()==0)throw new LockedAccountException();
		//5.封裝使用者認證資訊
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
				(user,//principal身份, 
				user.getPassword(), //hashedCredentials 已加密使用者憑證
				credentialsSalt,//credentialsSalt 憑證鹽
				getName());//realmName realm的類名
		return info;//此物件會返回給SecurityManager物件
	}
	
	/**
	 * 負責獲取加密憑證匹配器物件
	 */
	@Override
	public CredentialsMatcher getCredentialsMatcher() {
		HashedCredentialsMatcher hMatcher = new HashedCredentialsMatcher();
		hMatcher.setHashAlgorithmName("MD5");
		hMatcher.setHashIterations(1);
		return hMatcher;
	}

}

第二步:對此realm,需要在SpringShiroConfig配置類中,注入給SecurityManager物件,修改securityManager方法

@Bean
public SecurityManager securityManager(Realm realm) {
		 DefaultWebSecurityManager sManager= new DefaultWebSecurityManager();
		 sManager.setRealm(realm);
		 return sManager;
}

3.2.3 Controller 類實現

  • 業務描述及設計實現。
    在此物件中定義相關方法,處理客戶端的登陸請求,例如獲取使用者名稱,密碼等然後提交該shiro框架進行認證。
  • 關鍵程式碼分析及實現。
    第一步:在SysUserController中新增處理登陸的方法。關鍵程式碼如下:
 @RequestMapping("doLogin")
     public JsonResult doLogin(String username,String password,boolean isRememberMe) {
    	 //1.獲取Subject物件
    	 Subject subject = SecurityUtils.getSubject();
    	 //2.通過Subject提交使用者資訊,交給shiro框架進行認證操作
    	 //2.1對使用者進行封裝
    	 UsernamePasswordToken token = new UsernamePasswordToken(
    			 username,//身份資訊
    			 password);//憑證資訊
    	 //2.2對使用者資訊進行身份認證
    	 subject.login(token);
    	 if (isRememberMe)token.setRememberMe(isRememberMe);
    	 //分析:
    	 //1)token會傳給shiro的SecurityManager
    	 //2)Securitymanager將token傳遞給認證管理器
    	 //3)認證管理器會將token傳遞給realm
    	 return new JsonResult("login OK");
     }

第二步:修改shiroFilterFactory的配置,對/user/doLogin這個路徑進行匿名訪問的配置.
第三步:當我們在執行登入操作時,為了提高使用者體驗,可對系統中的異常資訊進行處理,例如,在統一異常處理類中新增如下方法:

@ExceptionHandler(ShiroException.class) 
   @ResponseBody
	public JsonResult doHandleShiroException(
			ShiroException e) {
		JsonResult r=new JsonResult();
		r.setState(0);
		if(e instanceof UnknownAccountException) {
			r.setMessage("賬戶不存在");
		}else if(e instanceof LockedAccountException) {
			r.setMessage("賬戶已被禁用");
		}else if(e instanceof IncorrectCredentialsException) {
			r.setMessage("密碼不正確");
		}else if(e instanceof AuthorizationException) {
			r.setMessage("沒有此操作許可權");
		}else {
			r.setMessage("系統維護中");
		}
		e.printStackTrace();
		return r;
	}

3.3 認證客戶端實現

3.3.1 編寫使用者登陸頁面

在/templates/pages/目錄下新增登陸頁面(login.html)。

3.3.2 非同步登陸操作實現

點選登入操作時,將輸入的使用者名稱,密碼非同步提交到服務端。

$(function () {
    $(".login-box-body").on("click",".btn",doLogin);
  });
  function doLogin(){
	  var params={
		 username:$("#usernameId").val(),
		 password:$("#passwordId").val()
	  }
	  var url="user/doLogin";
	  $.post(url,params,function(result){
		  if(result.state==1){
			//跳轉到indexUI對應的頁面
			location.href="doIndexUI?t="+Math.random();
		  }else{
			$(".login-box-msg").html(result.message); 
		  }
	  });
  }