SSM項目整合Shiro進行身份驗證

一、簡介

身份驗證指的是系統一般需要提供一些標識信息來表明登錄者的身份,如提供用戶名和密碼,或手機號和驗證碼來證明。在 Shiro 中,用戶需要提供principals(身份)和 credentials(證明)給 Shiro來驗證用戶身份。

  • principals:身份即爲主體的標識屬性,它可以是任何屬性,如用戶名、 郵箱,手機號等,必須保證唯一。一個主體可以有多個principals,但只有一個 Primary principals,一般是用戶名/郵箱/手機號。
  • credentials:證明/憑證,即只有主體知道的安全值,如密碼/數字證 書等。

最常見的 principals 和 credentials 組合就是用戶名和密碼了。

二、流程

身份驗證的具體流程,如下圖所示:
在這裏插入圖片描述
下面具體說明圖中的五個步驟,如下:

  1. 首先調用 Subject.login(token) 進行登錄,其會自動委託給SecurityManager,調用之前必須通過 SecurityUtils.setSecurityManager() 設置;
  2. SecurityManager 負責真正的身份驗證邏輯;它會委託給Authenticator 進行身份驗證;
  3. Authenticator 纔是真正的身份驗證者,Shiro API 中核心的身份認證入口點,此處可以自定義插入自己的實現;
  4. Authenticator 可能會委託給相應的 AuthenticationStrategy 進 行多 Realm 身份驗證,默認 ModularRealmAuthenticator 會調用AuthenticationStrategy 進行多 Realm 身份驗證;
  5. Authenticator 會把相應的 token 傳入 Realm,從 Realm 獲取身份驗證信息,如果沒有返回或者拋出異常表示身份驗證失敗了。此處可以配置多個Realm,將按照相應的順序及策略進行訪問。

使用

1.環境配置

下面基於之前這篇文章裏創建的SSM項目爲基礎來整合Shiro:https://blog.csdn.net/huangjhai/article/details/104068993

1.pom.xml上添加以下依賴:

        <!-- shiro包 -->     
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-all</artifactId>
		    <version>1.3.2</version>
		</dependency>
		<!-- Ehcache包 -->
		<dependency>
		    <groupId>net.sf.ehcache</groupId>
		    <artifactId>ehcache-core</artifactId>
		    <version>2.4.3</version>
		</dependency>

2.springmvc.xml添加shiro.filter配置,如下:

    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

