
Shiro集成Springhtml


首先集成Spring、SpringMVC和Shirojava
<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的過濾器web
<!--
1. 配置 Shiro 的 shiroFilter.
2. DelegatingFilterProxy 其實是 Filter 的一個代理對象. 默認狀況下, Spring 會到 IOC 容器中查找和
<filter-name> 對應的 filter bean. 也能夠經過 targetBeanName 的初始化參數來配置 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>
建立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進行配置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">
<!--
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>
配置完成,啓動項目便可數據庫

工做流程apache



Shiro經過在web.xml配置文件中配置的ShiroFilter來攔截全部請求,並經過配置filterChainDefinitions來指定哪些頁面受保護以及它們的權限。緩存

URL權限配置安全


[urls]部分的配置,其格式爲:url=攔截器[參數];若是當前請求的url匹配[urls]部分的某個url模式(url模式使用Ant風格匹配),將會執行其配置的攔截器,其中:微信
anon:該攔截器表示匿名訪問,即不須要登陸即可訪問
authc:該攔截器表示須要身份認證經過後才能夠訪問
logout:登出
roles:角色過濾器
例:
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
# everything else requires authentication:
/** = authc
</value>
</property>
須要注意的是,url權限採起第一次匹配優先的方式,即從頭開始使用第一個匹配的url模式對應的攔截器鏈,如:
/bb/**=filter1
/bb/aa=filter2
/**=filter3
若是請求的url是/bb/aa
,由於按照聲明順序進行匹配,那麼將使用filter1進行攔截。

Shiro認證流程


獲取當前的Subject —— SecurityUtils.getSubject()
校驗當前用戶是否已經被認證 —— 調用Subject的isAuthenticated()方法
若沒有被認證,則把用戶名和密碼封裝爲UsernamePasswordToken對象
執行登陸 —— 調動Subject的login(UsernamePasswordToken)方法
自定義Realm的方法,從數據庫中獲取對應的記錄,返回給Shiro
自定義類繼承org.apache.shiro.realm.AuthenticatingRealm
實現doGetAuthenticationInfo(AuthenticationToken)方法
由Shiro完成對用戶名密碼的比對
下面具體實現一下,首先建立login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>Login Page</h4>
<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();
//校驗當前用戶是否已經被認證
if(!currentUser.isAuthenticated()){
//把用戶名和密碼封裝爲UsernamePasswordToken對象
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
token.setRememberMe(true);
try {
//執行登陸
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 該參數其實是控制器方法中封裝用戶名和密碼後執行login()方法傳遞進去的參數token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//將參數轉回UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//從UsernamePasswordToken中取出用戶名
String username = token.getUsername();
//調用數據庫方法,從數據表中查詢username對應的記錄
System.out.println("從數據庫中獲取Username:" + username + "對應的用戶信息");
//若用戶不存在,則能夠拋出異常
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
//根據用戶信息的狀況,決定是否須要拋出其它異常
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
/* 根據用戶信息的狀況,構建AuthenticationInfo對象並返回,一般使用的實現類是SimpleAuthenticationInfo
* 如下信息是從數據庫中獲取的:
* principal:認證的實體信息,能夠是username,也能夠是數據表對應的用戶實體類對象
* 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>
<h4>List Page</h4>
<a href="logout">logout</a>
</body>
</html>
這裏實現了一個登出請求,是由於Shiro在登陸成功後會有緩存,此時不管用戶名是否有效,都將成功登陸,因此這裏進行一個登出操做。
編寫完成,最後啓動項目便可。

若沒有進行登陸,將沒法訪問其它頁面,若輸入錯誤的用戶名,則沒法成功登陸,也沒法訪問其它頁面:

若輸入正確的用戶名和密碼,則登陸成功,能夠訪問其它頁面:

從新來回顧一下上述的認證流程:
首先在login.jsp頁面中有一個表單用於登陸,當用戶輸入用戶名和密碼點擊登陸後,請求會被ShiroHandler控制器攔截
在ShiroHandler中校驗用戶是否已經被認證,若未認證,則將用戶名和密碼封裝成UsernamePasswordToken對象,並執行登陸
當執行登陸後,UsernamePasswordToken對象會被傳入ShiroRealm類的doGetAuthenticationInfo()方法的入參中,在該方法中對數據做進一步的校驗

密碼校驗的過程


在剛纔的例子中,咱們實現了在用戶登陸先後對頁面權限的控制,事實上,在程序中咱們並無去編寫密碼比對的代碼,而登陸邏輯顯然對密碼進行了校驗,能夠猜測這必定是Shiro幫助咱們完成了密碼的校驗。
咱們在UserNamePasswordToken類中的getPassword()方法中打一個斷點:

此時以debug的方式啓動項目,在表單中輸入用戶名和密碼,點擊登陸,程序就能夠在該方法處暫停運行:

咱們往前找在哪執行了密碼校驗的邏輯,發如今doCredentialsMatch()方法:

再觀察右邊的參數:

這不正是我在表單輸入的密碼和數據表中查詢出來的密碼嗎?由此確認在此處Shiro幫助咱們對密碼進行了校驗。
在往前找找能夠發現:

Shiro其實是用CredentialsMatcher對密碼進行校驗的,那麼爲何要大費周章地來找CredentialsMatcher呢?
CredentialsMatcher是一個接口,咱們來看看它的實現類:

那麼相信你們已經知道接下來要作什麼了,沒錯,密碼的加密,而加密就是經過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"/>
<!-- 指定加密次數 -->
<property name="hashIterations" value="5"/>
</bean>
</property>
</bean>
這裏由於Md5CredentialsMatcher類已通過期了,Shiro推薦直接使用HashedCredentialsMatcher。
這樣配置之後,從表單中輸入的密碼就可以自動地進行MD5加密,可是從數據表中獲取的密碼仍然是明文狀態,因此還須要對該密碼進行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底層實現,咱們以Shiro一樣的方式對其進行MD5加密,兩份密碼都加密完成了,以debug運行項目,再次找到Shiro校驗密碼的地方:

我在表單輸入的密碼是123456,通過校驗發現,兩份密碼的密文是一致的,因此登陸成功。

考慮密碼重複的狀況


剛纔對密碼進行了加密,進一步解決了密碼的安全問題,但又有一個新問題擺在咱們面前,假若有兩個用戶的密碼是同樣的,這樣即便進行了加密,由於密文是同樣的,這樣仍然會有安全問題,那麼能不可以實現即便密碼同樣,但生成的密文卻能夠不同呢?
固然是能夠的,這裏須要藉助一個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 {
//將參數轉回UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//從UsernamePasswordToken中取出用戶名
String username = token.getUsername();
//調用數據庫方法,從數據表中查詢username對應的記錄
System.out.println("從數據庫中獲取Username:" + username + "對應的用戶信息");
//若用戶不存在,則能夠拋出異常
if("unknow".equals(username)){
throw new UnknownAccountException("用戶不存在!");
}
//根據用戶信息的狀況,決定是否須要拋出其它異常
if("monster".equals(username)){
throw new LockedAccountException("用戶被鎖定!");
}
/* 根據用戶信息的狀況,構建AuthenticationInfo對象並返回,一般使用的實現類是SimpleAuthenticationInfo
* 如下信息是從數據庫中獲取的:
* principal:認證的實體信息,能夠是username,也能夠是數據表對應的用戶實體類對象
* 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的配置


剛纔實現的是單個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("從數據庫中獲取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,那麼就必定會有認證策略的區別,好比多個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
權限:安全策略中的原子受權單位
角色:權限的集合
下面實現一個案例來感覺一下受權的做用,新建aaa.jsp和bbb.jsp文件,並修改list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>List Page</h4>
<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>
如今的狀況是登陸成功以後就可以訪問aaa和bbb頁面了:

可是我想實現這樣一個效果,只有具有當前用戶的權限纔可以訪問到指定頁面,好比我以aaa用戶的身份登陸,那麼我將只能訪問aaa.jsp而沒法訪問bbb.jsp;一樣地,若以bbb用戶的身份登陸,則只能訪問bbb.jsp而沒法訪問aaa.jsp,該如何實現呢?
實現其實很是簡單,修改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>
不然程序將沒法正常運行。
如今雖然把權限加上了,但不管你是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("從數據庫中獲取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;
}
/**
* 受權時會被Shiro回調的方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//獲取登陸用戶的信息
Object principal = principalCollection.getPrimaryPrincipal();
//獲取當前用戶的角色
Set<String> roles = new HashSet<>();
roles.add("aaa");
if("bbb".equals(principal)){
roles.add("bbb");
}
//建立SimpleAuthorizationInfo,並設置其roles屬性
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
return info;
}
}
首先將繼承的類作了修改,改成繼承AuthorizingRealm類,能夠經過實現該類的doGetAuthenticationInfo()方法完成認證,經過doGetAuthorizationInfo()方法完成受權,因此源代碼不用動,直接添加下面的doGetAuthorizationInfo()方法便可,看運行效果:

能夠看到aaa用戶只能訪問到aaa.jsp而沒法訪問bbb.jsp,可是bbb用戶卻可以訪問到兩個頁面,若是你仔細觀察剛纔添加的方法你就可以明白爲何。
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//獲取登陸用戶的信息
Object principal = principalCollection.getPrimaryPrincipal();
//獲取當前用戶的角色
Set<String> roles = new HashSet<>();
roles.add("aaa");
if("bbb".equals(principal)){
roles.add("bbb");
}
//建立SimpleAuthorizationInfo,並設置其roles屬性
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
return info;
}
由於不論是什麼用戶登陸,我都將aaa用戶添加到了roles中,因此bbb用戶是具備aaa用戶權限的,權限徹底是由你本身控制的,想怎麼控制你就怎麼寫。

註解實現受權


先來看看關於受權的幾個註解:
@RequiresAuthentication:表示當前Subject已經經過login進行了身份驗證;即 Subject. isAuthenticated()返回 true
@RequiresUser:表示當前 Subject 已經身份驗證或者經過記住我登陸的
@RequiresGuest:表示當前Subject沒有身份驗證或經過記住我登陸過,便是遊客身份。
@RequiresRoles(value={「aaa」, 「bbb」}, logical=Logical.AND):表示當前 Subject 須要角色aaa和bbb
@RequiresPermissions (value={「user:a」, 「user:b」},logical= Logical.OR):表示當前 Subject 須要權限user:a 或user:b
把Spring配置文件中的角色過濾器刪掉,而後定義一個Service:
package com.wwj.shiro.service;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Service;
@Service
public class ShiroService {
@RequiresRoles({"aaa"})
public void test(){
System.out.println("test...");
}
}
在test()方法上添加註解@RequiresRoles({"aaa"}),意思是該方法只有aaa用戶才能訪問,接下來在ShiroHandler中添加一個方法:
@Autowired
private ShiroService shiroService;
@RequestMapping("/testAnnotation")
public String testAnnotation(){
shiroService.test();
return "redirect:/list.jsp";
}
此時當你訪問testAnnotation請求時,只有aaa用戶可以成功訪問,bbb用戶就會拋出異常。
uiresRoles(value={「aaa」, 「bbb」}, logical=Logical.AND):表示當前 Subject 須要角色aaa和bbb
@RequiresPermissions (value={「user:a」, 「user:b」},logical= Logical.OR):表示當前 Subject 須要權限user:a 或user:b
把Spring配置文件中的角色過濾器刪掉,而後定義一個Service:
package com.wwj.shiro.service;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Service;
@Service
public class ShiroService {
@RequiresRoles({"aaa"})
public void test(){
System.out.println("test...");
}
}
在test()方法上添加註解@RequiresRoles({"aaa"}),意思是該方法只有aaa用戶才能訪問,接下來在ShiroHandler中添加一個方法:
@Autowired
private ShiroService shiroService;
@RequestMapping("/testAnnotation")
public String testAnnotation(){
shiroService.test();
return "redirect:/list.jsp";
}
此時當你訪問testAnnotation請求時,只有aaa用戶可以成功訪問,bbb用戶就會拋出異常。
本文分享自微信公衆號 - 碼視界(otc_18679428729)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。