Shiro 整合 Spring 第一次

輸入圖片說明

<!-- shiro的配置 -->
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-core</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-web</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-spring</artifactId>
		    <version>1.2.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-ehcache</artifactId>
		    <version>1.2.3</version>
		</dependency>

輸入圖片說明

<!-- shiro的filter -->
  <!-- shiro的過濾器,DeleagtionFilterProxy經過代理模式將spring容器中的bean的filter關聯起來 -->
  <filter>
  		<filter-name>shiroFilter</filter-name>
  		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  		<!-- 設置true 表示由sevlet容器控制filter的生命週期 -->
  		<init-param>
  			<param-name>targetFilterLifecycle</param-name>
  			<param-value>true</param-value>
  		</init-param>
  		
  		<!-- 設置spring容器的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>

輸入圖片說明

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter對應的bean -->
 		<!-- shiro的web過濾器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl認證提交地址,若是沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證-->
			<property name="loginUrl" value="/Login.action"/>
			<!-- 1.3  unauthorizedUrl指定沒有權限時跳轉頁面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			<!-- 1.4  過濾器鏈的定義 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- /**=anon anon全部的url均可以匿名訪問 -->
					/**=anon
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>

1 認證

輸入圖片說明

輸入圖片說明

package com.shi.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shi.exception.CustomException;

@Controller
public class LoginController {

	//登陸提交地址,和applicationContext-shiro.xml文件 中配置的loginUrl保持一致
	@RequestMapping("Login")
	public String Login(HttpServletRequest request) throws Exception{
		
		//若是失敗從request中獲取認證異常信息,shiroLoginFilure就是shiro異常類的權限類名
		String exceptionClassName=(String) request.getAttribute("shiroLoginFailure");
		
		System.out.println("登陸異常=========="+exceptionClassName);
		
		//根據shiro返回的異常類路徑判斷,拋出指定異常信息
		if(exceptionClassName!=null){
			if(UnknownAccountException.class.getName().equals(exceptionClassName)){
				throw new CustomException("帳戶不存在");
			}else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
				System.out.println("密碼錯誤");
				throw new CustomException("用戶名/密碼錯誤");
			}else{
				throw new Exception();//最終在異常處理器生成未知異常
			}
		}
		/**
		 * 此方法不處理登陸成功(認證成功),shiro認證成功會自動跳轉到上一個請求路徑
		 * 登陸失敗還到login頁面
		 */
		return "login";
	}
}

輸入圖片說明

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter對應的bean -->
 		<!-- shiro的web過濾器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl認證提交地址,若是沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證-->
			<property name="loginUrl" value="/login.action" />
			<!-- 1.3  unauthorizedUrl指定沒有權限時跳轉頁面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			
			<!-- 1.5  配置成功頁面 -->
			<property name="successUrl" value="/first.action"/>
			<!-- 1.4  過濾器鏈的定義 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- 對靜態資源進行匿名訪問 -->
					/images/**=anon
					<!-- 請求logout.action地址,shiro去清空session -->
					/logout.action=logout
					<!-- /**=authc 表示全部url都必須認證經過以後開能夠訪問 -->
					/**=authc
					
					<!-- /**=anon anon全部的url均可以匿名訪問 -->
					<!-- /**=anon -->
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>

輸入圖片說明

輸入圖片說明

輸入圖片說明

輸入圖片說明

2 受權

2.1 受權的配置文件java

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 1  配置filter對應的bean -->
 		<!-- shiro的web過濾器 -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<!-- 1.1 配置安全管理器 -->
			<property name="securityManager" ref="securityManager"/>
			<!-- 1.2 loginUrl認證提交地址,若是沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證-->
			<property name="loginUrl" value="/login.action" />
			<!-- 1.3  unauthorizedUrl指定沒有權限時跳轉頁面-->
			<property name="unauthorizedUrl" value="refuse.jsp" />
			
			<!-- 1.5  配置成功頁面 -->
			<property name="successUrl" value="/first.action"/>
			<!-- 1.4  過濾器鏈的定義 -->
			<property name="filterChainDefinitions">
				<value>
					<!-- 對靜態資源進行匿名訪問 -->
					/images/**=anon
					<!-- 請求logout.action地址,shiro去清空session -->
					/logout.action=logout
					<!-- /**=authc 表示全部url都必須認證經過以後開能夠訪問 -->
					
					<!-- 受權的控制 -->
					/items/query.action=perms[items:query]
					/user/query.action=perms[user:query]
					
					<!-- 對全部剩下的認證 -->
					/**=authc
					<!-- /**=anon anon全部的url均可以匿名訪問 -->
					<!-- /**=anon -->
				</value>
			</property>
		</bean>
<!-- 2  配置安全管理器  securityManager-->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="customRealm"></property>
		</bean>
		

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm"></bean>
</beans>

2.2 自定義的realmweb

package com.shi.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.shi.pojo.ActiveUser;

public class CustomRealm extends AuthorizingRealm{

	//設置realm的名字
	@Override
	public void setName(String name) {
		super.setName("customRealm");
	}
	
	
	/**
	 * 用於認證
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//1 從token中取出身份信息(token是用戶輸入的)
		String userCode=(String) token.getPrincipal();
		System.out.println("token.getPrincipal="+userCode); //打印出:zhangsan
		System.out.println("token.getCredentials="+token.getCredentials());//打印出:[C@3c3aeae4
		
		//2 根據用戶輸入的userCode從數據庫查詢
		//...  模擬數據庫中取出的密碼是"111111"
		String password="123456";
		
		//3 若是 查詢不到返回null
		/*if(!"zhangsan".equals(userCode)){
			return null;
		}*/
		
		//把用戶信息封裝到ActiveUser中
		ActiveUser activeUser=new ActiveUser();
		activeUser.setUserId(1);
		activeUser.setUserName("張三");
		activeUser.setUserPassword("123456");
		
		List<String> meniuList =new ArrayList<String>();
		meniuList.add("用戶管理");
		meniuList.add("商品管理");
		
		activeUser.setMeniuList(meniuList);
		
		//若是查詢到 返回認證信息AuthenticationInfo
		//這裏的用戶信息能夠存儲字符串,或者自定義的pojo
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(activeUser, password, this.getName());
		
		return simpleAuthenticationInfo;
	}
	
	/**
	 * 用於受權
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		/**
		 * 1  從principals中得到主身份信息
		 * 將getPrimaryPrincipal方法返回值轉爲真實身份類型,
		 * (在上邊的doGetAuthenticationInfo認證經過填充到SimpleAuthenticationInfo)
		 */
		ActiveUser activeUser=(ActiveUser) principals.getPrimaryPrincipal();
		System.out.println("principals.權限控制中獲取用戶信息="+activeUser);//打印出:zhangsan
		
		/**
		 * 2  根據身份信息獲取權限信息(從數據庫中查詢)
		 * 模擬查詢到的數據
		 */
		List<String> permissions=new ArrayList<String>();
		permissions.add("user:create");//用戶的建立
		permissions.add("items:add:1");//商品添加
		permissions.add("items:query");//商品查詢
		//3 查詢到數據返回受權信息
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		//4  將上面查詢到數據填充到SimpleAuthorizationInfo對象中
		simpleAuthorizationInfo.addStringPermissions(permissions);
		
		return simpleAuthorizationInfo;
	}

}