3.applicationContext.xml配置,:

   <!--   1. 配置 SecurityManager!-->     
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>     
        <property name="realm" ref="jdbcRealm" />  
        
    </bean>
    <!--  
    2. 配置 CacheManager. 
    2.1 需要加入 ehcache 的 jar 包及配置文件. 
    -->     
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
    </bean>
    <!-- 
    	3. 配置 Realm 
    	3.1 直接配置實現了 org.apache.shiro.realm.Realm 接口的 bean
    -->     
    <bean id="jdbcRealm" class="com.learn.shiro.realms.ShiroRealm">
        <property name="credentialsMatcher">
         <!-- 憑證匹配器的類型 -->
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
          <!--加密算法 -->
             <property name="hashAlgorithmName" value="MD5"></property>
         <!-- 加密次數 -->
             <property name="hashIterations" value="1024"></property>
        </bean>
        </property>    
    </bean>
    <!--  
    4. 配置 LifecycleBeanPostProcessor. 可以自定的來調用配置在 Spring IOC 容器中 shiro bean 的生命週期方法. 
    -->       
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!--  
    5. 啓用 IOC 容器中使用 shiro 的註解. 但必須在配置了 LifecycleBeanPostProcessor 之後纔可以使用. 
    -->     
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    <!--  
    6. 配置 ShiroFilter. 
    6.1 id 必須和 web.xml 文件中配置的 DelegatingFilterProxy 的 <filter-name> 一致.
    -->     
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login.jsp"/>
        <property name="successUrl" value="/list.jsp"/>
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!--  
        	配置哪些頁面需要受保護. 
        	以及訪問這些頁面需要的權限. 
        	1). anon 可以被匿名訪問
        	2). authc 必須認證(即登錄)後纔可能訪問的頁面. 
        	3). logout 登出.
        -->
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                /shiro/login=anon
                /shiro/logout=logout
                 /error=anon            
                # everything else requires authentication:
                /** = authc
            </value>
        </property>
    </bean> 

這裏配置的cacheManager時出現了這樣的錯誤:

Cannot convert value of type [org.apache.shiro.cache.ehcache.EhCacheManager] to required type [net.sf.ehcache.CacheManager] for property 'cacheManager': no matching editors or conversion strategy found

就是沒法將[org.apache.shiro.cache.ehcache.EhCacheManager]轉換成[net.sf.ehcache.CacheManager] 。這是由於我使用byname的方式自動注入bean。而引入的net.sf.ehcache包中有着同名的bean。這裏可以改爲byType方式注入或者bean換個id。

4.添加ehcache.xml,直接使用了Shiro整合Spring的示例中的,如下:

<ehcache>
    <diskStore path="java.io.tmpdir"/>  
    <cache name="authorizationCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="authenticationCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <cache name="shiro-activeSessionCache"
           eternal="false"
           timeToIdleSeconds="3600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        />
    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        overflowToDisk="true"
        />
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> 
</ehcache>

2.測試

1.創建pojo包並創建users類

public class Users {
	private int id;
	private String username;
	private String password;
	//省略getter和setting方法

2.創建mapper包並創建usersMapper接口和usersMapper.xml
usersMapper.java:

public interface UsersMapper {
    public Users selUser(String username);
}

usersMapper.xml.java:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="com.learn.mapper.UsersMapper">
   <select id="selUser" parameterType="string" resultType="com.learn.pojo.Users">
   select * from users where username=#{username}
   </select>
  </mapper>

3.創建service包並創建usersService接口和usersServiceImpl實現類
usersService.java:

public interface UsersService {
	 public Users selUser(String username);
}

usersServiceImpl.java:

@Service
public class UsersServiceImpl implements UsersService {
	@Resource
	private UsersMapper usersMapper;
	@Override
	public Users selUser(String username) {
		// TODO Auto-generated method stub
		return usersMapper.selUser(username);
	}
}

4.創建controller並創建LoginController類

@Controller
@RequestMapping("/shiro")
public class LoginController {
	@RequestMapping(value = "login",method = RequestMethod.POST)
	public String checkLogin(@RequestParam("username") String username,@RequestParam("password") String password) {		
	      Subject currentUser = SecurityUtils.getSubject();
	      if (!currentUser.isAuthenticated()) {
	        	// 把用戶名和密碼封裝爲 UsernamePasswordToken 對象
	            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
	            System.out.println(username+": "+password);
	            try {
	            	// 執行登錄. 
	                currentUser.login(token);
	            } 
	            // 所有認證時異常的父類. 
	            catch (AuthenticationException ae) {
	                System.out.println("出現異常:——————->"+ae.getMessage());
	                return "error";
	            }
	        }
		return "list";
	}
}

5.創建ShiroRealm類繼承AuthenticatingRealm,如下:

public class ShiroRealm extends AuthenticatingRealm{
	@Autowired
	private UsersServiceImpl usersService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		System.out.println(token);
		//1.AutenticationToken轉換爲UsernamePasswordToken
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
		//2。從UsernamePasswordToken中取出username
		String username=usernamePasswordToken.getUsername();		
		//3.從數據庫中查詢username對應的用戶記錄
		Users users=usersService.selUser(username);			
		
		//4.若用戶不存在則拋出UnknowAccountException異常
		if (users==null) {
			throw new UnknownAccountException("用戶不存在");
		}
		//5.根據用戶信息的情況,決定是否需要拋出其他的 AuthenticationException異常
		
		//6.根據用戶的情況,來構建AuthenticationInfo對象返回
		Object principal=username;//認證的實體信息,可以是用戶名或數據包對應的用戶實體類對象
		Object credentials=users.getPassword();//密碼
		String realmName=getName();//當前realm對象的name,調用父類的getName()方法即可
		ByteSource credentialsSalt=ByteSource.Util.bytes(principal);//MD5的鹽值
		/*
		 * 這裏模擬生成在數據庫中保存的經過以用戶名爲鹽值的MD5算法加密後的密碼
		 */
		Object hashedCredentials=new SimpleHash("MD5", credentials, credentialsSalt, 1024);
		System.out.println("數據庫中的密碼:"+hashedCredentials);
		System.out.println("用戶輸入的經Shiro加密後的密碼:"+new SimpleHash("MD5", token.getCredentials(), credentialsSalt, 1024));
		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, hashedCredentials,credentialsSalt, realmName);
		return info;
	}
}

創建表單頁面後進行測試項目,瀏覽器訪問:
在這裏插入圖片描述
可以看到當密碼不正確時,會拋出異常:did not match the expected credentials.

當數據庫的密碼和輸入的密碼一致時,則會返回SimpleAuthenticationInfo對象,如下:
在這裏插入圖片描述

多Realm配置

