背景

在我的项目中咱们可能会存在一些动态资例如者图片、excel、pdf之类的文件拜访是须要受权才可拜访的。

谬误示例
1、咱们通过localhost/profile/girl.jpg能够拜访到美女图片,假如图片是存储在咱们的服务器的/home/data目录下,咱们能够通过nginx的反向动态资源代理能够间接将profile的申请文件转入到/home/data上来读取图片文件。
2、咱们能够将图片间接存储至云服务器,或者一个外网拜访地址例如:https://yunurl/profile/girl.jpg。这种状况咱们无需配置nginx代理。
以上两种状况都是在用户未认证,拿到地址即可拜访文件

解决方案

引入shiro,springboot对文件的申请门路减少映射时shiro进行认证权限判断。
咱们同样分两种状况
1、文件存储在本地,即与利用在同一服务器,例如咱们的文件是在/home/data目录下,咱们能够通过此配置来映射

    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry)    {        registry.addResourceHandler("/profile/**").addResourceLocations("file:/home/data");    }

以上配置使得拜访localhost/profile/girl.jpg时会映射至本地门路上来查找文件,并且shiro会先对此申请进行认证的权限拜访,如果没有登录拜访此链接则会跳转至登录页面。
2、对于存储在云端的文件,咱们同样也须要对其进行认证校验,而做法如上统一,联合addResourceLocations的源码咱们剖析

    /**     * Add one or more resource locations from which to serve static content.     * Each location must point to a valid directory. Multiple locations may     * be specified as a comma-separated list, and the locations will be checked     * for a given resource in the order specified.     * <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}}     * allows resources to be served both from the web application root and     * from any JAR on the classpath that contains a     * {@code /META-INF/public-web-resources/} directory, with resources in the     * web application root taking precedence.     * <p>For {@link org.springframework.core.io.UrlResource URL-based resources}     * (e.g. files, HTTP URLs, etc) this method supports a special prefix to     * indicate the charset associated with the URL so that relative paths     * appended to it can be encoded correctly, e.g.     * {@code [charset=Windows-31J]https://example.org/path}.     * @return the same {@link ResourceHandlerRegistration} instance, for     * chained method invocation     */    public ResourceHandlerRegistration addResourceLocations(String... resourceLocations) {        this.locationValues.addAll(Arrays.asList(resourceLocations));        return this;    }

动态资源的映射反对类门路、本地文件、并且反对url形式的门路映射,因而假如文件存储在https://yunurl/profile/girl.jpg此云门路下。
咱们能够同样来通过此办法来映射

    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry)    {        registry.addResourceHandler("/profile/**").addResourceLocations("https://yunurl/profile");    }

shiro对于申请门路的拦挡是默认在authc过滤级别下,因而只有保障咱们的我的项目申请可能并shiro拦挡,并且门路能映射到动态资源文件,则能够满足动态文件的拜访权限管制