1.許可權的簡單描述 2.實例表結構及內容及POJO 3.Shiro-pom.xml 4.Shiro-web.xml 5.Shiro-MyShiro-許可權認證,登錄認證層 6.Shiro-applicationContext-shiro.xml 7.HomeController三個JSP文件 1.許可權 ...
1.許可權的簡單描述 2.實例表結構及內容及POJO 3.Shiro-pom.xml 4.Shiro-web.xml 5.Shiro-MyShiro-許可權認證,登錄認證層 6.Shiro-applicationContext-shiro.xml 7.HomeController三個JSP文件
什麼是許可權呢?舉個簡單的例子:
我有一個論壇,註冊的用戶分為normal用戶,manager用戶。
對論壇的帖子的操作有這些:
添加,刪除,更新,查看,回覆
我們規定:
normal用戶只能:添加,查看,回覆
manager用戶可以:刪除,更新
normal,manager對應的是角色(role)
添加,刪除,更新等對應的是許可權(permission)
我們採用下麵的邏輯創建許可權表結構(不是絕對的,根據需要修改)
一個用戶可以有多種角色(normal,manager,admin等等)
一個角色可以有多個用戶(user1,user2,user3等等)
一個角色可以有多個許可權(save,update,delete,query等等)
一個許可權只屬於一個角色(delete只屬於manager角色)
我們創建四張表:
t_user用戶表:設置了3個用戶
-------------------------------
id + username + password
---+----------------+----------
1 + tom + 000000
2 + jack + 000000
3 + rose + 000000
---------------------------------
t_role角色表:設置3個角色
--------------
id + rolename
---+----------
1 + admin
2 + manager
3 + normal
--------------
t_user_role用戶角色表:tom是admin和normal角色,jack是manager和normal角色,rose是normal角色
---------------------
user_id + role_id
-----------+-----------
1 + 1
1 + 3
2 + 2
2 + 3
3 + 3
---------------------
t_permission許可權表:admin角色可以刪除,manager角色可以添加和更新,normal角色可以查看
-----------------------------------
id + permissionname + role_id
----+------------------------+-----------
1 + add + 2
2 + del + 1
3 + update + 2
4 + query + 3
-----------------------------------
使用SHIRO的步驟:
1,導入jar
2,配置web.xml
3,建立dbRelm
4,在Spring中配置
pom.xml中配置如下:
![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.hyx</groupId>
- <artifactId>springmvc</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>springmvc Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <!-- SpringMVC核心jar -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <!-- springmvc連接資料庫需要的jar -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-orm</artifactId>
- <version>3.2.4.RELEASE</version>
- </dependency>
- <!-- ************************************ -->
- <!-- Hibernate相關jar -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>4.2.5.Final</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-ehcache</artifactId>
- <version>4.2.5.Final</version>
- </dependency>
- <dependency>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache</artifactId>
- <version>2.7.2</version>
- </dependency>
- <dependency>
- <groupId>commons-dbcp</groupId>
- <artifactId>commons-dbcp</artifactId>
- <version>1.4</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.26</version>
- </dependency>
- <!-- javax提供的annotation -->
- <dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <version>1</version>
- </dependency>
- <!-- **************************** -->
- <!-- hibernate驗證 -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>5.0.1.Final</version>
- </dependency>
- <!-- 用於對@ResponseBody註解的支持 -->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.13</version>
- </dependency>
- <!-- 提供對c標簽的支持 -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <!-- servlet api -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- </dependency>
- <!--Apache Shiro所需的jar包-->
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-web</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-spring</artifactId>
- <version>1.2.2</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>springmvc</finalName>
- <!-- maven的jetty伺服器插件 -->
- <plugins>
- <plugin>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-maven-plugin</artifactId>
- <configuration>
- <scanIntervalSeconds>10</scanIntervalSeconds>
- <webApp>
- <contextPath>/</contextPath>
- </webApp>
- <!-- 修改jetty的預設埠 -->
- <connectors>
- <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
- <port>80</port>
- <maxIdleTime>60000</maxIdleTime>
- </connector>
- </connectors>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
web.xml中的配置:
Xml代碼![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <?xml version="1.0" encoding="UTF-8" ?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name>Archetype Created Web Application</display-name>
- <!-- spring-orm-hibernate4的OpenSessionInViewFilter -->
- <filter>
- <filter-name>opensessioninview</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>opensessioninview</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 配置springmvc servlet -->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <!-- / 表示所有的請求都要經過此serlvet -->
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <!-- spring的監聽器 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
- <!-- Shiro配置 -->
- <filter>
- <filter-name>shiroFilter</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>shiroFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
Java代碼
![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- package com.cn.service;
- import java.util.List;
- import javax.inject.Inject;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.SimpleAuthenticationInfo;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import com.cn.pojo.Role;
- import com.cn.pojo.User;
- @Service
- @Transactional
- public class MyShiro extends AuthorizingRealm{
- @Inject
- private UserService userService;
- /**
- * 許可權認證
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- //獲取登錄時輸入的用戶名
- String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();
- //到資料庫查是否有此對象
- User user=userService.findByName(loginName);
- if(user!=null){
- //許可權信息對象info,用來存放查出的用戶的所有的角色(role)及許可權(permission)
- SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
- //用戶的角色集合
- info.setRoles(user.getRolesName());
- //用戶的角色對應的所有許可權,如果只使用角色定義訪問許可權,下麵的四行可以不要
- List<Role> roleList=user.getRoleList();
- for (Role role : roleList) {
- info.addStringPermissions(role.getPermissionsName());
- }
- return info;
- }
- return null;
- }
- /**
- * 登錄認證;
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(
- AuthenticationToken authenticationToken) throws AuthenticationException {
- //UsernamePasswordToken對象用來存放提交的登錄信息
- UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
- //查出是否有此用戶
- User user=userService.findByName(token.getUsername());
- if(user!=null){
- //若存在,將此用戶存放到登錄認證info中
- return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
- }
- return null;
- }
- }
在spring的配置文件中配置,為了區別spring原配置和shiro我們將shiro的配置獨立出來。
applicationContext-shiro.xml
Xml代碼![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
- <!-- 配置許可權管理器 -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <!-- ref對應我們寫的realm MyShiro -->
- <property name="realm" ref="myShiro"/>
- <!-- 使用下麵配置的緩存管理器 -->
- <property name="cacheManager" ref="cacheManager"/>
- </bean>
- <!-- 配置shiro的過濾器工廠類,id- shiroFilter要和我們在web.xml中配置的過濾器一致 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <!-- 調用我們配置的許可權管理器 -->
- <property name="securityManager" ref="securityManager"/>
- <!-- 配置我們的登錄請求地址 -->
- <property name="loginUrl" value="/login"/>
- <!-- 配置我們在登錄頁登錄成功後的跳轉地址,如果你訪問的是非/login地址,則跳到您訪問的地址 -->
- <property name="successUrl" value="/user"/>
- <!-- 如果您請求的資源不再您的許可權範圍,則跳轉到/403請求地址 -->
- <property name="unauthorizedUrl" value="/403"/>
- <!-- 許可權配置 -->
- <property name="filterChainDefinitions">
- <value>
- <!-- anon表示此地址不需要任何許可權即可訪問 -->
- /static/**=anon
- <!-- perms[user:query]表示訪問此連接需要許可權為user:query的用戶 -->
- /user=perms[user:query]
- <!-- roles[manager]表示訪問此連接需要用戶的角色為manager -->
- /user/add=roles[manager]
- /user/del/**=roles[admin]
- /user/edit/**=roles[manager]
- <!--所有的請求(除去配置的靜態資源請求或請求地址為anon的請求)都要通過登錄驗證,如果未登錄則跳到/login-->
- /** = authc
- </value>
- </property>
- </bean>
- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
- </beans>
用於登錄,登出,許可權跳轉的控制:
Java代碼![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- package com.cn.controller;
- import javax.validation.Valid;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.validation.BindingResult;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- import com.cn.pojo.User;
- @Controller
- public class HomeController {
- @RequestMapping(value="/login",method=RequestMethod.GET)
- public String loginForm(Model model){
- model.addAttribute("user", new User());
- return "/login";
- }
- @RequestMapping(value="/login",method=RequestMethod.POST)
- public String login(@Valid User user,BindingResult bindingResult,RedirectAttributes redirectAttributes){
- try {
- if(bindingResult.hasErrors()){
- return "/login";
- }
- //使用許可權工具進行用戶登錄,登錄成功後跳到shiro配置的successUrl中,與下麵的return沒什麼關係!
- SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
- return "redirect:/user";
- } catch (AuthenticationException e) {
- redirectAttributes.addFlashAttribute("message","用戶名或密碼錯誤");
- return "redirect:/login";
- }
- }
- @RequestMapping(value="/logout",method=RequestMethod.GET)
- public String logout(RedirectAttributes redirectAttributes ){
- //使用許可權管理工具進行用戶的退出,跳出登錄,給出提示信息
- SecurityUtils.getSubject().logout();
- redirectAttributes.addFlashAttribute("message", "您已安全退出");
- return "redirect:/login";
- }
- @RequestMapping("/403")
- public String unauthorizedRole(){
- return "/403";
- }
- }
三個主要的JSP:
login.jsp:
![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'MyJsp.jsp' starting page</title>
- </head>
- <body>
- <h1>登錄頁面----${message }</h1>
- <img alt="" src="/static/img/1.jpg">
- <form:form action="/login" commandName="user" method="post">
- 用戶名:<form:input path="username"/> <form:errors path="username" cssClass="error"/> <br/>
- 密 碼:<form:password path="password"/> <form:errors path="password" cssClass="error" /> <br/>
- <form:button name="button">submit</form:button>
- </form:form>
- </body>
- </html>
user.jsp:
Html代碼![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>用戶列表</title>
- </head>
- <body>
- <h1>${message }</h1>
- <h1>用戶列表--<a href="/user/add">添加用戶</a>---<a href="/logout">退出登錄</a> </h1>
- <h2>許可權列表</h2>
- <shiro:authenticated>用戶已經登錄顯示此內容</shiro:authenticated>
- <shiro:hasRole name="manager">manager角色登錄顯示此內容</shiro:hasRole>
- <shiro:hasRole name="admin">admin角色登錄顯示此內容</shiro:hasRole>
- <shiro:hasRole name="normal">normal角色登錄顯示此內容</shiro:hasRole>
- <shiro:hasAnyRoles name="manager,admin">**manager or admin 角色用戶登錄顯示此內容**</shiro:hasAnyRoles>
- <shiro:principal/>-顯示當前登錄用戶名
- <shiro:hasPermission name="add">add許可權用戶顯示此內容</shiro:hasPermission>
- <shiro:hasPermission name="user:query">query許可權用戶顯示此內容<shiro:principal/></shiro:hasPermission>
- <shiro:lacksPermission name="user:del"> 不具有user:del許可權的用戶顯示此內容 </shiro:lacksPermission>
- <ul>
- <c:forEach items="${userList }" var="user">
- <li>用戶名:${user.username }----密碼:${user.password }----<a href="/user/edit/${user.id}">修改用戶</a>----<a href="javascript:;" class="del" ref="${user.id }">刪除用戶</a></li>
- </c:forEach>
- </ul>
- <img alt="" src="/static/img/1.jpg">
- <script type="text/javascript" src="http://cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script>
- <script>
- $(function(){
- $(".del").click(function(){
- var id=$(this).attr("ref");
- $.ajax({
- type:"delete",
- url:"/user/del/"+id,
- success:function(e){
- }
- });
- });
- });
- </script>
- </body>
- </html>
403.jsp:
Html代碼![收藏代碼](http://hunthon.iteye.com/images/icon_star.png)
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>許可權錯誤</title>
- </head>
- <body>
- <h1>對不起,您沒有許可權請求此連接!</h1>
- <img alt="" src="/static/img/1.jpg">
- </body>
- </html>
-
框架/平臺構成:
Maven+Springmvc + Mybatis + Shiro(許可權)+ Tiles(模板) +ActiveMQ(消息隊列) + Rest(服務) + WebService(服務)+ EHcache(緩存) + Quartz(定時調度)+ Html5(支持PC、IOS、Android)用戶許可權系統:
組織結構:角色、用戶、用戶組、組織機構;許可權點:頁面、方法、按鈕、數據許可權、分級授權
項目管理新體驗:
快速出原型系統、組件樹、版本控制、模塊移植、協同開發、實時監控、發佈管理
可持續集成:
所有組件可移植、可定製、可擴充,開發成果不斷積累,形成可持續發展的良性迴圈
支持平臺平臺:
Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix
伺服器容器:
Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5