2.3 控制器spring

/**
	 * /items/query.action 查詢商品的action
	 */
	@RequestMapping("/items/query.action")
	public ModelAndView queryItems()throws Exception{
		ModelAndView mv =new ModelAndView();
		
		mv.setViewName("queryItems");
		return mv;
	}

3 幾點注意點

輸入圖片說明

輸入圖片說明

輸入圖片說明

輸入圖片說明

anon: 例子/admins/**=anon 沒有參數,表示能夠匿名使用。
authc: 例如/admins/user/**=authc表示須要認證(登陸)才能使用,FormAuthenticationFilter是表單認證,沒有參數 
roles: 例子/admins/user/**=roles[admin],參數能夠寫多個,多個時必須加上引號,而且參數之間用逗號分割,當有多個參數時,例如admins/user/**=roles["admin,guest"],每一個參數經過纔算經過,至關於hasAllRoles()方法。
perms: 例子/admins/user/**=perms[user:add:*],參數能夠寫多個,多個時必須加上引號,而且參數之間用逗號分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當有多個參數時必須每一個參數都經過才經過,想當於isPermitedAll()方法。
rest: 例子/admins/user/**=rest[user],根據請求的方法,至關於/admins/user/**=perms[user:method] ,其中method爲post,get,delete等。
port: 例子/admins/user/**=port[8081],當請求的url的端口不是8081是跳轉到schemal://serverName:8081?queryString,其中schmal是協議http或https等,serverName是你訪問的host,8081是url配置裏port的端口,queryString
是你訪問的url裏的?後面的參數。
authcBasic: 例如/admins/user/**=authcBasic沒有參數表示httpBasic認證

ssl:  例子/admins/user/**=ssl沒有參數,表示安全的url請求,協議爲https
user:  例如/admins/user/**=user沒有參數表示必須存在用戶, 身份認證經過或經過記住我認證經過的能夠訪問,當登入操做時不作檢查
注:
anon,authcBasic,auchc,user是認證過濾器,
perms,roles,ssl,rest,port是受權過濾器

4 基於 md5 認證 的配置方式

4.1 在applicationContext-shiro.xml文件中配置 憑證匹配器數據庫

<!-- 3  配置realm -->
		<bean id="customRealm" class="com.shi.shiro.CustomRealm">
			<property name="credentialsMatcher" ref="credentialsMatcher"></property>
		</bean>

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

</beans>

4.2 自定義realm中 認證配置apache

/**
	 * 用於認證
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		//1 從token中取出身份信息(token是用戶輸入的)
		String userCode=(String) token.getPrincipal();
		System.out.println("token.getPrincipal="+userCode); //打印出:zhangsan
		System.out.println("token.getCredentials="+token.getCredentials());//打印出:[C@3c3aeae4
		
		
		
		//3 若是 查詢不到返回null
		if(!"zhangsan".equals(userCode)){
			return null;
		}
		
		//2 根據用戶輸入的userCode從數據庫查詢
		//...  模擬數據庫中取出的密碼是"123456"
		String password="588043b2413a9a1e26a623f58606f148";
		String salt="sjsii";
		
		
		//把用戶信息封裝到ActiveUser中
		ActiveUser activeUser=new ActiveUser();
		activeUser.setUserId(1);
		activeUser.setUserName("張三");
		activeUser.setUserPassword("123456");
		
		List<String> meniuList =new ArrayList<String>();
		meniuList.add("用戶管理");
		meniuList.add("商品管理");
		
		activeUser.setMeniuList(meniuList);
		
		//若是查詢到 返回認證信息AuthenticationInfo
		//這裏的用戶信息能夠存儲字符串,或者自定義的pojo
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo
				(activeUser, password,ByteSource.Util.bytes(salt), this.getName());
		
		return simpleAuthenticationInfo;
	}
相關文章
相關標籤/搜索