Shiro系列之Shiro+Spring MVC整合(Integration)
來源:程序員人生 發(fā)布時間:2016-04-05 08:00:41 閱讀次數(shù):3054次
Shiro系列之Shiro+Spring MVC整合
第1步,Shiro Filter
在web.xml文件中增加以下代碼,確保Web項(xiàng)目中需要權(quán)限管理的URL都可以被Shiro攔截過濾。
<!-- 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>
通常將這段代碼中的filter-mapping放在所有filter-mapping之前,以到達(dá)shiro是第1個對web要求進(jìn)行攔截過濾之目的。這里的fileter-name應(yīng)當(dāng)要和第2步中配置的java bean的id1致。
第2步,配置各種Java Bean
在root-context.xml文件中配置Shiro
<?xml version="1.0" encoding="UTF⑻"?>
<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">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/etao_java" />
<property name="username" value="root" />
<property name="password" value="cope9020" />
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
<!--
數(shù)據(jù)庫保存的密碼是使用MD5算法加密的,所以這里需要配置1個密碼匹配對象 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>
<!-- 緩存管理 -->
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>
<!--
使用Shiro自帶的JdbcRealm類
指定密碼匹配所需要用到的加密對象
指定存儲用戶、角色、權(quán)限許可的數(shù)據(jù)源及相干查詢語句
-->
<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
<property name="permissionsLookupEnabled" value="true"></property>
<property name="dataSource" ref="dataSource"></property>
<property name="authenticationQuery"
value="SELECT password FROM sec_user WHERE user_name = ?"></property>
<property name="userRolesQuery"
value="SELECT role_name from sec_user_role left join sec_role using(role_id) left join sec_user using(user_id) WHERE user_name = ?"></property>
<property name="permissionsQuery"
value="SELECT permission_name FROM sec_role_permission left join sec_role using(role_id) left join sec_permission using(permission_id) WHERE role_name = ?"></property>
</bean>
<!-- Shiro安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="jdbcRealm"></property>
<property name="cacheManager" ref="cacheManager"></property>
</bean>
<!--
Shiro主過濾器本身功能10分強(qiáng)大,其強(qiáng)大的地方就在于它支持任何基于URL路徑表達(dá)式的、自定義的過濾器的履行
Web利用中,Shiro可控制的Web要求必須經(jīng)過Shiro主過濾器的攔截,Shiro對基于Spring的Web利用提供了完善的支持
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,這個屬性是必須的 -->
<property name="securityManager" ref="securityManager"></property>
<!-- 要求登錄時的鏈接(登錄頁面地址),非必須的屬性,默許會自動尋覓Web工程根目錄下的"/login.jsp"頁面 -->
<property name="loginUrl" value="/security/login"></property>
<!-- 登錄成功后要跳轉(zhuǎn)的連接(本例中此屬性用不到,由于登錄成功后的處理邏輯在LoginController里硬編碼) -->
<!-- <property name="successUrl" value="/" ></property> -->
<!-- 用戶訪問未對其授權(quán)的資源時,所顯示的連接 -->
<property name="unauthorizedUrl" value="/"></property>
<property name="filterChainDefinitions">
<value>
/security/*=anon
/tag=authc
</value>
</property>
</bean>
<!--
開啟Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP掃描使用Shiro注解的類,
并在必要時進(jìn)行安全邏輯驗(yàn)證
-->
<!--
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"></property>
</bean>
-->
</beans>
上述代碼中已對每一個java bean的用處做了詳細(xì)的注釋說明,這里僅對FilterChain過濾鏈的定義詳細(xì)論述1下:
- 測試用例中對/security/*的訪問是不需要認(rèn)證控制的,這主要是用于用戶登錄和退出的
- 測試用例中對/tag的訪問是需要認(rèn)證控制的,就是說只有通過認(rèn)證的用戶才可以訪問該資源。如果用戶直接在地址欄中訪問http://localhost:8880/learning/tag,系統(tǒng)會自動跳轉(zhuǎn)至登錄頁面,要求用戶先進(jìn)行身份認(rèn)證。
完成這兩步以后,我們可以Run1下程序,如果可以看到以下頁面,就表明我們的配置文件沒有毛病,Shiro和Spring MVC的整合已完成了。后繼的步驟可以視為是對整合后的框進(jìn)行的1個測試。

第3步,編寫登錄頁面和后臺代碼
<%@ page language="java" contentType="text/html; charset=UTF⑻"
pageEncoding="UTF⑻"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF⑻">
<title>Login Page</title>
</head>
<body>
<h1>login page</h1>
<form id="" action="dologin" method="post">
<label>User Name</label> <input tyep="text" name="userName"
maxLength="40" /> <label>Password</label><input type="password"
name="password" /> <input type="submit" value="login" />
</form>
<%--用于輸入后臺返回的驗(yàn)證毛病信息 --%>
<P><c:out value="${message }" /></P>
</body>
</html>

后臺登錄代碼
/**
* 實(shí)際的登錄代碼
* 如果登錄成功,跳轉(zhuǎn)至首頁;登錄失敗,則將失敗信息反饋對用戶
*
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/dologin")
public String doLogin(HttpServletRequest request, Model model) {
String msg = "";
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println(userName);
System.out.println(password);
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
token.setRememberMe(true);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
if (subject.isAuthenticated()) {
return "redirect:/";
} else {
return "login";
}
} catch (IncorrectCredentialsException e) {
msg = "登錄密碼毛病. Password for account " + token.getPrincipal() + " was incorrect.";
model.addAttribute("message", msg);
System.out.println(msg);
} catch (ExcessiveAttemptsException e) {
msg = "登錄失敗次數(shù)過量";
model.addAttribute("message", msg);
System.out.println(msg);
} catch (LockedAccountException e) {
msg = "帳號已被鎖定. The account for username " + token.getPrincipal() + " was locked.";
model.addAttribute("message", msg);
System.out.println(msg);
} catch (DisabledAccountException e) {
msg = "帳號已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
model.addAttribute("message", msg);
System.out.println(msg);
} catch (ExpiredCredentialsException e) {
msg = "帳號已過期. the account for username " + token.getPrincipal() + " was expired.";
model.addAttribute("message", msg);
System.out.println(msg);
} catch (UnknownAccountException e) {
msg = "帳號不存在. There is no user with username of " + token.getPrincipal();
model.addAttribute("message", msg);
System.out.println(msg);
} catch (UnauthorizedException e) {
msg = "您沒有得到相應(yīng)的授權(quán)!" + e.getMessage();
model.addAttribute("message", msg);
System.out.println(msg);
}
return "login";
}
如果輸入不存在的用戶名或是毛病的密碼界面上會有相應(yīng)的提示信息。


登錄成功后,會轉(zhuǎn)至首頁,并顯示出當(dāng)前用戶名。

版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請注明出處。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