【问题标题】:Spring Boot WebSecurity not ignoring file uploaded from clientSpring Boot WebSecurity不忽略从客户端上传的文件
【发布时间】:2020-10-31 04:07:42
【问题描述】:

我有一个像这样配置 WebSecurity 的 Spring Boot 项目

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity http) throws Exception {
            http.ignoring().antMatchers("/resources/**");
    }
}

在我开始项目后,我可以通过网络浏览器正常访问资源文件夹中的文件。示例:http://localhost:8080/resources/file1.css

但问题是:我有一个用于将文件从客户端上传到服务器的功能。如果我从客户端上传文件:file2.css 到服务器中的资源文件夹。在我重新启动项目之前,我无法通过地址 http://localhost:8080/resources/file2.css 访问文件,file2.css 上传成功并存在于资源文件夹中,但响应错误未授权

<UnauthorizedException>
    <error>unauthorized</error>
    <error_description>Full authentication is required to access this resource</error_description>
</UnauthorizedException>

如果我重启服务器项目http://localhost:8080/resources/file2.css就可以正常访问了。

上传文件后有什么方法可以绕过 WebSecurity?

请帮忙,非常感谢!

【问题讨论】:

  • >> 如果我重新启动服务器项目localhost:8080/resources/file2.css 可以正常访问。这实际上可能意味着您的资源文件夹是构建的 jar 的一部分,而不是您尝试访问它的方式。
  • 我想了想,决定把文件放在不同的位置,然后用控制器上写的另一个 api 读取它的内容。它似乎工作正常,但我需要一个处理程序将文件路径作为 api 参数传递并从那里读取到适当的文件。谢谢

标签: java spring spring-boot spring-security


【解决方案1】:

问题在于您尝试将文件上传到类路径中的文件夹;我建议使用不同的位置来上传文件并将该位置配置为资源位置并使用资源处理程序进行访问。

例如,如果你打算上传文件到/usr/local/upload,那么你可以配置

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/upload/**")
          .addResourceLocations("file:/usr/local/upload");
     } 
}

【讨论】:

  • 我不太明白这个函数怎么写。我在 WebSecurityConfigurerAdapter 中搜索,但没有看到要覆盖的 addResourceHandlers。能详细点吗?
  • 你需要从 WebMvcConfigurer 覆盖 addResourceHandlers。
猜你喜欢
  • 2017-09-26
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 2017-06-11
  • 2019-11-05
  • 2021-08-08
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多