1

I have a simple Spring Boot application with a directory like this:

+ src
  + main
    + java
    + resources
      + public
         + images
            - dog.png
      + private
         + images
            - cat.png
      + templates
         - home.html
         - login.html

Resources in the public folder can be accessed by everyone. I want to make resources in the private folder to be only accessed by authenticated users.

For example, home.html can only be accessed by authenticated users, which has an image cat.png. If an unauthorized user tries to directly access the resource via https://localhost:8080/private/images/cat.png then the server will reject the request.

My WebSecurityConfig.java :

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .antMatchers("/", "/home").permitAll()
                .antMatchers(HttpMethod.GET, "/resources/private/images/cat.png").authenticated()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth.inMemoryAuthentication()
                .withUser("user").password(encoder.encode("password")).roles("USER");
    }

}

I've also tried using antMatchers.("/resources/private/**").authenticated() as well, but it still doesn't seem to work.

  • 2
    issue could be url pattern is /private/images/cat.png and you are adding /resources/private/ in your WebSecurityConfig – akshaya pandey Nov 06 '18 at 04:11
  • 1
    https://stackoverflow.com/a/45537528/6572971 might help you. – Alien Nov 06 '18 at 04:31
  • 1
    Your URL is wrong. There is no `/resources` as that is part of the classpath. So remove the `/resources` from the url mapping. Also you want to move the first line to just before the `anyRequest`.. Ordering of security rules is important as that is also the order they are consulted in. Also `home.html` is accessible by anyone according to your security configuration. – M. Deinum Nov 06 '18 at 07:40

0 Answers0