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.