Shiro【授權、整合Spirng、Shiro過濾器】

Java3y發表於2018-03-21

前言

本文主要講解的知識點有以下:

  • Shiro授權的方式簡單介紹
  • 與Spring整合
  • 初始Shiro過濾器

一、Shiro授權

上一篇我們已經講解了Shiro的認證相關的知識了,現在我們來弄Shiro的授權

Shiro授權的流程和認證的流程其實是差不多的:

這裡寫圖片描述

1.1Shiro支援的授權方式

Shiro支援的授權方式有三種:


Shiro 支援三種方式的授權:
程式設計式:通過寫if/else 授權程式碼塊完成:
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole(“admin”)) {
//有許可權
} else {
//無許可權
}
註解式:通過在執行的Java方法上放置相應的註解完成:
@RequiresRoles("admin")
public void hello() {
//有許可權
}
JSP/GSP 標籤:在JSP/GSP 頁面通過相應的標籤完成:
<shiro:hasRole name="admin">
<!— 有許可權—>
</shiro:hasRole>
複製程式碼

1.2使用程式設計式授權

同樣的,我們是通過安全管理器來去授權的,因此我們還是需要配置對應的配置檔案的:

shiro-permission.ini配置檔案:


#使用者
[users]
#使用者zhang的密碼是123,此使用者具有role1和role2兩個角色
zhang=123,role1,role2
wang=123,role2

#許可權
[roles]
#角色role1對資源user擁有create、update許可權
role1=user:create,user:update
#角色role2對資源user擁有create、delete許可權
role2=user:create,user:delete
#角色role3對資源user擁有create許可權
role3=user:create



#許可權識別符號號規則:資源:操作:例項(中間使用半形:分隔)
user:create:01  表示對使用者資源的01例項進行create操作。
user:create:表示對使用者資源進行create操作,相當於user:create:*,對所有使用者資源例項進行create操作。
user:*:01  表示對使用者資源例項01進行所有操作。


複製程式碼

程式碼測試:



	// 角色授權、資源授權測試
	@Test
	public void testAuthorization() {

		// 建立SecurityManager工廠
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(
				"classpath:shiro-permission.ini");

		// 建立SecurityManager
		SecurityManager securityManager = factory.getInstance();

		// 將SecurityManager設定到系統執行環境,和spring後將SecurityManager配置spring容器中,一般單例管理
		SecurityUtils.setSecurityManager(securityManager);

		// 建立subject
		Subject subject = SecurityUtils.getSubject();

		// 建立token令牌
		UsernamePasswordToken token = new UsernamePasswordToken("zhangsan",
				"123");

		// 執行認證
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("認證狀態:" + subject.isAuthenticated());
		// 認證通過後執行授權

		// 基於角色的授權
		// hasRole傳入角色標識
		boolean ishasRole = subject.hasRole("role1");
		System.out.println("單個角色判斷" + ishasRole);
		// hasAllRoles是否擁有多個角色
		boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1",
				"role2", "role3"));
		System.out.println("多個角色判斷" + hasAllRoles);

		// 使用check方法進行授權,如果授權不通過會丟擲異常
		// subject.checkRole("role13");

		// 基於資源的授權
		// isPermitted傳入許可權識別符號
		boolean isPermitted = subject.isPermitted("user:create:1");
		System.out.println("單個許可權判斷" + isPermitted);

		boolean isPermittedAll = subject.isPermittedAll("user:create:1",
				"user:delete");
		System.out.println("多個許可權判斷" + isPermittedAll);
		// 使用check方法進行授權,如果授權不通過會丟擲異常
		subject.checkPermission("items:create:1");

	}

複製程式碼

1.3自定義realm進行授權

一般地,我們的許可權都是從資料庫中查詢的,並不是根據我們的配置檔案來進行配對的。因此我們需要自定義reaml,讓reaml去對比的是資料庫查詢出來的許可權

shiro-realm.ini配置檔案:將自定義的reaml資訊注入到安全管理器中


[main]
#自定義 realm
customRealm=cn.itcast.shiro.realm.CustomRealm
#將realm設定到securityManager,相當 於spring中注入
securityManager.realms=$customRealm




複製程式碼

