一:配置文件
1:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>08shiro_ssm</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 配置字符编码过滤器 -->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean-->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2:spring.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/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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
<!-- 扫描类中注解 -->
<context:component-scan base-package="hhxy.**"></context:component-scan>
<!-- web.xml中shiro的filter对应的bean -->
<!-- Shiro 的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 -->
<property name="loginUrl" value="/login" />
<!-- 认证成功统一跳转到index.jsp,建议不配置,shiro认证成功自动到上一个请求路径 -->
<property name="successUrl" value="/index"/>
<!-- 通过unauthorizedUrl指定没有权限操作时跳转页面-->
<property name="unauthorizedUrl" value="/refuse" />
<!-- 过虑器链定义,从上向下顺序执行,一般将/**放在最下边 -->
<property name="filterChainDefinitions">
<value>
<!-- /** = authc 所有url都必须认证通过才可以访问-->
/login.jsp=anon
/toLogin=anon
/login=authc
/logout=logout
<!--权限注解作用一样 /find=perms[user:findAll] -->
/**=authc
<!-- /** = anon所有url都可以匿名访问 -->
</value>
</property>
</bean>
<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<property name="cacheManager" ref="cacheManager"/>
<property name="sessionManager" ref="sessionManager"/>
</bean>
<!-- 配置自定义realm -->
<bean id="userRealm" class="hhxy.realm.UserRealm">
<!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!-- 配置缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehCacheManager"/>
</bean>
<bean id="ehCacheManager" class ="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
<property name="shared" value="true"></property>
</bean>
<!-- 配置会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager">
<!-- 单位是毫秒 -->
<property name="globalSessionTimeout" value="300000"/>
<!-- 删除无效session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
<!-- 凭证匹配器 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<property name="hashIterations" value="2"/>
</bean>
<!-- 配置authc过滤器 -->
<bean id="authc" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
<property name="usernameParam" value="name"/>
<property name="passwordParam" value="pwd"/>
</bean>
<!-- 配置logout过滤器 -->
<bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/toLogin"/>
</bean>
<!-- 异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 认证异常 -->
<prop key="org.apache.shiro.authz.UnauthenticatedException">refuse</prop>
<!-- 授权异常 -->
<prop key="org.apache.shiro.authz.UnauthorizedException">refuse</prop>
</props>
</property>
</bean>
</beans>
3:springmvc.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:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<!-- 开启shiro注解模式 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
4:ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<diskStore path="java.io.tmpdir"/>
<!-- 设定缓存的默认数据过期策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
</ehcache>
二:视图
1:login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="login" method="post">
<p>功能测试,密码1111即可</p>
<p>用户名:<input name="name" type="text"/></p>
<p>密 码:<input name="pwd" type="password"></p>
<p><input name="登陆" value="登陆" type="submit"></p>
</form>
</body>
</html>
2:index.jsp
<%@page import="org.springframework.beans.factory.annotation.Autowired"%>
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<!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>Insert title here</title>
</head>
<body>
<p>登陆成功</p>
<p>
请测试权限:
<a href="find">测试</a>
</p>
<p>
请测试权限:
<a href="logout">退出</a>
</p>
<p>
<shiro:hasPermission name="user:add">
用户<shiro:principal />拥有user:add权限
</shiro:hasPermission>
</p>
<p>
<shiro:hasPermission name="user:delete">
用户<shiro:principal />拥有user:delete权限
</shiro:hasPermission>
</p>
<p>
<shiro:hasPermission name="user:update">
用户<shiro:principal />拥有user:update权限
</shiro:hasPermission>
</p>
<p>
<shiro:hasPermission name="user:find">
用户<shiro:principal />拥有user:find权限
</shiro:hasPermission>
</p>
<p>
<shiro:hasPermission name="user:create">
用户<shiro:principal />拥有user:create权限
</shiro:hasPermission>
</p>
<p>
<shiro:hasPermission name="user:alter">
用户<shiro:principal />拥有user:alter权限
</shiro:hasPermission>
</p>
</body>
</html>
3:refuse.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!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>Insert title here</title>
</head>
<body>
无权限
</body>
</html>
三:控制器
package controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@RequestMapping("login")
public String login(HttpServletRequest req,Model model){
String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
String error = null;
if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
error = "用户名/密码错误";
} else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
error = "用户名/密码错误";
} else if(exceptionClassName != null) {
error = "其他错误:" + exceptionClassName;
}
model.addAttribute("error", error);
System.out.println("认证失败-------------------------------------");
return "redirect:toLogin";
}
@RequestMapping("/find")
@RequiresPermissions("user:find")
public String find() {
System.out.println("授权通过-------------------------------------");
return "redirect:index";
}
@RequestMapping("/toLogin")
public ModelAndView toLogin() {
return new ModelAndView("login.jsp");
}
@RequestMapping("/index")
public ModelAndView index() {
return new ModelAndView("index.jsp");
}
@RequestMapping("/refuse")
public ModelAndView refuse() {
return new ModelAndView("refuse.jsp");
}
}
四:自定义Realm
package hhxy.realm;
import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.SecurityUtils;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
/**
* 自定义realm的实现,该realm提供了两个方法
* AuthorizationInfo 授权
* AuthenticationInfo 验证
* @author 李伟康
*
*/
public class UserRealm extends AuthorizingRealm{
@Override
public String getName() {
// TODO Auto-generated method stub
return "UserRealm";
}
//完成身份认证,并返回认证信息,如果验证失败返回null
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
//获取用户输入的用户名
System.out.println("认证--------------------------------");
String username=(String)token.getPrincipal();
System.out.println("username========"+username);
//根据用户名到数据库查询密码信息---模拟
//假定从数据库获取的密码为1111,盐为hhxy
String pwd="1111";
Md5Hash md5=new Md5Hash(pwd,"hhxy",2);
pwd=md5.toString();
String salt="hhxy";
//将盐的内容以二进制的形式传入
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,pwd,ByteSource.Util.bytes(salt),getName());
return info;
}
//授权的信息
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
String username=(String) principals.getPrimaryPrincipal();
System.out.println("授权--------------------------------");
System.out.println("username======"+username);
//模拟从数据库中查询该用户对应的权限信息
List<String> permission=new ArrayList<String>();
permission.add("user:add");
permission.add("user:delete");
permission.add("user:update");
permission.add("user:find");
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
for(String perms:permission) {
info.addStringPermission(perms);
}
return info;
}
//清理缓存
@Override
protected void clearCache(PrincipalCollection principals) {
// TODO Auto-generated method stub
Subject subject=SecurityUtils.getSubject();
super.clearCache(subject.getPrincipals());
}
}