shiro 和 spring boot 的集成

1 添加依赖

使用 shiro-spring-boot-web-starter 在 spring boot 中集成 shiro 只需要再添加一个依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.4.1</version>
</dependency>

2 基本配置

2.1 Bean 配置

shiro-spring-boot-web-starter 按照 spring boot 的设计理念,底层实现了大量的配置。按照官方的介绍,用户只需要添加两个必须的 Bean,就可以运行 shiro。一个是 Realm,另一个是 ShiroFilterChainDefinition。其中 Realm 可以添加多个,在启动时,会自动将他们添加进 SecurityManager。

代码如下

@Configuration
public class ShiroConfig {
    /**
     * 配置自定义 realm
     * @return
     */
    @Bean
    public Realm realm() {
        LoginRealm loginRealm = new LoginRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashIterations(3);
        credentialsMatcher.setHashAlgorithmName("md5");
        loginRealm.setCredentialsMatcher(credentialsMatcher);
        return loginRealm;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition shiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
        shiroFilterChainDefinition.addPathDefinition("/lib/**","anon");
        shiroFilterChainDefinition.addPathDefinition("/static/**","anon");
        shiroFilterChainDefinition.addPathDefinition("/verifyCode.jsp","anon");
        shiroFilterChainDefinition.addPathDefinition("/checkVerifyCode","anon");
        shiroFilterChainDefinition.addPathDefinition("/logout","logout");
        shiroFilterChainDefinition.addPathDefinition("/login","authc");
        shiroFilterChainDefinition.addPathDefinition("/**","user");
        return shiroFilterChainDefinition;
    }
}

另外,如果需要配置 CacheManager,还可以添加一个 Bean,例如下面使用 EhCache 作为缓存管理。

//配置缓存
@Bean
public CacheManager cacheManager() {
    EhCacheManager ehCacheManager = new EhCacheManager();
    ehCacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml");
    return ehCacheManager;
}

2.2 application.properties 配置

shiro-spring-boot-web-starter 还支持使用 application.properties 配置自定义参数,修改默认值,用于程序启动时初始化自动生成的 Bean。比如常见的 Cookie 和 Session 的时效、loginUrl、successUrl 等。

#配置Shiro
shiro.loginUrl=/login
shiro.successUrl=/index
shiro.unauthorizedUrl=/unauthorized
shiro.userNativeSessionManager=true
shiro.rememberMeManager.cookie.maxAge=259200
shiro.sessionManager.cookie.maxAge=10800

2.3 底层的配置过程

阅读源码可以知道,底层会将 spring 容器中的 Realm 和 ShiroFilterChainDefinition@Autowired 的方式注入后,用于创建 SecurityManagerShiroFilterFactoryBean

2.3.1 SecurityManager

shiro-spring-boot-web-starter 底层自动配置的 SecurityManager 对应生成 Bean 的配置类在 org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration,该类继承 AbstractShiroWebConfiguration,而 AbstractShiroWebConfiguration 继承 org.apache.shiro.spring.config.AbstractShiroConfiguration,下面是解析。

shiro-spring-boot-web-starter 原理图

2.3.2 ShiroFilterFactoryBean

在以前使用 shiro-spring 进行集成的时候,我们需要在 shiro 的配置文件配置 ShiroFilterFactoryBean 时,配置安全管理器、successUrl、loginUrl、filterChainDefinitions 等配置。如下

<!--配置 shiro 框架的过滤器-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!--注入安全管理器-->
    <property name="securityManager" ref="securityManager"/>
    <!--默认的认证成功后跳转的页面-->
    <property name="successUrl" value="/index"/>
    <!--认证失败、登录访问的页面-->
    <property name="loginUrl" value="/login"/>
    <!--没有权限访问时跳转的页面-->
    <property name="unauthorizedUrl" value="/unauthorized"/>

    <!--注入自定义 filter-->
    <property name="filters">
        <map>
            <entry key="authc" value-ref="myFormAuthenticationFilter"/>
        </map>
    </property>

    <!--配置过滤器链-->
    <property name="filterChainDefinitions">
        <value>
            <!--静态资源不需要验证,放行-->
            /lib/** = anon
            /static/** = anon
            /verifyCode.jsp = anon
            /checkVerifyCode = anon

            <!--退出登录-->
            /logout = logout

            <!--只有登录界面走验证-->
            /login = authc

            <!--其它所有页面都可以在rememberMe后访问-->
            /** = user
        </value>
    </property>
</bean>

而使用了 shiro-spring-boot-web-starter 后,底层会自动装配生成 ShiroFilterFactoryBean,参考的源码在 org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration,该类继承 AbstractShiroWebFilterConfiguration,具体的方法在抽象类内,解析如下

image

2.4 其它可选的 properties 配置项

参考官网,可选的配置项有:

image

3 进阶配置

实际开发中我们可能需要重写 Filter,例如 FormAuthenticationFilter 以实现业务需求。这时候我们就需要手动创建 ShiroFilterFactoryBean 覆盖框架自动生成的。源码和解析如下

image

4 注意事项

需要注意的一点是,使用 shiro-spring-boot-web-starter 时,会出现一些 bug:在 Controller 内的方法上用注解的方式做权限控制时(打了 @RequiresPermissions 标签),@RequestMapping 标签会出问题,前台浏览器访问时会报 404 错误。解决办法就是在添加一个 Bean,如下

/**
 * setUsePrefix(true)用于解决一个奇怪的bug。在引入spring aop的情况下。
 * 在@Controller注解的类的方法中加入@RequiresRole等shiro注解,会导致该方法无法映射请求,导致返回404。
 * 加入这项配置能解决这个bug
 */
@Bean
public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
    DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();
    defaultAdvisorAutoProxyCreator.setUsePrefix(true);
    return defaultAdvisorAutoProxyCreator;
}
posted @ 2019-07-30 16:49  Carlos_Ouyang  阅读(644)  评论(0编辑  收藏  举报