【发布时间】:2022-08-17 11:18:49
【问题描述】:
我对 spring 真的很陌生,这就是为什么它可能是一个非常愚蠢的问题,但我在提供静态文件时遇到了麻烦。我正在为图书馆应用程序创建一个 REST api,并且当用户尝试添加一本书时有一些逻辑:
- 我从 SecurityContextHolder 获得主要用户。
- 我添加书籍并将书籍添加到用户的书籍列表中
- 我从 base64 编码字符串中读取字节并将其写入 pdf 文件,存储在 /resources/static
那行得通。但我不知道如何获取此文件。我试着下一步做:
- 我创建了扩展
WebMvcConfigurer的ResourceConfig类,但它不起作用:@Configuration public class ResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler(\"/static/**\") .addResourceLocations(StaticAbsolutePath.getPath()); } }- 哦,
StaticAbsolutePath.getPath()是我用来获取静态目录路径的方法:
public class StaticAbsolutePath { private static final String path = \"A:\\\\java\\\\projects\\\\books\\\\src\\\\main\\\\resources\\\\static\"; public StaticAbsolutePath() { } public static String getPath() { return path; } }- 我决定我的安全配置阻止了这条路径,因为我没有被授权,所以我将它添加到配置类:
http.authorizeRequests().antMatchers(\"/static/**\").permitAll();但它也没有用。当我尝试向
http://localhost:8080/static/1252356147.pdf服务时,它会显示“Whitelabel Error Page”。因此,如果您知道可能是什么问题,请告诉我,我真的很感激!
以下是 SecurityConfig 的完整代码:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(authenticationManagerBean()); customAuthenticationFilter.setFilterProcessesUrl(\"/api/login\"); http.csrf().disable(); http.authorizeRequests().antMatchers(\"/api/login/**\").permitAll(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.authorizeRequests().antMatchers(HttpMethod.POST, \"/api/users/\").authenticated(); http.authorizeRequests().antMatchers(HttpMethod.GET, \"/api/user/current\").authenticated(); http.authorizeRequests().antMatchers(HttpMethod.POST, \"/api/books/**\").authenticated(); http.authorizeRequests().antMatchers(HttpMethod.GET, \"/api/books/**\").permitAll(); http.authorizeRequests().antMatchers(HttpMethod.PUT, \"/api/books/**\").authenticated(); http.authorizeRequests().antMatchers(\"/static/**\").permitAll(); http.addFilter(customAuthenticationFilter); http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } - 哦,
- 我创建了扩展
标签: java spring spring-boot static