繁体   English   中英

Spring 安全性:我可以加载 static 资源但不能加载图像

[英]Spring Security:I can load static resources but not images

我尝试了这里的所有建议,但我无法使其正常工作

我必须指定我要添加的图像在登录页面上。

我正在使用 maven 创建具有安全性和 thymeleaf 的 spring 引导 webapp。 似乎我所有的 static 资源都加载正常(css/jss)但图像没有。当我在 chrome 中检查开发人员工具时,我在控制台中收到该图像的 404 错误。无论我使用什么路径,我都是得到同样的错误。我已经允许在这里访问所有 static 内容

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers(HttpMethod.GET,"/resources/**" ,"/js/**", "/css/**", "/images/**" ,"/fonts/**", "/scss/**", "/index", "/", "/login").permitAll()
                .and()
                .authorizeRequests()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .defaultSuccessUrl("/home", true)
                .and()
                .logout()
                .logoutSuccessUrl("/")
                .logoutUrl("/signout");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**"); // #3
    }}

这就是我在 thymeleaf 中访问它的方式

 <div class="col-lg-2 ml-auto"  data-aos="fade-up" data-aos-delay="100">
                    <figure class="img-absolute">
                        <img th:src="@{/images/car.jpeg}" alt="Image" class="img-fluid">
                    </figure>
                </div>

这是我的文件夹结构

src->main->resources->static->images->car.jpeg

这是我在开发工具GET http://localhost:8080/images/car.jpeg 404

任何帮助将不胜感激。

使用此方法获取 static 图像和其他资源以加载到您的 html 页面上 -

1.)更正图像的文件夹结构,它应该是 - your_project_name -> src -> main -> resources -> static -> assets -> img --> your images

注意- 在 assets 文件夹中添加您的其他 static 文件和文件夹。

2.) 以及您的安全配置 class -

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
         // your code

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

3.) 在 html 页面上使用正确的 url 访问图像 -

//your code
<img th:src="@{/assets/img/car.jpeg}" alt="Image" class="img-fluid">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM