這篇文章主要講解了“怎么在Spring的配置文件中對Shiro進行配置”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么在Spring的配置文件中對Shiro進行配置”吧!
為永定等地區(qū)用戶提供了全套網(wǎng)頁設計制作服務,及永定網(wǎng)站建設行業(yè)解決方案。主營業(yè)務為網(wǎng)站設計制作、做網(wǎng)站、永定網(wǎng)站設計,以傳統(tǒng)方式定制建設網(wǎng)站,并提供域名空間備案等一條龍服務,秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
首先集成Spring、SpringMVC和Shiro
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.2</version>
</dependency>
</dependencies>
在web.xml文件中配置Shiro的過濾器
<!--
1. 配置 Shiro 的 shiroFilter.
2. DelegatingFilterProxy 實際上是 Filter 的一個代理對象. 默認情況下, Spring 會到 IOC 容器中查找和
<filter-name> 對應的 filter bean. 也可以通過 targetBeanName 的初始化參數(shù)來配置 filter bean 的 id.
-->
<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>
創(chuàng)建Shiro的配置文件(ehcache-shiro.xml)
<ehcache updateCheck="false" name="shiroCache">
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
在Spring的配置文件中對Shiro進行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
1. 配置 SecurityManager!
-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
</bean>
<!--
2. 配置 CacheManager.
2.1 需要加入 ehcache 的 jar 包及配置文件.
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>
</bean>
<!-- =========================================================
Shiro Spring-specific integration
========================================================= -->
<!-- Post processor that automatically invokes init() and destroy() methods
for Spring-configured Shiro objects so you don't have to
1) specify an init-method and destroy-method attributes for every bean
definition and
2) even know which Shiro objects require these methods to be
called. -->
<!--
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> 一致.
若不一致, 則會拋出: NoSuchBeanDefinitionException. 因為 Shiro 會來 IOC 容器中查找和 <filter-name> 名字對應的 filter bean.
-->
<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 登出.
4). roles 角色過濾器
-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
# everything else requires authentication:
/** = authc
</value>
</property>
</bean>
</beans>
配置完成,啟動項目即可
工作流程
Shiro通過在web.xml配置文件中配置的ShiroFilter來攔截所有請求,并通過配置filterChainDefinitions來指定哪些頁面受保護以及它們的權限。
URL權限配置
[urls]部分的配置,其格式為:url=攔截器[參數(shù)];如果當前請求的url匹配[urls]部分的某個url模式(url模式使用Ant風格匹配),將會執(zhí)行其配置的攔截器,其中:
anon:該攔截器表示匿名訪問,即不需要登錄便可訪問
authc:該攔截器表示需要身份認證通過后才可以訪問
logout:登出
roles:角色過濾器
例:
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
# everything else requires authentication:
/** = authc
</value>
</property>
需要注意的是,url權限采取第一次匹配優(yōu)先的方式,即從頭開始使用第一個匹配的url模式對應的攔截器鏈,如:
/bb/**=filter1
/bb/aa=filter2
/**=filter3
如果請求的url是/bb/aa
,因為按照聲明順序進行匹配,那么將使用filter1進行攔截。
Shiro認證流程
獲取當前的Subject —— SecurityUtils.getSubject()
校驗當前用戶是否已經(jīng)被認證 —— 調用Subject的isAuthenticated()方法
若沒有被認證,則把用戶名和密碼封裝為UsernamePasswordToken對象
執(zhí)行登錄 —— 調動Subject的login(UsernamePasswordToken)方法
自定義Realm的方法,從數(shù)據(jù)庫中獲取對應的記錄,返回給Shiro
自定義類繼承org.apache.shiro.realm.AuthenticatingRealm
實現(xiàn)doGetAuthenticationInfo(AuthenticationToken)方法
由Shiro完成對用戶名密碼的比對
下面具體實現(xiàn)一下,首先創(chuàng)建login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h5>Login Page</h5>
<form action="shiroLogin" method="post">
username:<input type="text" name="username"/>
<br/>
<br/>
password:<input type="password" name="password"/>
<br/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
然后編寫控制器:
package com.wwj.shiro.handlers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class ShiroHandler {
@RequestMapping("/shiroLogin")
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
//獲取當前的Subject
Subject currentUser = SecurityUtils.getSubject();
//校驗當前用戶是否已經(jīng)被認證
if(!currentUser.isAuthenticated()){
//把用戶名和密碼封裝為UsernamePasswordToken對象
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
token.setRememberMe(true);
try {
//執(zhí)行登錄
currentUser.login(token);
}catch (AuthenticationException ae){
System.out.println("登錄失敗" + ae.getMessage());
}
}
return "redirect:/list.jsp";
}
}
編寫自定義的Realm:
package com.wwj.shiro.realms;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
public class ShiroRealm extends AuthenticatingRealm {
/**
* @param authenticationToken 該參數(shù)實際上是控制器方法中封裝用戶名和密碼后執(zhí)行l(wèi)ogin()方法傳遞進去的參數(shù)token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//將參數(shù)轉回UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//從UsernamePasswordToken中取出用戶名
String username = token.getUsername();
//調用數(shù)據(jù)庫方法,從數(shù)據(jù)表中查詢username對應的記錄
System.out.println("從數(shù)據(jù)庫中獲取Username:" + username + "對應的用戶信息");
//若用戶不存在,則可以拋出異常
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
//根據(jù)用戶信息的情況,決定是否需要拋出其它異常
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
/* 根據(jù)用戶信息的情況,構建AuthenticationInfo對象并返回,通常使用的實現(xiàn)類是SimpleAuthenticationInfo
* 以下信息是從數(shù)據(jù)庫中獲取的:
* principal:認證的實體信息,可以是username,也可以是數(shù)據(jù)表對應的用戶實體類對象
* credentials:密碼
* realmName:當前realm對象的name,調用父類的getName()方法即可
*/
Object principal = username;
Object credentials = "123456";
String realmName = getName();
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
return info;
}
}
記得在Spring配置文件中攔截表單請求:
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
<!-- 攔截表單請求 -->
/shiroLogin = anon
<!-- 登出 -->
/logout = logout
# everything else requires authentication:
/** = authc
</value>
</property>
登錄成功后跳轉至list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h5>List Page</h5>
<a href="logout">logout</a>
</body>
</html>
這里實現(xiàn)了一個登出請求,是因為Shiro在登錄成功后會有緩存,此時無論用戶名是否有效,都將成功登錄,所以這里進行一個登出操作。
編寫完成,最后啟動項目即可。
若沒有進行登錄,將無法訪問其它頁面,若輸入錯誤的用戶名,則無法成功登錄,也無法訪問其它頁面:
若輸入正確的用戶名和密碼,則登錄成功,可以訪問其它頁面:
重新來回顧一下上述的認證流程:
首先在login.jsp頁面中有一個表單用于登錄,當用戶輸入用戶名和密碼點擊登錄后,請求會被ShiroHandler控制器攔截
在ShiroHandler中校驗用戶是否已經(jīng)被認證,若未認證,則將用戶名和密碼封裝成UsernamePasswordToken對象,并執(zhí)行登錄
當執(zhí)行登錄后,UsernamePasswordToken對象會被傳入ShiroRealm類的doGetAuthenticationInfo()方法的入?yún)⒅校谠摲椒ㄖ袑?shù)據(jù)作進一步的校驗
密碼校驗的過程
在剛才的例子中,我們實現(xiàn)了在用戶登錄前后對頁面權限的控制,事實上,在程序中我們并沒有去編寫密碼比對的代碼,而登錄邏輯顯然對密碼進行了校驗,可以猜想這一定是Shiro幫助我們完成了密碼的校驗。
我們在UserNamePasswordToken類中的getPassword()方法中打一個斷點:
此時以debug的方式啟動項目,在表單中輸入用戶名和密碼,點擊登錄,程序就可以在該方法處暫停運行:
我們往前找在哪執(zhí)行了密碼校驗的邏輯,發(fā)現(xiàn)在doCredentialsMatch()方法:
再觀察右邊的參數(shù):
這不正是我在表單輸入的密碼和數(shù)據(jù)表中查詢出來的密碼嗎?由此確認在此處Shiro幫助我們對密碼進行了校驗。
在往前找找可以發(fā)現(xiàn):
Shiro實際上是用CredentialsMatcher對密碼進行校驗的,那么為什么要大費周章地來找CredentialsMatcher呢?
CredentialsMatcher是一個接口,我們來看看它的實現(xiàn)類:
那么相信大家已經(jīng)知道接下來要做什么了,沒錯,密碼的加密,而加密就是通過CredentialsMatcher來完成的。
MD5加密
加密算法其實有很多,這里以md5加密為例。
修改Spring配置文件中對自定義Realm的配置:
<bean id="myRealm" class="com.wwj.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<!-- 指定加密次數(shù) -->
<property name="hashIterations" value="5"/>
</bean>
</property>
</bean>
這里因為Md5CredentialsMatcher類已經(jīng)過期了,Shiro推薦直接使用HashedCredentialsMatcher。
這樣配置以后,從表單中輸入的密碼就能夠自動地進行MD5加密,但是從數(shù)據(jù)表中獲取的密碼仍然是明文狀態(tài),所以還需要對該密碼進行MD5加密:
public static void main(String[] args) {
String algorithmName = "MD5";
Object credentials = "123456";
Object salt = null;
int hashIterations = 5;
Object result = new SimpleHash(algorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
該代碼可以參考Shiro底層實現(xiàn),我們以Shiro同樣的方式對其進行MD5加密,兩份密碼都加密完成了,以debug運行項目,再次找到Shiro校驗密碼的地方:
我在表單輸入的密碼是123456,經(jīng)過校驗發(fā)現(xiàn),兩份密碼的密文是一致的,所以登錄成功。
考慮密碼重復的情況
剛才對密碼進行了加密,進一步解決了密碼的安全問題,但又有一個新問題擺在我們面前,倘若有兩個用戶的密碼是一樣的,這樣即使進行了加密,因為密文是一樣的,這樣仍然會有安全問題,那么能不能夠實現(xiàn)即使密碼一樣,但生成的密文卻可以不一樣呢?
當然是可以的,這里需要借助一個credentialsSalt屬性(這里我們假設以用戶名為標識進行密文的重新加密):
public static void main(String[] args) {
String algorithmName = "MD5";
Object credentials = "123456";
Object salt = ByteSource.Util.bytes("aaa");
//Object salt = ByteSource.Util.bytes("bbb");
int hashIterations = 5;
Object result = new SimpleHash(algorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
通過該方式,我們生成了兩個不一樣的密文,即使密碼一樣:
c8b8a6de6e890dea8001712c9e149496
3d12ecfbb349ddbe824730eb5e45deca
既然這里對加密進行了修改,那么在表單密碼進行加密的時候我們也要進行修改:
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//將參數(shù)轉回UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//從UsernamePasswordToken中取出用戶名
String username = token.getUsername();
//調用數(shù)據(jù)庫方法,從數(shù)據(jù)表中查詢username對應的記錄
System.out.println("從數(shù)據(jù)庫中獲取Username:" + username + "對應的用戶信息");
//若用戶不存在,則可以拋出異常
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
//根據(jù)用戶信息的情況,決定是否需要拋出其它異常
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
/* 根據(jù)用戶信息的情況,構建AuthenticationInfo對象并返回,通常使用的實現(xiàn)類是SimpleAuthenticationInfo
* 以下信息是從數(shù)據(jù)庫中獲取的:
* principal:認證的實體信息,可以是username,也可以是數(shù)據(jù)表對應的用戶實體類對象
* credentials:密碼
* realmName:當前realm對象的name,調用父類的getName()方法即可
*/
Object principal = username;
Object credentials = null;
//對用戶名進行判斷
if("aaa".equals(username)){
credentials = "c8b8a6de6e890dea8001712c9e149496";
}else if("bbb".equals(username)){
credentials = "3d12ecfbb349ddbe824730eb5e45deca";
}
String realmName = getName();
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);
return info;
}
這樣就輕松解決了密碼重復的安全問題了。
多Relam的配置
剛才實現(xiàn)的是單個Relam的情況,下面來看看多個Relam之間的配置。
首先自定義第二個Relam:
package com.wwj.shiro.realms;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
public class ShiroRealm2 extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("ShiroRealm2...");
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
System.out.println("從數(shù)據(jù)庫中獲取Username:" + username + "對應的用戶信息");
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
Object principal = username;
Object credentials = null;
if("aaa".equals(username)){
credentials = "ba89744a3717743bef169b120c052364621e6135";
}else if("bbb".equals(username)){
credentials = "29aa55fcb266eac35a6b9c1bd5eb30e41d4bfd8d";
}
String realmName = getName();
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);
return info;
}
public static void main(String[] args) {
String algorithmName = "SHA1";
Object credentials = "123456";
Object salt = ByteSource.Util.bytes("bbb");
int hashIterations = 5;
Object result = new SimpleHash(algorithmName, credentials, salt, hashIterations);
System.out.println(result);
}
}
這里簡單復制了第一個Relam的代碼,并將加密方式改為了SHA1。
接下來修改Spring的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<!-- 添加此處配置 -->
<property name="authenticator" ref="authenticator"/>
</bean>
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>
<!-- 添加此處配置 -->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="myRealm"/>
<ref bean="myRealm2"/>
</list>
</property>
</bean>
<bean id="myRealm" class="com.wwj.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="5"/>
</bean>
</property>
</bean>
<!-- 添加此處配置 -->
<bean id="myRealm2" class="com.wwj.shiro.realms.ShiroRealm2">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"/>
<property name="hashIterations" value="5"/>
</bean>
</property>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.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>
<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"/>
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiroLogin = anon
/logout = logout
# everything else requires authentication:
/** = authc
</value>
</property>
</bean>
</beans>
注釋的地方就是需要修改的地方。
此時我們啟動項目進行登錄,查看控制臺信息:
可以看到兩個Relam都被調用了。
認證策略
既然有多個Relam,那么就一定會有認證策略的區(qū)別,比如多個Relam中是一個認證成功即為成功還是要所有Relam都認證成功才算成功,Shiro對此提供了三種策略:
FirstSuccessfulStrategy:只要有一個Relam認證成功即可,只返回第一個Relam身份認證成功的認證信息,其它的忽略
AtLeastOneSuccessfulStrategy:只要有一個Relam認證成功即可,和FirstSuccessfulStrategy不同,它將返回所有Relam身份認證成功的認證信息
AllSuccessfulStrategy:所有Relam認證成功才算成功,且返回所有Relam身份認證成功的認證信息
默認使用的策略是AtLeastOneSuccessfulStrategy,具體可以通過查看源碼來體會。
若要修改默認的認證策略,可以修改Spring的配置文件:
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="myRealm"/>
<ref bean="myRealm2"/>
</list>
</property>
<!-- 修改認證策略 -->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>
</property>
</bean>
授權
授權也叫訪問控制,即在應用中控制誰訪問哪些資源,在授權中需要了解以下幾個關鍵對象:
主體:訪問應用的用戶
資源:在應用中用戶可以訪問的url
權限:安全策略中的原子授權單位
角色:權限的集合
下面實現(xiàn)一個案例來感受一下授權的作用,新建aaa.jsp和bbb.jsp文件,并修改list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h5>List Page</h5>
<a href="aaa.jsp">aaa Page</a>
<br/>
<br/>
<a href="bbb.jsp">bbb Page</a>
<br/>
<br/>
<a href="logout">logout</a>
</body>
</html>
現(xiàn)在的情況是登錄成功之后就能夠訪問aaa和bbb頁面了:
但是我想實現(xiàn)這樣一個效果,只有具備當前用戶的權限才能夠訪問到指定頁面,比如我以aaa用戶的身份登錄,那么我將只能訪問aaa.jsp而無法訪問bbb.jsp;同樣地,若以bbb用戶的身份登錄,則只能訪問bbb.jsp而無法訪問aaa.jsp,該如何實現(xiàn)呢?
實現(xiàn)其實非常簡單,修改Sping的配置文件:
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiroLogin = anon
/logout = logout
<!-- 添加角色過濾器 -->
/aaa.jsp = roles[aaa]
/bbb.jsp = roles[bbb]
# everything else requires authentication:
/** = authc
</value>
</property>
啟動項目看看效果:
這里有一個坑,就是在編寫授權之前,你需要將Relam的引用放到securityManager中:
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
<property name="realms">
<list>
<ref bean="myRealm"/>
<ref bean="myRealm2"/>
</list>
</property>
</bean>
否則程序將無法正常運行。
現(xiàn)在雖然把權限加上了,但無論你是aaa用戶還是bbb用戶,你都無法訪問到頁面了,Shiro都自動跳轉到了無權限頁面,我們還需要做一些操作,對ShiroRelam類進行修改:
package com.wwj.shiro.realms;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.HashSet;
import java.util.Set;
public class ShiroRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
System.out.println("從數(shù)據(jù)庫中獲取Username:" + username + "對應的用戶信息");
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
Object principal = username;
Object credentials = null;
if("aaa".equals(username)){
credentials = "c8b8a6de6e890dea8001712c9e149496";
}else if("bbb".equals(username)){
credentials = "3d12ecfbb349ddbe824730eb5e45deca";
}
String realmName = getName();
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);
return info;
}
&n
當前名稱:怎么在Spring的配置文件中對Shiro進行配置
鏈接分享:http://bm7419.com/article24/pscgje.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供電子商務、虛擬主機、網(wǎng)站設計、品牌網(wǎng)站設計、App開發(fā)、網(wǎng)站維護
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源:
創(chuàng)新互聯(lián)