I use Spring Security and Thymeleaf. Spring Security hides pictures from the resources/static/images folder if the user is not authorized, while the block itself is visible. How to make the pictures available to everyone?

 <div sec:authorize="isAnonymous()" class="container"> <div class="row"> <div class="span12"> <h2>Our customers</h2> <div class="col-xs-3" > <div class="well"> <img th:src="@{/images/pic1.jpg}" width="75" height="75" class="img-circle"/> </div> </div> <div class="col-xs-3"> <div class="well"> <img th:src="@{/images/pic2.jpg}" width="75" height="75" class="img-circle"/> </div> </div> </div> </div> </div> 

Spring security config

 @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home", "/images").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } ... } 

    1 answer 1

    In order to check the URL match with antMatchers() Spring uses AntPathMatcher . The correct template, which will get all the files in /images - is /images/* . In order not to guess, it is always better to check the pattern by writing a simple unit test:

     @Test public void testPathMatcher() { final AntPathMatcher pathMatcher = new AntPathMatcher(); assertTrue(pathMatcher.match("/images/*", "/images/picture.png")); } 

    Many additional sample templates can be found in the Spring tests .


    If we talk about static resources, they are usually ignored, and not assigned to access rights, as you do. Here is an example:

    WEB-INF

     └───WEB-INF ├───fonts ├───images ├───scripts ├───styles 

    Webconfig

     @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/scripts/**").addResourceLocations("/WEB-INF/scripts/"); registry.addResourceHandler("/styles/**").addResourceLocations("/WEB-INF/styles/"); registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/images/"); registry.addResourceHandler("/fonts/**").addResourceLocations("/WEB-INF/fonts/"); } } 

    Securityconfig

     @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers("/scripts/**") .antMatchers("/styles/**") .antMatchers("/images/**") .antMatchers("/fonts/**"); } @Override protected void configure(HttpSecurity http) throws Exception { //... настройка security } } 

    The corresponding template includes the directory, and all subdirectories.