1.首先在applicationContext.xml中配置,其中選擇加密算法爲SHA1

    <!-- 配置第二個Realm -->
   <bean id="jdbcRealmTwo" class="com.learn.shiro.realms.ShiroRealmTwo">
        <property name="credentialsMatcher">
         <!-- 憑證匹配器的類型 -->
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
          <!--加密算法 -->
             <property name="hashAlgorithmName" value="SHA1"></property>
         <!-- 加密次數 -->
             <property name="hashIterations" value="1024"></property>
        </bean>
        </property>    
    </bean>

2.在對應配置中的class創建ShiroRealmTwo,這裏直接複製 ShiroReal,添加顯示提示代碼,如下:

public class ShiroRealmTwo extends AuthenticatingRealm{
	@Autowired
	private UsersServiceImpl usersService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		System.out.println(token);
		System.out.println("---------ShiroRealmTwo  was called!------------");
		//1.AutenticationToken轉換爲UsernamePasswordToken
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
		//2。從UsernamePasswordToken中取出username
		String username=usernamePasswordToken.getUsername();		
		//3.從數據庫中查詢username對應的用戶記錄
		Users users=usersService.selUser(username);			
		
		//4.若用戶不存在則拋出UnknowAccountException異常
		if (users==null) {
			throw new UnknownAccountException("用戶不存在");
		}
		//5.根據用戶信息的情況,決定是否需要拋出其他的 AuthenticationException異常
		
		//6.根據用戶的情況,來構建AuthenticationInfo對象返回
		Object principal=username;//認證的實體信息,可以是用戶名或數據包對應的用戶實體類對象
		Object credentials=users.getPassword();//密碼
		String realmName=getName();//當前realm對象的name,調用父類的getName()方法即可
		ByteSource credentialsSalt=ByteSource.Util.bytes(principal);//MD5的鹽值
		/*
		 * 這裏模擬生成在數據庫中保存的經過以用戶名爲鹽值的MD5算法加密後的密碼,
		 * 在保存時可以使用SimpleHash進行構造加密後的密碼。
		 */
		Object hashedCredentials=new SimpleHash("MD5", credentials, credentialsSalt, 1024);
		System.out.println("數據庫中的密碼:"+hashedCredentials);
		System.out.println("用戶輸入的經Shiro加密後的密碼:"+new SimpleHash("SHA1", token.getCredentials(), credentialsSalt, 1024));
		//SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, credentials, realmName);
		//進行身份驗證
		SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, hashedCredentials,credentialsSalt, realmName);		
	return info;
		
	}
}

  1. Authenticator及AuthenticationStrategy
    Authenticator的職責是驗證用戶帳號,是Shiro API中身份驗證核心的入口點。如果驗證成功,將返回AuthenticationInfo驗證信息;此信息中包含了身份及憑證;如果驗證失敗將拋出相應的AuthenticationException實現。

SecurityManager接口繼承了Authenticator,另外還有一個ModularRealmAuthenticator實現,其委託給多個Realm進行驗證,驗證規則通過AuthenticationStrategy接口指定。

ModularRealmAuthenticator實現驗證功能的是doAuthenticate方法,而realms是一個集合。當只用一個realm時調用doSingleRealmAuthentication方法,realm數量大於一時調用doMultiRealmAuthentication方法。

    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        if (realms.size() == 1) {
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }

這裏配置ModularRealmAuthenticator的realms屬性

    <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
       <property name="realms">
          <list>
                <ref bean="jdbcRealm"/>
                <ref bean="jdbcRealmTwo"/>
          </list>  
       </property>
    </bean>

對應的需要配置SecurityManager的authenticator屬性,將authenticator配置給SecurityManager。

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>      
        <property name="authenticator" ref="authenticator"></property>
    </bean>

這樣就完成了第二個Realm的配置

再次訪問在這裏插入圖片描述
可以看到securityManager會按照realms指定的順序進行身份認證。先動用ShiroRealm再調用ShiroRealmTwo。對應了配置文件中的順序。而ShiroRealmTwo的密碼不一致,仍然可以登錄成功登錄。這是因爲ModularRealmAuthenticator默認使用的是AtLeastOneSuccessfulStrategy策略

Shiro默認提供的AuthenticationStrategy接口實現有:

  • FirstSuccessfulStrategy:只要有一個Realm驗證成功即可,只返回第一個Realm身份驗證成功的認證信息,其他的忽略;
  • AtLeastOneSuccessfulStrategy:只要有一個Realm驗證成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份驗證成功的認證信息;
  • AllSuccessfulStrategy:所有Realm驗證成功纔算成功,且返回所有Realm身份驗證成功的認證信息,如果有一個失敗就失敗了。

這篇文章將對這個項目的身份驗證流程的源碼分析一下:
Shiro的身份驗證流程的源碼分析

參考:
https://www.w3cschool.cn/shiro/xgj31if4.html

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