天天看点

SpringBoot2与Shiro的二三事

  用的技术:SpringBoot2+MySql8+Mybatis Generator+Mybatis+Redis+Druid+Maven多模块+Swagger

tips:

1.可以把Util模块作为依赖写进主模块里面 这样打包的时候util模块会被打包成一个jar包进web_inf里面,这样发生修改的时候,只要替换对应的jar包就可以了.

2.在Swagger最新的版本中,已经有swagger-spring-boot-swagger版本了,所以不用再向以前一样定义SwaggerConfig,然后再进行各种配置了,现在直接再application文件里面进行各种配置就可以了.(必要的时候可以登陆官网查看)

SpringBoot2与Shiro的二三事

3.Mybatis Generator配合lombok插件,可以生成超级简洁的文件.

SpringBoot2与Shiro的二三事

具体的配置如下图

SpringBoot2与Shiro的二三事

4.通过https://github.com/theborakompanioni/thymeleaf-extras-shiro 可以在html页面中使用shiro标签来进行权限控制 注意要使用thymeleaf模板引擎而且html页面要加入引用

SpringBoot2与Shiro的二三事

配合上对thymeleaf的引用

SpringBoot2与Shiro的二三事

5.SpringBoot2和shiro里面拦截器都注定了需要自定义静态资源的解析路径和shiro放开对它的拦截

filterChainDefinitionMap.put("/static/**", "anon");
           
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         *只要在<img src="/static/picName.jpg" />便可以直接引用图片
         * ResourceHandler 表示资源的请求路径 ResourceLocations表示资源的定位
         **/
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

}
           

5.为了避免shiro极短时间内频繁调用sessionread,引入了本地ThreadLocal机制;

6.shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized") 设置无效,无权限页面不跳转 .

SpringBoot2与Shiro的二三事

原因:满足filter instanceof AuthorizationFilter的,只有perms,roles,ssl,rest,port才是属于AuthorizationFilter,而anon,authcBasic,auchc,user是AuthenticationFilter, 所以unauthorizedUrl设置后页面不跳转. Shiro注解模式下,登录失败与没有权限都是通过抛出异常,并且默认并没有去处理或者捕获这些异常。所以通过配置了全局异常捕捉来处理

SpringBoot2与Shiro的二三事

7.访问不存在的后台服务,如/userInfo/adddfdsafsafsa 这样后面随便乱打的,这种情况,依然还是返回了Whitelabel Error Page页面,我们不想看到这种效果,所以还需要在ShiroConfig配置类中,添加以下配置:

SpringBoot2与Shiro的二三事

8.Druid 现在也有starter模块了 先引入依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
           

再在配置文件中加入如下配置:所以现在是真的方便.

SpringBoot2与Shiro的二三事

继续阅读