shiro 与spring集成

实际开发项目中shiro经常与spring集成使用,该文章就来介绍下sping集成shiro完成权限验证的操作。

1、引入shiro相关jar包

加入shiro的jar包,此处使用版本为1.4.0,spring的jar包就忽略了(当 大家有spring基础)

   <!-- Shiro权限管理 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>1.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-quartz</artifactId>
      <version>1.4.0</version>
    </dependency>

2、在web.xml中加入shiro的过滤器

<filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
        <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>

3、编写shiro的登录和权限认证类Realm

/**
     * 权限认证,验证授权信息,主要设置用户的角色和权限信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取登录用户信息
        HUser user = (HUser) principalCollection.getPrimaryPrincipal();
        //2.查询用户的权限信息
        List<HPermission> permissionList =
                permissionService.findPermissonByUser(user.getId());
        // 创建权限信息对象
        SimpleAuthorizationInfo authorizationInfo =
                new SimpleAuthorizationInfo();
        Set<String> permissionSet=new HashSet<>();
        for (HPermission hPermission : permissionList) {
                permissionSet.add(hPermission.getPercode());
        }
        //设置权限信息(权限编码)
        authorizationInfo.setStringPermissions(permissionSet);
        List<HRole> roleList = roleService.findRolesByUser(user.getId());
        Set<String>roleSet=new HashSet<>();
        for (HRole hRole : roleList) {
            roleSet.add(hRole.getRolecode());
        }
        //设置角色信息(角色编码)
        authorizationInfo.setRoles(roleSet);
        return authorizationInfo;
    }

    /**
     * 身份认证,登录时判断用户身份信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1、authenticationToken 保存了用户登录信息,获取前台登录传递的用户名
        String name = (String) authenticationToken.getPrincipal();
        //2、根据用户名查询用户信息
        HUser user = userService.findUserByName(name);
        //返回null则验证不通过
        if(user==null) {
            return null;
        }
        //身份认证信息对象
        //第一个参数为需要保存到session中的对象
        //第二个参数为数据库中存储的密码
        //第三个参数为盐值
        //第四个参数为自定义的realm的名字
        SimpleAuthenticationInfo simpleAuthenticationInfo=
          new SimpleAuthenticationInfo(user,user.getPassword()
          ,new SimpleByteSource(user.getCreatetime().getTime()+"")
          ,getName());
        return simpleAuthenticationInfo;
    }

4、与spring整合

4.1 配置applicationContext-shrio.xml配置文件,用以配置shiro的信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置sessionManager-->
    <bean id="sessionManager"
          class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!--设置session超时时间-->
        <property name="globalSessionTimeout" value="9000000"></property>
        <!--设置删除无效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="1"/>
    </bean>

    <!--配置Realm-->
    <bean id="myRealm" class="com.seecen.ssm.shiro.MyRealm">
        <!--将加密方式注入-->
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

    <!--配置安全管理器-->
    <bean id="securityManager"
          class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--注入验证类-->
        <property name="realm" ref="myRealm"/>
        <!--注入sessionManager-->
        <property name="sessionManager" ref="sessionManager"/>
    </bean>
    <!--配置shiro的过滤器-->
    <bean id="shiroFilter"
          class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--注入安全管理器-->
        <property name="securityManager" ref="securityManager"/>
        <!--配置登录页面地址,当用户未登录时会跳转到该地址-->
        <property name="loginUrl" value="/login.jsp"></property>
        <!--登录成功地址-->
        <property name="successUrl" value="/index.jsp"></property>
        <!--配合过滤规则-->
        <property name="filterChainDefinitions">
            <value>
                /js/** =anon
                /login.jsp =anon
                /plugins/** =anon
                /login =anon
                /register.jsp =anon
                /register =anon
                /** =authc
            </value>
        </property>
    </bean>

</beans>
 @RequestMapping("/register")
    public String register(HUser user){
        //设置创建时间
        user.setCreatetime(new Date());
        //将用户密码MD5加密
        SimpleHash md5 = new SimpleHash(
                "MD5"//加密方法
                ,user.getPassword()//需要加密的数据
                ,user.getCreatetime().getTime()+""//盐值
                ,2);//加密次数
        //将加密后的密码设置进user对象
        user.setPassword(String.valueOf(md5));
        userService.insert(user);
        return "redirect:/toLogin";
    }
 @RequestMapping("login")
    public String login(HUser user){
        //获取登录用户Subject
        Subject subject = SecurityUtils.getSubject();
        //封装token
        UsernamePasswordToken token=
                new UsernamePasswordToken(user.getName(),user.getPassword());
        try {
            //执行登录验证,会调用自定义realm进行验证。
            subject.login(token);
        }catch (AuthenticationException e){
            //如果抛出异常,则认证失败,跳转到登录页面
            return "login";
        }
        //没抛异常则认证通过,跳转到首页
        return "redirect:/index";
    }

4.2 在springmvc配置文件中配置shiro

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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">

    <!--设置返回json格式数据时,日期格式 ,当某些需要特殊处理,不按此方式来时,
  在get方法上使用@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                    <property name="objectMapper">
                        <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                            <property name="dateFormat">
                                <bean class="java.text.SimpleDateFormat">
                                    <!-- 设置全局返回JSON到前端时日期格式化 -->
                                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
                                </bean>
                            </property>
                        </bean>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
    <!--aop注解-->
    <aop:aspectj-autoproxy/>
    <!--<aop:aspectj-autoproxy proxy-target-class="true" />-->
    <!--开启注解-->
    <mvc:annotation-driven/>
    <!--配置控制层扫描包-->
    <context:component-scan base-package="com.seecen.ssm.controller,com.seecen.ssm.aop"/>

    <!--配置静态资源-->
    <mvc:default-servlet-handler />

    <!--设置开启shiro注解-->
    <aop:config proxy-target-class="true"/>
    <bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">

    <property name="securityManager" ref="securityManager"></property>
    </bean>

    <!--
       springmvc简单异常处理器,配置异常信息,实现全局异常处理
       也可以自定义全局异常处理类 implements HandlerExceptionResolver
        @ControllerAdvice+ @ ExceptionHandler等
    -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--配置异常信息跳转规则-->
        <property name="exceptionMappings">
            <props>
                <!--配置异常对应的操作-->
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    /refuse.jsp
                </prop>
            </props>
        </property>
    </bean>
</beans>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,976评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,249评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,449评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,433评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,460评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,132评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,721评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,641评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,180评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,267评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,408评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,076评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,767评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,255评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,386评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,764评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,413评论 2 358

推荐阅读更多精彩内容