Jar包
1 com.springsource.net.sf.cglib-2.2.0.jar 2 com.springsource.org.aopalliance-1.0.0.jar 3 com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar 4 commons-logging-1.1.3.jar 5 ehcache-core-2.4.3.jar 6 jackson-all-1.9.11.jar 7 log4j-1.2.15.jar 8 shiro-all-1.3.2.jar 9 slf4j-api-1.6.1.jar 10 slf4j-log4j12-1.6.1.jar 11 spring-aop-4.0.0.RELEASE.jar 12 spring-aspects-4.0.0.RELEASE.jar 13 spring-beans-4.0.0.RELEASE.jar 14 spring-context-4.0.0.RELEASE.jar 15 spring-context-support-4.0.0.RELEASE.jar 16 spring-core-4.0.0.RELEASE.jar 17 spring-expression-4.0.0.RELEASE.jar 18 spring-jdbc-4.0.0.RELEASE.jar 19 spring-orm-4.0.0.RELEASE.jar 20 spring-tx-4.0.0.RELEASE.jar 21 spring-web-4.0.0.RELEASE.jar 22 spring-webmvc-4.0.0.RELEASE.jar
web.xml配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <!-- Spring --> 7 <context-param> 8 <param-name>contextConfigLocation</param-name> 9 <param-value>classpath:applicationContext.xml</param-value> 10 </context-param> 11 12 <listener> 13 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 14 </listener> 15 16 <!-- SpringMVC --> 17 <servlet> 18 <servlet-name>spring</servlet-name> 19 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 20 <load-on-startup>1</load-on-startup> 21 </servlet> 22 <servlet-mapping> 23 <servlet-name>spring</servlet-name> 24 <url-pattern>/</url-pattern> 25 </servlet-mapping> 26 27 <!-- 28 1. 配置 Shiro 的 shiroFilter. 29 2. DelegatingFilterProxy 实际上是 Filter 的一个代理对象. 默认情况下, Spring 会到 IOC 容器中查找和 30 <filter-name> 对应的 filter bean. 也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id. 31 --> 32 <filter> 33 <filter-name>shiroFilter</filter-name> 34 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 35 <init-param> 36 <param-name>targetFilterLifecycle</param-name> 37 <param-value>true</param-value> 38 </init-param> 39 </filter> 40 41 <filter-mapping> 42 <filter-name>shiroFilter</filter-name> 43 <url-pattern>/*</url-pattern> 44 </filter-mapping> 45 46 47 </web-app>
SpringMVC配置文件
spring-servlet.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 <!-- 自动扫描 --> 11 <context:component-scan base-package="com.shiro"></context:component-scan> 12 <!-- 前后缀 --> 13 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 14 <property name="prefix" value="/"></property> 15 <property name="suffix" value=".jsp"></property> 16 </bean> 17 <!-- 注解 --> 18 <mvc:annotation-driven></mvc:annotation-driven> 19 <mvc:default-servlet-handler/> 20 21 </beans>
Spring配置文件
applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 11 12 <!-- 1. 配置 SecurityManager --> 13 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 14 <property name="cacheManager" ref="cacheManager" /> 15 <property name="authenticator" ref="authenticator" /> 16 <property name="realms"> 17 <list> 18 <ref bean="jdbcRealm"/> 19 <ref bean="secondRealm"/> 20 </list> 21 </property> 22 </bean> 23 <!-- 2.配置cacheManager 2.1需要加入ehcache.xml的jar包以及配置文件 --> 24 <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 25 <property name="cacheManagerConfigFile" value="classpath:ehcache.xml" /> 26 </bean> 27 28 <bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator"> 29 <property name="authenticationStrategy"> 30 <!-- 有一个通过即可 --> 31 <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/> 32 </property> 33 </bean> 34 35 <!-- 3.配置Realm 3.1直接配置实现了org.apache.shiro.realm.Realm接口的bean --> 36 <bean id="jdbcRealm" class="com.shiro.realms.ShiroRealm"> 37 <property name="credentialsMatcher"> 38 <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> 39 <property name="hashAlgorithmName" value="MD5"></property> 40 <!--指定加密次数 --> 41 <property name="hashIterations" value="1024"></property> 42 </bean> 43 </property> 44 </bean> 45 46 <bean id="secondRealm" class="com.shiro.realms.SecondShiroRealms"> 47 <property name="credentialsMatcher"> 48 <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> 49 <property name="hashAlgorithmName" value="SHA1"></property> 50 <!--指定加密次数 --> 51 <property name="hashIterations" value="1024"></property> 52 </bean> 53 </property> 54 </bean> 55 56 <!-- 4.配置 LifecycleBeanPostProcessor. 可以自定的来调用配置在 Spring IOC 容器中 shiro bean 57 的生命周期方法. --> 58 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> 59 60 <!-- 5. 启用 IOC 容器中使用 shiro 的注解. 但必须在配置了 LifecycleBeanPostProcessor 之后才可以使用. --> 61 <bean 62 class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" 63 depends-on="lifecycleBeanPostProcessor" /> 64 65 <bean 66 class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> 67 <property name="securityManager" ref="securityManager" /> 68 </bean> 69 70 <!-- 6. 配置 ShiroFilter. 71 6.1 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy的<filter-name> 一致. 若不一致, 则会抛出: NoSuchBeanDefinitionException. 72 因为 Shiro 会来IOC 容器中查找和 <filter-name> 名字对应的 filter bean. --> 73 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 74 <property name="securityManager" ref="securityManager" /> 75 <property name="loginUrl" value="/login.jsp" /> 76 <property name="successUrl" value="/list.jsp" /> 77 <property name="unauthorizedUrl" value="/unauthorized.jsp" /> 78 79 <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property> 80 81 <!-- 配置哪些页面需要受保护. 以及访问这些页面需要的权限. 82 1). anon 可以被匿名访问 83 2). authc 必须认证(即登录)后才可能访问的页面. 84 3). logout 登出. 85 4). roles 角色过滤器 86 --> 87 <!-- <property name="filterChainDefinitions"> --> 88 <!-- <value> --> 89 <!-- /login.jsp = anon --> 90 <!-- /shiro/login = anon --> 91 <!-- /user.jsp = roles[user] --> 92 <!-- /admin.jsp = roles[admin] --> 93 <!-- # everything else requires authentication: --> 94 <!-- /** = authc --> 95 <!-- </value> --> 96 <!-- </property> --> 97 </bean> 98 <!-- 配置一个 bean, 该 bean 实际上是一个 Map. 通过实例工厂方法的方式 --> 99 <bean id="filterChainDefinitionMap" factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefinitionMap"></bean> 100 101 <bean id="filterChainDefinitionMapBuilder" class="com.shiro.factory.FilterChainDefinitionMapBuilder"></bean> 102 103 <bean id="shiroServiceTest" class="com.shiro.service.ShiroServiceTest"></bean> 104 </beans>
缓存配置文件
ehcache.xml
1 <ehcache> 2 3 <!-- Sets the path to the directory where cache .data files are created. 4 5 If the path is a Java System Property it is replaced by 6 its value in the running VM. 7 8 The following properties are translated: 9 user.home - User's home directory 10 user.dir - User's current working directory 11 java.io.tmpdir - Default temp file path --> 12 <diskStore path="java.io.tmpdir"/> 13 14 <cache name="authorizationCache" 15 eternal="false" 16 timeToIdleSeconds="3600" 17 timeToLiveSeconds="0" 18 overflowToDisk="false" 19 statistics="true"> 20 </cache> 21 22 <cache name="authenticationCache" 23 eternal="false" 24 timeToIdleSeconds="3600" 25 timeToLiveSeconds="0" 26 overflowToDisk="false" 27 statistics="true"> 28 </cache> 29 30 <cache name="shiro-activeSessionCache" 31 eternal="false" 32 timeToIdleSeconds="3600" 33 timeToLiveSeconds="0" 34 overflowToDisk="false" 35 statistics="true"> 36 </cache> 37 38 <!--Default Cache configuration. These will applied to caches programmatically created through 39 the CacheManager. 40 41 The following attributes are required for defaultCache: 42 43 maxInMemory - Sets the maximum number of objects that will be created in memory 44 eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element 45 is never expired. 46 timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used 47 if the element is not eternal. Idle time is now - last accessed time 48 timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used 49 if the element is not eternal. TTL is now - creation time 50 overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache 51 has reached the maxInMemory limit. 52 53 --> 54 <defaultCache 55 maxElementsInMemory="10000" 56 eternal="false" 57 timeToIdleSeconds="120" 58 timeToLiveSeconds="120" 59 overflowToDisk="true" 60 /> 61 62 <!--Predefined caches. Add your cache configuration settings here. 63 If you do not have a configuration for your cache a WARNING will be issued when the 64 CacheManager starts 65 66 The following attributes are required for defaultCache: 67 68 name - Sets the name of the cache. This is used to identify the cache. It must be unique. 69 maxInMemory - Sets the maximum number of objects that will be created in memory 70 eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element 71 is never expired. 72 timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used 73 if the element is not eternal. Idle time is now - last accessed time 74 timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used 75 if the element is not eternal. TTL is now - creation time 76 overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache 77 has reached the maxInMemory limit. 78 79 --> 80 81 <!-- Sample cache named sampleCache1 82 This cache contains a maximum in memory of 10000 elements, and will expire 83 an element if it is idle for more than 5 minutes and lives for more than 84 10 minutes. 85 86 If there are more than 10000 elements it will overflow to the 87 disk cache, which in this configuration will go to wherever java.io.tmp is 88 defined on your system. On a standard Linux system this will be /tmp" 89 --> 90 <cache name="sampleCache1" 91 maxElementsInMemory="10000" 92 eternal="false" 93 timeToIdleSeconds="300" 94 timeToLiveSeconds="600" 95 overflowToDisk="true" 96 /> 97 98 <!-- Sample cache named sampleCache2 99 This cache contains 1000 elements. Elements will always be held in memory. 100 They are not expired. --> 101 <cache name="sampleCache2" 102 maxElementsInMemory="1000" 103 eternal="true" 104 timeToIdleSeconds="0" 105 timeToLiveSeconds="0" 106 overflowToDisk="false" 107 /> --> 108 109 <!-- Place configuration for your caches following --> 110 111 </ehcache>
登录授权
ShiroRealm.java
1 package com.shiro.realms; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import org.apache.shiro.authc.AuthenticationException; 7 import org.apache.shiro.authc.AuthenticationInfo; 8 import org.apache.shiro.authc.AuthenticationToken; 9 import org.apache.shiro.authc.LockedAccountException; 10 import org.apache.shiro.authc.SimpleAuthenticationInfo; 11 import org.apache.shiro.authc.UnknownAccountException; 12 import org.apache.shiro.authc.UsernamePasswordToken; 13 import org.apache.shiro.authz.AuthorizationInfo; 14 import org.apache.shiro.authz.SimpleAuthorizationInfo; 15 import org.apache.shiro.crypto.hash.SimpleHash; 16 import org.apache.shiro.realm.AuthorizingRealm; 17 import org.apache.shiro.subject.PrincipalCollection; 18 import org.apache.shiro.util.ByteSource; 19 20 public class ShiroRealm extends AuthorizingRealm{ 21 22 // 实现登录 23 @Override 24 protected AuthenticationInfo doGetAuthenticationInfo( 25 AuthenticationToken token) throws AuthenticationException { 26 System.out.println("First ---> doGetAuthenticationInfo--->"+token); 27 //1. 把 AuthenticationToken 转换为 UsernamePasswordToken 28 UsernamePasswordToken upToken = (UsernamePasswordToken) token; 29 30 //2. 从 UsernamePasswordToken 中来获取 username 31 String username = upToken.getUsername(); 32 33 //3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录 34 System.out.println("First --->从数据库中获取 username: " + username + " 所对应的用户信息."); 35 36 //4. 若用户不存在, 则可以抛出 UnknownAccountException 异常 37 if("unknow".equals(username)){ 38 throw new UnknownAccountException("账户不存在"); 39 } 40 41 //5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常. 42 if("monster".equals(username)){ 43 throw new LockedAccountException("账户被锁定"); 44 } 45 46 //6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo 47 //以下信息是从数据库中获取的. 48 //1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. 49 Object principal = username; 50 51 //2). credentials: 密码. 52 String credentials = null; 53 if("admin".equals(username)){ 54 credentials = "038bdaf98f2037b31f1e75b5b4c9b26e"; 55 }else if("user".equals(username)){ 56 credentials = "098d2c478e9c11555ce2823231e02ec1"; 57 } 58 59 //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可 60 String realmName = getName(); 61 //4).credentialsSalt 盐值 62 //使用用户名作为盐值进行加密 63 ByteSource credentialsSalt = ByteSource.Util.bytes(username); 64 65 SimpleAuthenticationInfo info = null;//new SimpleAuthenticationInfo(principal, credentials, realmName); 66 info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName); 67 System.out.println("first ---> end"); 68 return info; 69 } 70 71 public static void main(String[] args) { 72 // 加密方式 73 String algorithmName = "MD5"; 74 // 原文 75 Object source = "123456"; 76 // 盐值 77 Object salt = ByteSource.Util.bytes("user"); 78 // 加密次数 79 int hashIterations = 1024; 80 Object simpleHash = new SimpleHash(algorithmName, source, salt, hashIterations); 81 System.out.println(simpleHash); 82 } 83 84 // 实现授权 85 @Override 86 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 87 //1. 从 PrincipalCollection 中来获取登录用户的信息 88 Object principal = principals.getPrimaryPrincipal(); 89 90 //2. 利用登录的用户的信息来用户当前用户的角色或权限(可能需要查询数据库) 91 Set<String> roles= new HashSet<String>(); 92 roles.add("user"); 93 94 if("admin".equals(principal)){ 95 roles.add("admin"); 96 } 97 // 创建SimpleAuthorizationInfo 并设置其roles属性 98 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles); 99 return info; 100 } 101 102 }
SecondShiroRealms.java
1 package com.shiro.realms; 2 3 import org.apache.shiro.authc.AuthenticationException; 4 import org.apache.shiro.authc.AuthenticationInfo; 5 import org.apache.shiro.authc.AuthenticationToken; 6 import org.apache.shiro.authc.LockedAccountException; 7 import org.apache.shiro.authc.SimpleAuthenticationInfo; 8 import org.apache.shiro.authc.UnknownAccountException; 9 import org.apache.shiro.authc.UsernamePasswordToken; 10 import org.apache.shiro.crypto.hash.SimpleHash; 11 import org.apache.shiro.realm.AuthenticatingRealm; 12 import org.apache.shiro.util.ByteSource; 13 14 public class SecondShiroRealms extends AuthenticatingRealm{ 15 16 @Override 17 protected AuthenticationInfo doGetAuthenticationInfo( 18 AuthenticationToken token) throws AuthenticationException { 19 System.out.println("SECOND [doGetAuthenticationInfo]--->"+token); 20 //1. 把 AuthenticationToken 转换为 UsernamePasswordToken 21 UsernamePasswordToken upToken = (UsernamePasswordToken) token; 22 23 //2. 从 UsernamePasswordToken 中来获取 username 24 String username = upToken.getUsername(); 25 26 //3. 调用数据库的方法, 从数据库中查询 username 对应的用户记录 27 System.out.println("从数据库中获取 username: " + username + " 所对应的用户信息."); 28 29 //4. 若用户不存在, 则可以抛出 UnknownAccountException 异常 30 if("unknow".equals(username)){ 31 throw new UnknownAccountException("账户不存在"); 32 } 33 34 //5. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常. 35 if("monster".equals(username)){ 36 throw new LockedAccountException("账户被锁定"); 37 } 38 39 //6. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo 40 //以下信息是从数据库中获取的. 41 //1). principal: 认证的实体信息. 可以是 username, 也可以是数据表对应的用户的实体类对象. 42 Object principal = username; 43 44 //2). credentials: 密码. 45 String credentials = null; 46 if("admin".equals(username)){ 47 credentials = "315c68cd108fd7352b8a5341682ea3919c670ddd"; 48 }else if("user".equals(username)){ 49 credentials = "ff10a2885358d5e826fbd6aea284902393b79ab8"; 50 } 51 52 //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可 53 String realmName = getName(); 54 //4).credentialsSalt 盐值 55 //使用用户名作为盐值进行加密 56 ByteSource credentialsSalt = ByteSource.Util.bytes(username); 57 58 SimpleAuthenticationInfo info = null;//new SimpleAuthenticationInfo(principal, credentials, realmName); 59 info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName); 60 System.out.println("second ---> end"); 61 return info; 62 } 63 64 public static void main(String[] args) { 65 // 加密方式 66 String algorithmName = "SHA1"; 67 // 原文 68 Object source = "1"; 69 // 盐值 70 Object salt = ByteSource.Util.bytes("admin"); 71 // 加密次数 72 int hashIterations = 1024; 73 Object simpleHash = new SimpleHash(algorithmName, source, salt, hashIterations); 74 System.out.println(simpleHash); 75 } 76 77 }
权限配置
FilterChainDefinitionMapBuilder.java
1 package com.shiro.factory; 2 3 import java.util.LinkedHashMap; 4 5 public class FilterChainDefinitionMapBuilder { 6 7 public LinkedHashMap<String, String> buildFilterChainDefinitionMap(){ 8 LinkedHashMap<String,String> map = new LinkedHashMap<String,String>(); 9 10 map.put("/login.jsp", "anon"); 11 map.put("/shiro/login", "anon"); 12 map.put("/shiro/logout", "logout"); 13 map.put("/user.jsp", "authc,roles[user]"); 14 map.put("/admin.jsp", "authc,roles[admin]"); 15 map.put("/list.jsp", "user"); 16 17 map.put("/**", "authc"); 18 19 return map; 20 } 21 22 }
service
1 package com.shiro.service; 2 3 import java.util.Date; 4 5 import org.apache.shiro.authz.annotation.RequiresRoles; 6 7 public class ShiroServiceTest { 8 9 @RequiresRoles({"admin"}) 10 public void serviceTest(){ 11 System.out.println("serviceTest --->"+ new Date()); 12 } 13 14 }
controller
1 package com.shiro.controller; 2 3 4 5 import org.apache.shiro.SecurityUtils; 6 import org.apache.shiro.authc.UsernamePasswordToken; 7 import org.apache.shiro.subject.Subject; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Controller; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 12 import com.shiro.service.ShiroServiceTest; 13 14 @Controller 15 @RequestMapping("/shiro") 16 public class ShiroController { 17 18 @Autowired 19 private ShiroServiceTest shiroServiceTest; 20 21 @RequestMapping("/login") 22 public String login(String username,String password){ 23 Subject currentUser = SecurityUtils.getSubject(); 24 if(!currentUser.isAuthenticated()){ 25 UsernamePasswordToken token = new UsernamePasswordToken(username, password); 26 token.setRememberMe(true); 27 try { 28 currentUser.login(token); 29 } catch (Exception e) { 30 System.out.println(e.toString()); 31 // TODO: handle exception 32 } 33 } 34 System.out.println("controller ---> end"); 35 return "redirect:/list.jsp"; 36 } 37 @RequestMapping("/logout") 38 public String logout(){ 39 Subject currentUser = SecurityUtils.getSubject(); 40 currentUser.logout(); 41 return "redirect:/login.jsp"; 42 } 43 44 @RequestMapping("/testAnnotation") 45 public String testAnnotation(){ 46 shiroServiceTest.serviceTest(); 47 return "redirect:/list.jsp"; 48 } 49 50 }