我們上次已經使用過了一個自定義reaml,當時候僅僅重寫了doGetAuthenticationInfo()方法,這次我們重寫doGetAuthorizationInfo()方法

	// 用於授權
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		//從 principals獲取主身份資訊
		//將getPrimaryPrincipal方法返回值轉為真實身份型別(在上邊的doGetAuthenticationInfo認證通過填充到SimpleAuthenticationInfo中身份型別),
		String userCode =  (String) principals.getPrimaryPrincipal();
		
		//根據身份資訊獲取許可權資訊
		//連線資料庫...
		//模擬從資料庫獲取到資料
		List<String> permissions = new ArrayList<String>();
		permissions.add("user:create");//使用者的建立
		permissions.add("items:add");//商品新增許可權
		//....
		
		//查到許可權資料,返回授權資訊(要包括 上邊的permissions)
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//將上邊查詢到授權資訊填充到simpleAuthorizationInfo物件中
		simpleAuthorizationInfo.addStringPermissions(permissions);

		return simpleAuthorizationInfo;
	}

複製程式碼

測試程式:


	// 自定義realm進行資源授權測試
	@Test
	public void testAuthorizationCustomRealm() {

		// 建立SecurityManager工廠
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(
				"classpath:shiro-realm.ini");
		// 建立SecurityManager
		SecurityManager securityManager = factory.getInstance();
		// 將SecurityManager設定到系統執行環境,和spring後將SecurityManager配置spring容器中,一般單例管理
		SecurityUtils.setSecurityManager(securityManager);
		// 建立subject
		Subject subject = SecurityUtils.getSubject();

		// 建立token令牌
		UsernamePasswordToken token = new UsernamePasswordToken("zhangsan",
				"111111");
		// 執行認證
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("認證狀態:" + subject.isAuthenticated());
		// 認證通過後執行授權

		// 基於資源的授權,呼叫isPermitted方法會呼叫CustomRealm從資料庫查詢正確許可權資料
		// isPermitted傳入許可權識別符號,判斷user:create:1是否在CustomRealm查詢到許可權資料之內
		boolean isPermitted = subject.isPermitted("user:create:1");
		System.out.println("單個許可權判斷" + isPermitted);

		boolean isPermittedAll = subject.isPermittedAll("user:create:1",
				"user:create");
		System.out.println("多個許可權判斷" + isPermittedAll);

		// 使用check方法進行授權,如果授權不通過會丟擲異常
		subject.checkPermission("items:add:1");

	}
複製程式碼

這裡寫圖片描述


二、Spring與Shiro整合

2.1匯入jar包

  • shiro-web的jar、
  • shiro-spring的jar
  • shiro-code的jar

這裡寫圖片描述

2.2快速入門

shiro也通過filter進行攔截。filter攔截後將操作權交給spring中配置的filterChain(過慮鏈兒)

在web.xml中配置filter


<!-- shiro的filter -->
	<!-- shiro過慮器,DelegatingFilterProxy通過代理模式將spring容器中的bean和filter關聯起來 -->
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<!-- 設定true由servlet容器控制filter的生命週期 -->
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
		<!-- 設定spring容器filter的bean id,如果不設定則找與filter-name一致的bean-->
		<init-param>
			<param-name>targetBeanName</param-name>
			<param-value>shiroFilter</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
複製程式碼

applicationContext-shiro.xml 中配置web.xml中fitler對應spring容器中的bean


