shiro +spring + spring mvc+ mybatis整合

sql
[html] view plain copy
CREATE TABLE `sys_permission` (  
  `id` bigint(20) NOT NULL COMMENT '主键',  
  `name` varchar(128) NOT NULL COMMENT '资源名称',  
  `type` varchar(32) NOT NULL COMMENT '资源类型:menu,button,',  
  `url` varchar(128) DEFAULT NULL COMMENT '访问url地址',  
  `percode` varchar(128) DEFAULT NULL COMMENT '权限代码字符串',  
  `parentid` bigint(20) DEFAULT NULL COMMENT '父结点id',  
  `parentids` varchar(128) DEFAULT NULL COMMENT '父结点id列表串',  
  `sortstring` varchar(128) DEFAULT NULL COMMENT '排序号',  
  `available` char(1) DEFAULT NULL COMMENT '是否可用,1:可用,0不可用',  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  
/*Table structure for table `sys_role` */  
  
CREATE TABLE `sys_role` (  
  `id` varchar(36) NOT NULL,  
  `name` varchar(128) NOT NULL,  
  `available` char(1) DEFAULT NULL COMMENT '是否可用,1:可用,0不可用',  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  
/*Table structure for table `sys_role_permission` */  
  
CREATE TABLE `sys_role_permission` (  
  `id` varchar(36) NOT NULL,  
  `sys_role_id` varchar(32) NOT NULL COMMENT '角色id',  
  `sys_permission_id` varchar(32) NOT NULL COMMENT '权限id',  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  
/*Table structure for table `sys_user` */  
  
CREATE TABLE `sys_user` (  
  `id` varchar(36) NOT NULL COMMENT '主键',  
  `usercode` varchar(32) NOT NULL COMMENT '账号',  
  `username` varchar(64) NOT NULL COMMENT '姓名',  
  `password` varchar(32) NOT NULL COMMENT '密码',  
  `salt` varchar(64) DEFAULT NULL COMMENT '盐',  
  `locked` char(1) DEFAULT NULL COMMENT '账号是否锁定,1:锁定,0未锁定',  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  
CREATE TABLE `items` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(32) NOT NULL COMMENT '商品名称',  
  `price` float(10,1) NOT NULL COMMENT '商品定价',  
  `detail` text COMMENT '商品描述',  
  `pic` varchar(64) DEFAULT NULL COMMENT '商品图片',  
  `createtime` datetime NOT NULL COMMENT '生产日期',  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;  

[html] view plain copy
/*Data for the table `sys_permission` */  
  
insert  into `sys_permission`(`id`,`name`,`type`,`url`,`percode`,`parentid`,`parentids`,`sortstring`,`available`) values (1,'权限','','',NULL,0,'0/','0','1'),(11,'商品管理','menu','/item/queryItem.action',NULL,1,'0/1/','1.','1'),(12,'商品新增','permission','/item/add.action','item:create',11,'0/1/11/','','1'),(13,'商品修改','permission','/item/editItem.action','item:update',11,'0/1/11/','','1'),(14,'商品删除','permission','','item:delete',11,'0/1/11/','','1'),(15,'商品查询','permission','/item/queryItem.action','item:query',11,'0/1/15/',NULL,'1'),(21,'用户管理','menu','/user/query.action','user:query',1,'0/1/','2.','1'),(22,'用户新增','permission','','user:create',21,'0/1/21/','','1'),(23,'用户修改','permission','','user:update',21,'0/1/21/','','1'),(24,'用户删除','permission','','user:delete',21,'0/1/21/','','1');  
  
/*Data for the table `sys_role` */  
  
insert  into `sys_role`(`id`,`name`,`available`) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f28','商品管理员','1'),('ebc9d647-c6f9-11e4-b137-0adc305c3f28','用户管理员','1');  
  
/*Data for the table `sys_role_permission` */  
  
insert  into `sys_role_permission`(`id`,`sys_role_id`,`sys_permission_id`) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f21','ebc8a441-c6f9-11e4-b137-0adc305c','12'),('ebc8a441-c6f9-11e4-b137-0adc305c3f22','ebc8a441-c6f9-11e4-b137-0adc305c','11'),('ebc8a441-c6f9-11e4-b137-0adc305c3f24','ebc9d647-c6f9-11e4-b137-0adc305c','21'),('ebc8a441-c6f9-11e4-b137-0adc305c3f25','ebc8a441-c6f9-11e4-b137-0adc305c','15'),('ebc9d647-c6f9-11e4-b137-0adc305c3f23','ebc9d647-c6f9-11e4-b137-0adc305c','22'),('ebc9d647-c6f9-11e4-b137-0adc305c3f26','ebc8a441-c6f9-11e4-b137-0adc305c','13');  
  
/*Data for the table `sys_user` */  
  
insert  into `sys_user`(`id`,`usercode`,`username`,`password`,`salt`,`locked`) values ('lisi','lisi','李四','bf07fd8bbc73b6f70b8319f2ebb87483','uiwueylm','0'),('zhangsan','zhangsan','张三','cb571f7bd7a6f73ab004a70322b963d5','eteokues','0');  
  
/*Data for the table `sys_user_role` */  
  
insert  into `sys_user_role`(`id`,`sys_user_id`,`sys_role_id`) values ('ebc8a441-c6f9-11e4-b137-0adc305c3f28','zhangsan','ebc8a441-c6f9-11e4-b137-0adc305c'),('ebc9d647-c6f9-11e4-b137-0adc305c3f28','lisi','ebc9d647-c6f9-11e4-b137-0adc305c');  
  
insert  into `items`(`id`,`name`,`price`,`detail`,`pic`,`createtime`) values (1,'台式机',3000.0,'该电脑质量非常好!!!!',NULL,'2015-02-03 13:22:53'),(2,'笔记本',6000.0,'笔记本性能好,质量好!!!!!',NULL,'2015-02-09 13:22:57'),(3,'背包',200.0,'名牌背包,容量大质量好!!!!',NULL,'2015-02-06 13:23:02');  
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;  

pom.xml
[html] view plain copy
<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/xsd/maven-4.0.0.xsd">  
    <modelVersion>4.0.0</modelVersion>  
    <groupId>com.me</groupId>  
    <artifactId>shiro-web</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
    <packaging>war</packaging>  
    <dependencies>  
        <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>3.8.1</version>  
            <scope>test</scope>  
        </dependency>  
  
        <!-- 添加Servlet支持 -->  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>javax.servlet-api</artifactId>  
            <version>3.1.0</version>  
        </dependency>  
  
        <dependency>  
            <groupId>javax.servlet.jsp</groupId>  
            <artifactId>javax.servlet.jsp-api</artifactId>  
            <version>2.3.1</version>  
        </dependency>  
  
        <!-- 添加jtl支持 -->  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
  
        <!-- 添加Spring支持 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-beans</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aspects</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>4.1.7.RELEASE</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.3</version>  
        </dependency>  
  
  
        <!-- 添加日志支持 -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
        </dependency>  
  
        <!-- 添加mybatis支持 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.3.0</version>  
        </dependency>  
  
        <!-- jdbc驱动包 -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.38</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-core</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-ehcache</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-log4j12</artifactId>  
            <version>1.7.12</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-web</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-spring</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
  
  
    </dependencies>  
    <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->  
    <build>  
        <resources>  
            <resource>  
                <directory>src/main/java</directory>  
                <includes>  
                    <include>**/*.properties</include>  
                    <include>**/*.xml</include>  
                </includes>  
                <filtering>false</filtering>  
            </resource>  
            <resource>  
                <directory>src/main/resources</directory>  
                <includes>  
                    <include>**/*.properties</include>  
                    <include>**/*.xml</include>  
                </includes>  
                <filtering>false</filtering>  
            </resource>  
        </resources>  
    </build>  
</project>  


web.xml
[html] view plain copy
<?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>shiro-web</display-name>  
  
    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
      
      
    <!-- Spring监听器 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <!-- Spring配置文件 -->  
        <param-value>classpath:spring/applicationContext.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
      
    <!-- shiro的filter -->  
    <!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->  
    <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>  
      
    <!-- 添加对springmvc的支持 -->  
    <servlet>  
        <servlet-name>springMVC</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>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>springMVC</servlet-name>  
        <url-pattern>*.do</url-pattern>  
    </servlet-mapping>  
      
  
      
      
      
    <!-- post乱码处理 -->  
    <filter>  
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
      
  
      
</web-app>  

spring-mvc.xml
[html] view plain copy
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd   
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">  
  
    <!-- 使用spring组件扫描 -->  
    <context:component-scan base-package="cn.me.ssm.controller" />  
  
    <!-- 通过annotation-driven可以替代下边的处理器映射器和适配器 -->  
    <mvc:annotation-driven>  
    </mvc:annotation-driven>  
  
    <!-- 配置视图解析器 要求将jstl的包加到classpath -->  
    <!-- ViewResolver -->  
    <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
      
      
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 无权权限跳转页面 -->  
                <prop key="org.apache.shiro.authz.UnauthorizedException">refuse</prop>  
            </props>  
        </property>  
    </bean>  
  
    <!-- 定义统一异常处理器 -->  
    <bean class="cn.me.ssm.exception.CustomExceptionResolver"></bean>  
  
    <!-- 开启aop,对类代理 -->  
    <aop:config proxy-target-class="true"></aop:config>  
    <!-- 开启shiro注解支持 -->  
    <bean  
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>  
</beans>  

spring-shiro.xml
[html] view plain copy
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
    xsi:schemaLocation="      
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd    
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd    
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
  
  
  
    <!-- Shiro过滤器 -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <!-- Shiro的核心安全接口,这个属性是必须的 -->  
        <property name="securityManager" ref="securityManager" />  
        <!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证,请求此地址将由formAuthenticationFilter进行表单认证 -->  
        <property name="loginUrl" value="/login.do" />  
        <!-- 认证成功统一跳转到first.action,建议不配置,shiro认证成功自动到上一个请求路径 -->  
        <property name="successUrl" value="/first.do" />  
        <!-- 通过unauthorizedUrl指定没有权限操作时跳转页面 -->  
        <property name="unauthorizedUrl" value="/refuse.jsp" />  
        <!-- Shiro连接约束配置,即过滤链的定义 -->  
        <property name="filterChainDefinitions">  
            <value>  
                <!-- /** = anon所有url都可以匿名访问 -->  
                <!-- 对静态资源设置匿名访问 -->  
                /images/** = anon  
                /js/** = anon  
                /styles/** = anon  
                <!-- 验证码,可匿名访问 -->  
                /validatecode.jsp = anon  
  
                <!-- 请求 logout.action地址,shiro去清除session -->  
                /logout.action = logout  
                <!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 -->  
                <!-- /items/queryItems.action = perms[item:query] -->  
                <!-- /** = authc 所有url都必须认证通过才可以访问 -->  
                /**=authc  
  
            </value>  
        </property>  
    </bean>  
    <!-- 安全管理器 -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <!-- 注入自定义Realm -->  
        <property name="realm" ref="customRealm" />  
        <!-- 注入缓存管理器 -->  
        <property name="cacheManager" ref="cacheManager"/>  
    </bean>  
  
    <!-- 自定义Realm -->  
    <bean id="customRealm" class="cn.me.ssm.shiro.CustomRealm">  
        <!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->  
        <property name="credentialsMatcher" ref="credentialsMatcher" />  
    </bean>  
  
    <!-- 凭证匹配器 -->  
    <bean id="credentialsMatcher"  
        class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">  
        <property name="hashAlgorithmName" value="md5" />  
        <property name="hashIterations" value="1" />  
  
    </bean>  
  
    <!-- 缓存管理器 -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
        <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />  
    </bean>  
  
  
</beans>  

[html] view plain copy
package cn.me.ssm.shiro;  
  
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.realm.AuthorizingRealm;  
import org.apache.shiro.subject.PrincipalCollection;  
import org.apache.shiro.util.ByteSource;  
import org.springframework.beans.factory.annotation.Autowired;  
  
import cn.me.ssm.po.ActiveUser;  
import cn.me.ssm.po.SysPermission;  
import cn.me.ssm.po.SysUser;  
import cn.me.ssm.service.SysService;  
  
/**  
 * 自定义realm  
 *   
 * @author Administrator  
 *  
 */  
public class CustomRealm extends AuthorizingRealm {  
  
    @Autowired  
    private SysService sysService;  
  
    @Override  
    public void setName(String name) {  
        // TODO Auto-generated method stub  
        super.setName("customRealm");  
    }  
      
  
    // 用于认证  
    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
        // token是用户输入的  
        // 第一步从token中取出身份信息  
        String userCode = (String) token.getPrincipal();  
        SysUser sysUser = null;  
        // 第二步:根据用户输入的userCode从数据库查询  
        try {  
            sysUser = sysService.findSysUserByUserCode(userCode);  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
  
        // 如果查询不到返回null  
        if (sysUser == null) {  
            return null;  
        }  
  
        // 从数据库查询加密后密码  
        String password = sysUser.getPassword();  
        // 盐  
        String salt = sysUser.getSalt();  
  
        ActiveUser activeUser = new ActiveUser();  
        activeUser.setUserid(sysUser.getId());  
        activeUser.setUsercode(sysUser.getUsercode());  
        activeUser.setUsername(sysUser.getUsername());  
  
        // 根据用户id取出菜单  
        List<SysPermission> menus = null;  
        try {  
            menus = sysService.findMenuListByUserId(sysUser.getId());  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        activeUser.setMenus(menus);  
  
        // 如果查询到返回认证信息AuthenticationInfo  
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(activeUser, password,  
                ByteSource.Util.bytes(salt), this.getName());  
  
        return authenticationInfo;  
    }  
  
      
    // 用于授权  
    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
        // TODO Auto-generated method stub  
        // 从principals获取主身份信息  
        // 将getPrimaryPrincipal方法返回值转为真实身份类型  
        // (在上边doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中的身份类型)  
        ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();  
  
        // 根据身份信息获取权限信息  
        // 从数据库获取到权限数据  
        List<SysPermission> permissionList = null;  
        try {  
            permissionList = sysService.findPermissionListByUserId(activeUser.getUserid());  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        List<String> permissions = new ArrayList<>();  
        if (permissionList != null) {  
            // 将数据库查到权限标签符放到集合  
            for (SysPermission permission : permissionList) {  
                permissions.add(permission.getPercode());  
            }  
        }  
  
        // 将查询到授权信息填充到simpleAuthorizationInfo对象中  
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();  
        simpleAuthorizationInfo.addStringPermissions(permissions);  
  
        // 返回授权信息  
        return simpleAuthorizationInfo;  
  
    }  
  
    // 清除缓存  
    public void clearCached() {  
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();  
        super.clearCache(principals);  
    }  
}  


设置凭证匹配器


数据库中存储到的md5的散列值,在realm中需要设置数据库中的散列值它使用散列算法 及散列次数,让shiro进行散列对比时和原始数据库中的散列值使用的算法 一致。
[html] view plain copy
<!-- 凭证匹配器 -->  
    <bean id="credentialsMatcher"  
        class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">  
        <property name="hashAlgorithmName" value="md5" />  
        <property name="hashIterations" value="1" />  
  
    </bean>  

授权
修改realm的doGetAuthorizationInfo,从数据库查询权限信息。
使用注解式授权方法。
[html] view plain copy
// 商品信息方法  
    @RequestMapping("/queryItems")  
    @RequiresPermissions("item:query") // 执行queryItems需要"item:query"权限  
    public ModelAndView queryItems(HttpServletRequest request)  

springmvc.xml
[html] view plain copy
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 无权权限跳转页面 -->  
                <prop key="org.apache.shiro.authz.UnauthorizedException">refuse</prop>  
            </props>  
        </property>  
    </bean>  
  
  
    <!-- 开启aop,对类代理 -->  
    <aop:config proxy-target-class="true"></aop:config>  
    <!-- 开启shiro注解支持 -->  
    <bean  
        class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
        <property name="securityManager" ref="securityManager" />  
    </bean>  


使用jsp标签授权方法。
[html] view plain copy
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>  

[html] view plain copy
<!-- 有item:update权限才显示修改链接,没有该 权限不显示,相当 于if(hasPermission(item:update)) -->  
     <shiro:hasPermission name="item:update">   
    <a href="${pageContext.request.contextPath }/items/editItems.do?id=${item.id}">修改</a>  
     </shiro:hasPermission>   

jsp标签 授权


Jsp页面添加:
<%@ tagliburi="http://shiro.apache.org/tags" prefix="shiro" %>


标签名称 标签条件(均是显示标签内容)
<shiro:authenticated>  登录之后
<shiro:notAuthenticated> 不在登录状态时
<shiro:guest> 用户在没有RememberMe时
<shiro:user>  用户在RememberMe时
<shiro:hasAnyRoles name="abc,123" >  在有abc或者123角色时
<shiro:hasRole name="abc"> 拥有角色abc
<shiro:lacksRole name="abc">  没有角色abc
<shiro:hasPermission name="abc"> 拥有权限资源abc
<shiro:lacksPermission name="abc"> 没有abc权限资源
<shiro:principal>  显示用户身份名称
 <shiro:principal property="username"/>     显示用户身份中的属性值

授权测试


当调用controller的一个方法,由于该 方法加了@RequiresPermissions("item:query") ,shiro调用realm获取数据库中的权限信息,看"item:query"是否在权限数据中存在,如果不存在就拒绝访问,如果存在就授权通过。


当展示一个jsp页面时,页面中如果遇到<shiro:hasPermission name="item:update">,shiro调用realm获取数据库中的权限信息,看item:update是否在权限数据中存在,如果不存在就拒绝访问,如果存在就授权通过。


问题:只要遇到注解或jsp标签的授权,都会调用realm方法查询数据库,需要使用缓存解决此问题。

shiro缓存

针对上边授权频繁查询数据库,需要使用shiro缓存。

缓存流程

shiro中提供了对认证信息和授权信息的缓存。shiro默认是关闭认证信息缓存的,对于授权信息的缓存shiro默认开启的。主要研究授权信息缓存,因为授权的数据量大。


用户认证通过。
该 用户第一次授权:调用realm查询数据库
该 用户第二次授权:不调用realm查询数据库,直接从缓存中取出授权信息(权限标识符)。

添加jar
[html] view plain copy
<dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-ehcache</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
[html] view plain copy
<!-- 安全管理器 -->  
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
    <!-- 注入自定义Realm -->  
    <property name="realm" ref="customRealm" />  
    <!-- 注入缓存管理器 -->  
    <property name="cacheManager" ref="cacheManager"/>  
</bean>  
  
<!-- 缓存管理器 -->  
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
    <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />  
</bean>  

shiro-ehcache.xml
[html] view plain copy
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">  
    <!--diskStore:缓存数据持久化的目录 地址  -->  
    <diskStore path="F:\develop\ehcache" />  
    <defaultCache   
        maxElementsInMemory="1000"   
        maxElementsOnDisk="10000000"  
        eternal="false"   
        overflowToDisk="false"   
        diskPersistent="false"  
        timeToIdleSeconds="120"  
        timeToLiveSeconds="120"   
        diskExpiryThreadIntervalSeconds="120"  
        memoryStoreEvictionPolicy="LRU">  
    </defaultCache>  
</ehcache>  

[html] view plain copy
缓存清空  
  
如果用户正常退出,缓存自动清空。  
  
如果用户非正常退出,缓存自动清空。  
  
如果修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。  
需要手动进行编程实现:  
    在权限修改后调用realm的clearCache方法清除缓存。  
下边的代码正常开发时要放在service中调用。  
在service中,权限修改后调用realm的方法。  
在realm中定义clearCached方法:  
[html] view plain copy
//清除缓存  
    public void clearCached() {  
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();  
        super.clearCache(principals);  
    }  
  
  
测试清除缓存controller方法:  

[html] view plain copy
@Controller  
public class ClearShiroCache {  
  
    // 注入realm  
    @Autowired  
    private CustomRealm customRealm;  
  
    @RequestMapping("/clearShiroCache")  
    public String clearShiroCache() {  
  
        // 清除缓存,将来正常开发要在service调用customRealm.clearCached()  
        customRealm.clearCached();  
  
        return "success";  
    }  
  
}  

 sessionManager 
和shiro整合后,使用shiro的session管理,shiro提供sessionDao操作 会话数据。
配置sessionManager
[html] view plain copy
<!-- 会话管理器 -->  
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
        <!-- session的失效时长,单位毫秒 -->  
        <property name="globalSessionTimeout" value="600000"/>  
        <!-- 删除失效的session -->  
        <property name="deleteInvalidSessions" value="true"/>  
    </bean>  

[html] view plain copy
<!-- 安全管理器 -->  
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
    <!-- 注入自定义Realm -->  
    <property name="realm" ref="customRealm" />  
    <!-- 注入缓存管理器 -->  
    <property name="cacheManager" ref="cacheManager"/>  
    <!-- 注入session管理器 -->  
    <property name="sessionManager" ref="sessionManager" />  
</bean>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值