Search code examples
htmlcssspringthymeleaf

Spring error_page cannot load css


I have a Spring Boot project. I'm using Spring Security with this config:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests(authorize -> authorize
                        .antMatchers("/static/**", "/index").permitAll()
                        .antMatchers("/premium/**").hasAnyAuthority("ADMIN","PREMIUM")
                        .antMatchers("/user/**").hasAnyAuthority("ADMIN","PREMIUM","USER")
                )
                .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login-error")
                    .defaultSuccessUrl("/index")
                    .permitAll()
                .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/index")
                    .permitAll();
    }

This is my structure for html pages.

\resources
    \static
        \css
            style.css

    \templates
        index.html
        error_page.html
        \premium
            premium.html

In all the html files I have css loaded this way:

<link rel="stylesheet" type="text/css" href="css/style.css">

When I open each of the pages separately, the css is loaded and everything works properly.

The problem happens when a user with the role "USER" tries to access the premium.html. Spring shows an error_page with the 403 error code. But this error page is located at the premium.html URL. In other words, URL bar shows www.domain/premium.html but the contents of the page are the ones of the error page. So the assets are not loaded with this error:

Failed to load resource: the server responded with a status of 403 () http://domain/premium/css/style.css

A tried using th:href but with no luck.

<link rel="stylesheet" type="text/css" th:href="@{css/style.css}">

How can I fix this?


Solution

  • The problem is that the page is looking for the assets in /premium/css/style.css where they are obviously not present

    What you're missing is a single slash /.

    Instead of:

    <link rel="stylesheet" type="text/css" th:href="@{css/style.css}">
    

    ...please do:

    <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}">
    

    As stated in Thymeleaf's documentation:

    Relative URLs starting with / (eg: /order/details) will be automatically prefixed by the application context name.

    That way your link will be relative to application context (http://domain/) and will point to proper folder.