【Shiro】SpringMVC+Shiro权限管理
2017-04-03 11:01
155 查看
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中配置如下:
Xml代码
<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代码
<?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代码
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代码
<?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代码
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:
Html代码
<%@ 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代码
<%@ 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代码
<%@ 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>
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中配置如下:
Xml代码
<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代码
<?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代码
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代码
<?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代码
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:
Html代码
<%@ 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代码
<%@ 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代码
<%@ 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>
相关文章推荐
- Shiro 项目开发中第一次使用到,所以研究了一下,这里
- java鬼混笔记:shiro 7、shiro验证码功能
- shiro:简单实例
- shiro框架实战讲解
- Shiro 学习笔记(6)—— 加密
- SpringMVC + Spring + Mybatis+ Redis +shiro以及MyBatis学习
- Spring Boot系列(十五) 安全框架Apache Shiro(二)缓存-基于Hazelcast的分布式缓存
- shiro在springmvc里面的集成使用【转】
- SSM + Shiro 整合 (6)- Shiro 集成 Spring
- 简单扩展shiro 实现NOT、AND、OR权限验证(支持复杂一点的表达式)
- Apache Shiro和Spring Security的详细对比
- 关于shiro权限框架简单快速入门
- shiro自学
- SpringMVC + Mybatis + Shiro 权限整合【转】
- SpringMVC + Mybatis + Shiro 权限整合【转】
- ShiroFilterFactoryBean源码及阻截原理深入分析
- shiro+springmvc+mybatis【转】
- springmvc+spring+mybatis+maven项目集成shiro进行用户权限控制【转】
- 简单权限系统基于shiro-springmvc-spring-mybatis(学习笔记2)
- eclipse 导入 ssm项目shiro quartz 启动报java.lang.NoClassDefFoundError: org/quartz/SchedulerException