关于springboot:在SpringBoot下结合shiro对静态资源实现认证访问权限控制

10次阅读

共计 2091 个字符,预计需要花费 6 分钟才能阅读完成。

背景

在我的项目中咱们可能会存在一些动态资例如者图片、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 拦挡,并且门路能映射到动态资源文件,则能够满足动态文件的拜访权限管制

正文完
 0