<!-- web.xml中shiro的filter對應的bean -->
<!-- Shiro 的Web過濾器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 -->
		<property name="loginUrl" value="/login.action" />
		<!-- 認證成功統一跳轉到first.action,建議不配置,shiro認證成功自動到上一個請求路徑 -->
		<!-- <property name="successUrl" value="/first.action"/> -->
		<!-- 通過unauthorizedUrl指定沒有許可權操作時跳轉頁面-->
		<property name="unauthorizedUrl" value="/refuse.jsp" />
		<!-- 自定義filter配置 -->
		<property name="filters">
			<map>
				<!-- 將自定義 的FormAuthenticationFilter注入shiroFilter中-->
				<entry key="authc" value-ref="formAuthenticationFilter" />
			</map>
		</property>
		
		<!-- 過慮器鏈定義,從上向下順序執行,一般將/**放在最下邊 -->
		<property name="filterChainDefinitions">
			<value>
				<!--所有url都可以匿名訪問-->
				/** = anon
			</value>
		</property>
	</bean>
複製程式碼

配置安全管理器


<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="customRealm" />	
</bean>
複製程式碼

配置reaml


<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
</bean>
複製程式碼

步驟:

  • 在web.xml檔案中配置shiro的過濾器
  • 在對應的Spring配置檔案中配置與之對應的filterChain(過慮鏈兒)
  • 配置安全管理器,注入自定義的reaml
  • 配置自定義的reaml

2.3靜態資源不攔截

我們在spring配置過濾器鏈的時候,我們發現這麼一行程式碼:

	<!--所有url都可以匿名訪問 -->
 	/** = anon
複製程式碼

anon其實就是shiro內建的一個過濾器,上邊的程式碼就代表著所有的匿名使用者都可以訪問

當然了,後邊我們還需要配置其他的資訊,為了讓頁面能夠正常顯示,我們的靜態資源一般是不需要被攔截的

於是我們可以這樣配置:


	<!-- 對靜態資源設定匿名訪問 -->
	/images/** = anon
	/js/** = anon
	/styles/** = anon
複製程式碼

三、初識shiro過濾器

上面我們瞭解到了anno過濾器的,shiro還有其他的過濾器的..我們來看看

這裡寫圖片描述

常用的過濾器有下面幾種:

anon:例子/admins/**=anon 沒有引數,表示可以匿名使用。 authc:例如/admins/user/**=authc表示需要認證(登入)才能使用,FormAuthenticationFilter是表單認證,沒有引數 perms:例子/admins/user/**=perms[user:add:*],引數可以寫多個,多個時必須加上引號,並且引數之間用逗號分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當有多個引數時必須每個引數都通過才通過,想當於isPermitedAll()方法。 user:例如/admins/user/**=user沒有引數,表示必須存在使用者, 身份認證通過或通過記住我認證通過的可以訪問,當登入操作時不做檢查

3.1登陸與退出

使用FormAuthenticationFilter過慮器實現 ,原理如下:

  • 當使用者沒有認證時,請求loginurl進行認證【上邊我們已經配置了】,使用者身份和使用者密碼提交資料到loginurl
  • FormAuthenticationFilter攔截住取出request中的username和password(兩個引數名稱是可以配置的
  • FormAuthenticationFilter 呼叫realm傳入一個token(username和password)
  • realm認證時根據username查詢使用者資訊(在Activeuser中儲存,包括 userid、usercode、username、menus)。
  • 如果查詢不到,realm返回null,FormAuthenticationFilter向request域中填充一個引數(記錄了異常資訊)
  • 查詢出使用者的資訊之後,FormAuthenticationFilter會自動將reaml返回的資訊和token中的使用者名稱和密碼對比。如果不對,那就返回異常。

3.1.1登陸頁面

由於FormAuthenticationFilter的使用者身份和密碼的input的預設值(username和password)修改頁面的賬號和密碼的input的名稱為username和password


	<TR>
		<TD>使用者名稱:</TD>
		<TD colSpan="2"><input type="text" id="usercode"
			name="username" style="WIDTH: 130px" /></TD>
	</TR>
	<TR>
		<TD>密 碼:</TD>
		<TD><input type="password" id="pwd" name="password" style="WIDTH: 130px" />
		</TD>
	</TR>
複製程式碼

3.1.2登陸程式碼實現

上面我們已經說了,當使用者沒有認證的時候,請求的loginurl進行認證,使用者身份的使用者密碼提交資料到loginrul中

當我們提交到loginurl的時候,表單過濾器會自動解析username和password去呼叫realm來進行認證。最終在request域物件中儲存shiroLoginFailure認證資訊,如果返回的是異常的資訊,那麼我們在login中丟擲異常即可



//登陸提交地址,和applicationContext-shiro.xml中配置的loginurl一致
	@RequestMapping("login")
	public String login(HttpServletRequest request)throws Exception{
		
		//如果登陸失敗從request中獲取認證異常資訊,shiroLoginFailure就是shiro異常類的全限定名
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		//根據shiro返回的異常類路徑判斷,丟擲指定異常資訊
		if(exceptionClassName!=null){
			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
				//最終會拋給異常處理器
				throw new CustomException("賬號不存在");
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				throw new CustomException("使用者名稱/密碼錯誤");
			} else if("randomCodeError".equals(exceptionClassName)){
				throw new CustomException("驗證碼錯誤 ");
			}else {
				throw new Exception();//最終在異常處理器生成未知錯誤
			}
		}
		//此方法不處理登陸成功(認證成功),shiro認證成功會自動跳轉到上一個請求路徑
		//登陸失敗還到login頁面
		return "login";
	}
複製程式碼

配置認證過濾器


	<value>
		<!-- 對靜態資源設定匿名訪問 -->
		/images/** = anon
		/js/** = anon
		/styles/** = anon

		<!-- /** = authc 所有url都必須認證通過才可以訪問-->
		/** = authc
	</value>

複製程式碼

3.2退出

不用我們去實現退出,只要去訪問一個退出的url(該 url是可以不存在),由LogoutFilter攔截住,清除session。

在applicationContext-shiro.xml配置LogoutFilter:


		<!-- 請求 logout.action地址,shiro去清除session-->
		/logout.action = logout
複製程式碼

四、認證後資訊在頁面顯示

1、認證後使用者選單在首頁顯示 2、認證後使用者的資訊在頁頭顯示

realm從資料庫查詢使用者資訊,將使用者選單、usercode、username等設定在SimpleAuthenticationInfo中。


	//realm的認證方法,從資料庫查詢使用者資訊
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		// token是使用者輸入的使用者名稱和密碼 
		// 第一步從token中取出使用者名稱
		String userCode = (String) token.getPrincipal();

		// 第二步:根據使用者輸入的userCode從資料庫查詢
		SysUser sysUser = null;
		try {
			sysUser = sysService.findSysUserByUserCode(userCode);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// 如果查詢不到返回null
		if(sysUser==null){//
			return null;
		}
		// 從資料庫查詢到密碼
		String password = sysUser.getPassword();
		
		//鹽
		String salt = sysUser.getSalt();

		// 如果查詢到返回認證資訊AuthenticationInfo
		
		//activeUser就是使用者身份資訊
		ActiveUser activeUser = new ActiveUser();
		
		activeUser.setUserid(sysUser.getId());
		activeUser.setUsercode(sysUser.getUsercode());
		activeUser.setUsername(sysUser.getUsername());
		//..
		
		//根據使用者id取出選單
		List<SysPermission> menus  = null;
		try {
			//通過service取出選單 
			menus = sysService.findMenuListByUserId(sysUser.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//將使用者選單 設定到activeUser
		activeUser.setMenus(menus);

		//將activeUser設定simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				activeUser, password,ByteSource.Util.bytes(salt), this.getName());

		return simpleAuthenticationInfo;
	}
複製程式碼

配置憑配器,因為我們用到了md5和雜湊


<!-- 憑證匹配器 -->
<bean id="credentialsMatcher"
	class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
	<property name="hashAlgorithmName" value="md5" />
	<property name="hashIterations" value="1" />
</bean>
複製程式碼

<!-- realm -->
<bean id="customRealm" class="cn.itcast.ssm.shiro.CustomRealm">
	<!-- 將憑證匹配器設定到realm中,realm按照憑證匹配器的要求進行雜湊 -->
	<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
複製程式碼

在跳轉到首頁的時候,取出使用者的認證資訊,轉發到JSP即可


	//系統首頁
	@RequestMapping("/first")
	public String first(Model model)throws Exception{
		
		//從shiro的session中取activeUser
		Subject subject = SecurityUtils.getSubject();
		//取身份資訊
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		//通過model傳到頁面
		model.addAttribute("activeUser", activeUser);
		
		return "/first";
	}
複製程式碼

五、總結

  • Shiro使用者許可權有三種方式
    • 程式設計式
    • 註解式
    • 標籤式
  • Shiro的reaml預設都是去找配置檔案的資訊來進行授權的,我們一般都是要reaml去資料庫來查詢對應的資訊。因此,又需要自定義reaml
  • 總體上,認證和授權的流程差不多。
  • Spring與Shiro整合,Shiro實際上的操作都是通過過濾器來乾的。Shiro為我們提供了很多的過濾器。
    • 在web.xml中配置Shiro過濾器
    • 在Shiro配置檔案中使用web.xml配置過的過濾器。
  • 配置安全管理器類,配置自定義的reaml,將reaml注入到安全管理器類上。將安全管理器交由Shiro工廠來進行管理。
  • 在過濾器鏈中設定靜態資源不攔截。
  • 在Shiro使用過濾器來進行使用者認證,流程是這樣子的:
    • 配置用於認證的請求路徑
    • 當訪問程式設計師該請求路徑的時候,Shiro會使用FormAuthenticationFilter會呼叫reaml獲得使用者的資訊
    • reaml可以拿到token,通過使用者名稱從資料庫獲取得到使用者的資訊,如果使用者不存在則返回null
    • FormAuthenticationFilter會將reaml返回的資料進行對比,如果不同則丟擲異常
    • 我們的請求路徑僅僅是用來檢測有沒有異常丟擲,並不用來做校驗的。
  • shiro還提供了退出使用者的攔截器,我們配置一個url就行了。
  • 當需要獲取使用者的資料用於回顯的時候,我們可以在SecurityUtils.getSubject()來得到主體,再通過主體拿到身份資訊。

如果文章有錯的地方歡迎指正,大家互相交流。習慣在微信看技術文章,想要獲取更多的Java資源的同學,可以關注微信公眾號:Java3y

相關文章