Shiro學習--與SpringMVC整合(資料庫,Shiro註解和Shiro標籤)
關於Shiro的環境搭建和核心概念參考
通過Shiro官方給的Tutorial我們知道Shiro的操作都是基於Subject的,而Subject來自SecurityManager,如下
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
通過整合之道我們知道Spring和其他框架的整合就是將其他框架的核心概念通過一個bean交由Spring管理起來,而Shiro的核心概念就是SecurityManager,所以Spring對Shiro的整合就是對SecurityManager的整合。而與SpringMVC的整合是SpringMVC攔截請求的時候還要交給Shiro進行攔截。
先來看一下結果,有個感性的認識,再看細節,直接上圖。
沒有登入跳轉到登入頁面,登入後進入剛才輸入的頁面
不同許可權看到的頁面
讓我們仔細看一下實現細節。
資料庫結構
參考
總共有五張表,
使用者表,儲存使用者的相關資訊
角色表,儲存角色的相關資訊
許可權表,儲存許可權的相關資訊
使用者角色表,儲存使用者和角色的對應關係 一對多
角色許可權表,儲存角色和許可權的對應關係 一對對
關係如下
資料庫指令碼
資料庫名稱為shiro_test
/*
Navicat MySQL Data Transfer
Source Server : 本地連線
Source Server Version : 50620
Source Host : localhost:3306
Source Database : shiro_test
Target Server Type : MYSQL
Target Server Version : 50620
File Encoding : 65001
Date: 2016-03-09 16:50:54
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for sec_permission
-- ----------------------------
DROP TABLE IF EXISTS `sec_permission`;
CREATE TABLE `sec_permission` (
`permission_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`permission_name` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`permission_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for sec_role
-- ----------------------------
DROP TABLE IF EXISTS `sec_role`;
CREATE TABLE `sec_role` (
`role_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`role_name` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for sec_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sec_role_permission`;
CREATE TABLE `sec_role_permission` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`permission_id` int(10) unsigned NOT NULL,
`role_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `permission_id外來鍵` (`permission_id`),
KEY `role_id外來鍵1` (`role_id`),
CONSTRAINT `permission_id外來鍵` FOREIGN KEY (`permission_id`) REFERENCES `sec_permission` (`permission_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `role_id外來鍵1` FOREIGN KEY (`role_id`) REFERENCES `sec_role` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for sec_user
-- ----------------------------
DROP TABLE IF EXISTS `sec_user`;
CREATE TABLE `sec_user` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`password` varchar(128) COLLATE utf8_bin DEFAULT NULL,
`created_time` datetime DEFAULT NULL,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for sec_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sec_user_role`;
CREATE TABLE `sec_user_role` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned DEFAULT NULL,
`role_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id外來鍵` (`user_id`),
KEY `role_id外來鍵` (`role_id`),
CONSTRAINT `role_id外來鍵` FOREIGN KEY (`role_id`) REFERENCES `sec_role` (`role_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `user_id外來鍵` FOREIGN KEY (`user_id`) REFERENCES `sec_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
初始資料
使用者表sec_user
INSERT INTO `sec_user` VALUES ('1', 'jacky', '9661FD65249B026EBEA0F49927E82F0E', '2016-03-08 16:37:59', '2016-03-08 16:38:06');
INSERT INTO `sec_user` VALUES ('2', 'cheng', '89975C5E5D407916E8080D137C48DDD7', '2016-03-09 15:09:35', '2016-03-09 15:10:16');
使用者jacky密碼jacky
使用者cheng密碼cheng
角色表sec_role
INSERT INTO `sec_role` VALUES ('1', 'admin', '2016-03-09 11:58:12', '2016-03-09 11:58:16');
INSERT INTO `sec_role` VALUES ('2', 'user', '2016-03-09 15:09:04', '2016-03-09 15:09:08');
兩種角色admin和user
許可權表sec_permission
INSERT INTO `sec_permission` VALUES ('1', 'user:create', '2016-03-09 15:42:07', '2016-03-09 15:42:10');
INSERT INTO `sec_permission` VALUES ('2', 'user:view', '2016-03-09 15:43:35', '2016-03-09 15:43:39');
兩種許可權,建立使用者user:create和檢視使用者user:view
情景
使用者jacky屬於admin組,admin擁有建立使用者user:create和檢視使用者user:view許可權
使用者cheng輸入user組,user組擁有檢視使用者user:view許可權
使用者角色表sec_user_role
INSERT INTO `sec_user_role` VALUES ('1', '1', '1');
INSERT INTO `sec_user_role` VALUES ('2', '2', '2');
角色許可權表sec_role_permission
INSERT INTO `sec_role_permission` VALUES ('1', '1', '1');
INSERT INTO `sec_role_permission` VALUES ('2', '2', '1');
INSERT INTO `sec_role_permission` VALUES ('3', '2', '2');
與Spring整合
首先需要一個SpringMVC,參考
整合參考
首先在web.xml中定義shiro的過濾器
配置web.xml
web.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>
<!-- shiro的filter-mapping-->
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
完整的web.xml
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- spring核心的位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-core.xml</param-value>
</context-param>
<!-- 統一編碼filter -->
<filter>
<filter-name>charsetEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- 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-mapping>
<filter-name>charsetEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- shiro的filter-mapping-->
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 此監聽器出用於主要為了解決java.beans.Introspector導致記憶體洩漏的問題. This listener should
be registered as the first one in web.xml, before any application listeners
such as Spring's ContextLoaderListener. -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 載入spring核心的listener-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc前端控制器配置 -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置Bean
其次在Spring的配置檔案中定義各種bean
這裡新建一個Spring配置檔案spring-shiro.xml
結構如下
在web.xml中載入spring的時候會載入springmvc的xml,spring-mvc.xml
和spring的核心配置檔案spring-core.xml
再由spring負責載入其他配置檔案
關於快取和hibernate請參考以下文章
接下來看一下spring-shiro的詳細配置
spring-shiro.xml
<?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-4.2.xsd">
<!-- 匯入資料庫的相關配置 -->
<import resource="classpath:spring/spring-hibernate.xml"/>
<!-- 對應於web.xml中配置的那個shiroFilter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全介面,這個屬性是必須的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登入時的連結(登入頁面地址),非必須的屬性,預設會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
<property name="loginUrl" value="/login.html"/>
<!-- 登入成功後要跳轉的連線(本例中此屬性用不到,因為登入成功後的處理邏輯在LoginController裡硬編碼) -->
<!-- <property name="successUrl" value="/" ></property> -->
<!-- 使用者訪問未對其授權的資源時,所顯示的連線 -->
<property name="unauthorizedUrl" value="/error/unauthorized"/>
<property name="filterChainDefinitions">
<value>
/admin/**=authc
</value>
</property>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
<!-- 資料庫儲存的密碼是使用MD5演算法加密的,所以這裡需要配置一個密碼匹配物件 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>
<!-- 快取管理 -->
<bean id="shiroCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>
<!--
使用Shiro自帶的JdbcRealm類
指定密碼匹配所需要用到的加密物件
指定儲存使用者、角色、許可權許可的資料來源及相關查詢語句
-->
<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="shiroCacheManager"></property>
</bean>
<!-- Shiro的註解配置一定要放在spring-mvc中 -->
</beans>
為了開啟Shiro註解,必須在spring-mvc.xml中配置,在其他配置檔案中不生效
spring-mvc.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 匯入shiro的相關配置 -->
<import resource="classpath:spring/spring-shiro.xml" />
<!-- 配置掃描路徑 -->
<context:component-scan base-package="com.gwc.shirotest.controller" />
<!-- 配置根檢視 -->
<mvc:view-controller path="/" view-name="index"/>
<!-- 開啟@MatrixVariable註解 -->
<mvc:annotation-driven enable-matrix-variables="true">
</mvc:annotation-driven>
<!-- 啟用基於註解的配置 @RequestMapping, @ExceptionHandler,資料繫結 ,@NumberFormat ,
@DateTimeFormat ,@Controller ,@Valid ,@RequestBody ,@ResponseBody等 -->
<!-- <mvc:annotation-driven /> -->
<!-- 圖片,css,js等靜態資源配置 -->
<mvc:resources location="/assets/" mapping="/assets/**"/>
<!-- jsp檢視層配置 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 檔案上傳的bean 10*1024*1024 10M -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="10485760"
p:resolveLazily="true"/>
<!-- 開啟shiro註解-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
最後兩個bean就是配置啟用shiro註解的bean,和官方文件中有點不一樣
<property name="proxyTargetClass" value="true" />
如果不配置這個,註解也是開不了的
開發Controller
登入相關
ShiroController.java
package com.gwc.shirotest.controller;
import com.gwc.shirotest.entity.User;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
/**
* Created by GWCheng on 2016/3/8.
*/
@Controller
public class ShiroController {
private static final Logger logger = Logger.getLogger(ShiroController.class);
@RequestMapping(value="/login.html",method=RequestMethod.GET)
public String login(){
logger.info("======使用者進入了ShiroController的/login.html");
return "login";
}
@RequestMapping(value = "/logout.html")
public String doLogout(HttpServletRequest request, Model model) {
logger.info("======使用者"+request.getSession().getAttribute("user")+"退出了系統");
SecurityUtils.getSubject().logout();
return "redirect:login.html";
}
@RequestMapping(value="/doLogin.html",method=RequestMethod.POST)
public String doLogin(User user,HttpServletRequest request, Model model){
logger.info("======使用者進入了ShiroController的/doLogin.html");
String msg ;
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
token.setRememberMe(true);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
if (subject.isAuthenticated()) {
request.getSession().setAttribute("user",user);
SavedRequest savedRequest = WebUtils.getSavedRequest(request);
// 獲取儲存的URL
if (savedRequest == null || savedRequest.getRequestUrl() == null) {
return "admin/home";
} else {
//String url = savedRequest.getRequestUrl().substring(12, savedRequest.getRequestUrl().length());
return "forward:" + savedRequest.getRequestUrl();
}
} 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 = "登入失敗次數過多";
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 = "您沒有得到相應的授權!" + e.getMessage();
model.addAttribute("message", msg);
System.out.println(msg);
}
return "login";
}
}
許可權相關
AdminController.java
package com.gwc.shirotest.controller;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by GWCheng on 2016/3/8.
*/
@Controller
public class AdminController {
// 登入成功的頁面
@RequestMapping(value = "/admin/home")
public String adminHomePage(){
return "admin/home";
}
// 只有角色為admin的才能訪問
@RequiresRoles("admin")
@RequestMapping(value = "/admin/role")
public String adminWithRole(){
return "admin/withrole";
}
// 只用同時具有user:view和user:create許可權才能訪問
@RequiresPermissions(value={"user:view","user:create"}, logical= Logical.AND)
@RequestMapping(value = "/admin/auth")
public String adminWithAuth(){
return "admin/withauth";
}
}
開發頁面
結構
登入頁面
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false" %>
<!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-8">
<title>hello</title>
<c:catch var="importError0">
<c:import url="common/base.jsp" charEncoding="utf-8"></c:import>
</c:catch>
<c:out value="${importError0}"></c:out>
</head>
<body>
<h1>login page</h1>
<form action="<c:url value='/doLogin.html'/>" 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>
<%--用於輸入後臺返回的驗證錯誤資訊 --%>
<P>${message }</P>
</body>
</html>
登入成功的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page isELIgnored="false" %>
<!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-8">
<title>hello</title>
<c:catch var="importError0">
<c:import url="../common/base.jsp" charEncoding="utf-8"></c:import>
</c:catch>
<c:out value="${importError0}"></c:out>
</head>
<body>
歡迎${user.username}登入
<a href="<c:url value='/logout.html'/>"><button>退出登入</button></a>
</body>
</html>
有角色才能訪問的頁面