• springboot 整合apache shiro


    这几天因为项目需要,学习了下shiro,由此留下一些记录,也希望对初学shiro的朋友有帮助。

    springboot 是这两年新兴起来的一个项目,它的出现是为了减少springmvc开发过程中需要引入各种的jar包,各种xml配置文件,它充分利用了JavaConfig的配置模式以及“约定优于配置”的理念,帮开发者配置大部分需要的东西,在github上的springboot项目里面,提供了很多列子,

    而apache shiro 是一个轻量级的身份验证与授权框架,与spring security 相比较,简单易用,灵活性高,springboot本身是提供了对security的支持,毕竟是自家的东西。springboot暂时没有集成shiro,这得自己配。

    网上找了一些资料,配置shiro的,有很多需要在web.xml、application.xml里面各种配置,然而springboot 并没有这些,而且springboot提倡无xml,使用javaconfig的配置方式,对这个不是很熟悉,但有人使用javaconfig的方式配置了shiro,参见这位csdn里面一位同学的博客spring boot 集成shiro的配置,下载了demo,然后模仿着成功配置了下。但习惯了xml的配置方式,感觉javaconfig的方式并不是很直观,于是自己又把它换成了xml的方式。以下是主要的配置过程

    首先是spring-shiro.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:util="http://www.springframework.org/schema/util"
        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/util http://www.springframework.org/schema/util/spring-util.xsd  
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <!-- ========================================================= 
                       Shiro Components 
            ========================================================= -->
    
        <!-- 缓存管理器 使用Ehcache实现 -->
        <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
            <property name="cacheManagerConfigFile" value="classpath:app/config/ehcache-shiro.xml" />
        </bean>
    
        <!-- 虚需要自己写的realm实现类 充当shiro和应用的安全数据的桥梁  -->
        <bean id="MonitorRealm" class="com.test.MonitorRealm"></bean>
        
        <!-- 安全管理器 -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realms">
                <list>
                    <ref bean="MonitorRealm" />
                </list>
            </property>
            <property name="cacheManager" ref="cacheManager" />
        </bean>
    
        <!-- Shiro生命周期处理器 -->
        <!-- 官方对其的解释是  http://shiro.apache.org/static/1.2.1/apidocs/org/apache/shiro/spring/LifecycleBeanPostProcessor.html
        This post processor makes it easier to configure Shiro beans in Spring, 
        since the user never has to worry about whether or not
        if they have to specify init-method and destroy-method bean attributes. 
                大意是使shiro bena 注入更加方便  -->
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    
        <!-- Shiro的Web过滤器 -->
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager" />
            <property name="loginUrl" value="/user-web/login" />
            <property name="unauthorizedUrl" value="/unauthorized  " />
            <property name="filters">
                <util:map>
                    <entry key="authc">
                    <!-- 身份验证拦截器,默认为FormAuthenticationFilter,但 PassThruAuthenticationFilter功能相对强大,详情见
                    https://shiro.apache.org/static/1.2.1/apidocs/org/apache/shiro/web/filter/authc/PassThruAuthenticationFilter.html-->
                        <bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
                    </entry>
                </util:map>
            </property>
            
            <!-- shiro的强大的拦截器链,可以匹配全部的url,并根据配置进行拦截-->
            <property name="filterChainDefinitions">
                <value>
                    # 无需认证便可以访问的的文件放在前面
                    /js/* = anon
                    /css/* = anon
                    /img/* = anon
                    /images/* = anon
    
                    /user-web/login = anon
                    /logout = logout
                    
                    /user-web/* = authc
                    /backend-web/* = authc
                </value>
            </property>
        </bean>
    
    
        <!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
        <!-- 这里要配置以下两个bean,在这之前要配置好lifecycleBeanPostProcessor-->
      
        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
         <!--  加上下面这一句是为了解决If the controller requires proxying (e.g. due to @Transactional), please use class-based proxying  的报错-->
         <!-- 参考http://www.cnblogs.com/digdeep/p/4624998.html 会发现上面错误是 Spring AOP 不同配置方式产生的冲突问题 -->
           <property name="proxyTargetClass" value="true"/>    
        </bean>
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
            <property name="securityManager" ref="securityManager" />
        </bean>
        
        <!-- 异常拦截 -->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="org.apache.shiro.authz.UnauthorizedException">   
                        /unauthorized                                <!-- 未授权处理页 -->        
                    </prop>
                    <prop key="org.apache.shiro.authz.UnauthenticatedException">
                        /user-web/login                             <!-- 身份没有验证 -->
                    </prop>
                </props>
            </property>
        </bean>
    </beans>  

    接着是Ehcache.xml文件。

    ehcache是一个纯Java的进程内缓存框架,相关介绍可以看这里

    <ehcache updateCheck="false" name="shiroCache">
        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="false"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
                />
    </ehcache>

    springboot加载xml配置文件

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @SpringBootApplication
    @ComponentScan
    @EnableAutoConfiguration
    public class Application {
    	public static void main(String[] args) {
    		SpringApplication.run(new String[] {
    				"classpath*:app/config/spring-*.xml",
    				"classpath*:app/config/spring-session-redis.xml",
    				"classpath*:/user/captcha.xml"
    				//....
    			}, args);
    	}
    }

    这样。spingboot以xml形式配置shiro就完成了,后面在controller的方法上面使用注解的的方式,就可以进行权限控制。

    这里没有提供MonitorRealm类,里面要实现doGetAuthorizationInfo(授权)和doGetAuthenticationInfo(认证)两个方法,还有就是loginController里面要做一些改动,有需要的朋友可以参考这篇SpringMVC整合Shiro博文。

  • 相关阅读:
    2010上交:计算表达式
    添加子评论
    上传图片
    settings配置 文件操作
    django 操作前端数据
    静态文件配置
    render httprequest
    上传文件配置
    Django为什么要跳转到不同的页面来实现不同的功能
    定义日志器
  • 原文地址:https://www.cnblogs.com/LZYY/p/4678749.html
Copyright © 2020-2023  润新知