Search code examples
htmlspringspring-bootspring-mvcthymeleaf

Refused to display image in Thymeleaf


I have a SpringBoot 2.1.7.RELEASE app. with Thymeleaf template engine I hace this piece of code in a Thymeleaf template, but the image does not show up

<object data="assets/img/icons/ico_status_up.svg" type="image/svg+xml">
    <img th:src="@{assets/img/icons/ico_status_up.png}"  alt="UP">
</object>

I and see this error in the console of the browser:

Refused to display 'http://localhost:8080/bonanza/pecador/assets/img/icons/ico_status_up.svg' in a frame because it set 'X-Frame-Options' to 'deny'.

I use spring-security in my project:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

   <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

Solution

  • The problem is you are probably using authconfigured Spring Security module.

    As explained in Spring Security Docs :

    A more modern approach to address clickjacking is to use X-Frame-Options header:

    X-Frame-Options: DENY

    The X-Frame-Options response header instructs the browser to prevent any site with this header in the response from being rendered within a frame. By default, Spring Security disables rendering within an iframe.

    So to configure this behaviour you should configure your Spring Security :

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            // ...
            .headers()
                .frameOptions()
                    .sameOrigin(); // or disable();
        }
    }
    

    Also I would encourage you to look at SO question which covers topic on what html tag to use to display SVG - Do I use <img>, <object>, or <embed> for SVG files?