SpringSecurity 静态资源无法访问的问题

我使用SpringSecurity+spring boot,遇到了img、css、js静态资源无法访问的问题。

我的html页面使用templates可以进行访问,但是我有一个功能是图片存储问题,在

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        LogoutSuccessHandler myLogoutSuccessHandler = new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                response.sendRedirect("/login");
            }

        };

        http
                //关闭csrf
                .csrf().disable()
                //验证码自定义
                .addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class)
                // 如果没有下面的语句, 那么任何请求都可以免认证
                .authorizeHttpRequests(auth -> auth

                        .requestMatchers("/cs").permitAll()
                         //我这里对图片进行放行,但是毫无作用
                        .requestMatchers("/static/resources/img/**").permitAll()

                        .requestMatchers("/vercodes").permitAll()
                        .requestMatchers("/log").hasRole("2")
                        .requestMatchers("/role").hasRole("7")
                        .requestMatchers("/user").hasRole("1")
                        .requestMatchers("/projiect").hasRole("4")
                        .requestMatchers("/investigate").hasRole("5")

                        .anyRequest().authenticated())
                .formLogin(form -> form.loginPage("/login").permitAll()
                        .defaultSuccessUrl("/index",true)
                        .failureForwardUrl("/index")
                )

                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessHandler(myLogoutSuccessHandler)
                        .invalidateHttpSession(true)
                        .deleteCookies("JSESSIONID")
                )
                ;
        return http.build();
    }

除此之外无任何配置了,希望有相同经历的小伙伴可以帮我解决问题。
网上的大多数都使用过了,无法解决问题

以下内容部分参考ChatGPT模型:


首先,建议检查一下SpringSecurity的配置,是否有配置忽略静态资源的路径。如果没有,可以在WebSecurityConfigurerAdapter的configure方法中添加如下代码:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
}

这样就可以让SpringSecurity忽略这些静态资源的访问权限控制。

另外,如果是图片存储的问题,可以考虑使用Spring Boot提供的静态资源目录。在application.properties中添加如下代码:

spring.resources.static-locations=classpath:/static/,classpath:/public/,file:/path/to/images/

其中,file:/path/to/images/是你存储图片的路径。这样,你就可以通过访问http://localhost:8080/images/xxx.jpg%E6%9D%A5%E8%AE%BF%E9%97%AE%E5%9B%BE%E7%89%87%E4%BA%86%E3%80%82

希望这些解决思路对你有所帮助。


如果我的建议对您有帮助、请点击采纳、祝您生活愉快

问题已经解决