У меня есть простое приложение Spring Boot с таким каталогом:
+ src
+ main
+ java
+ resources
+ public
+ images
- dog.png
+ private
+ images
- cat.png
+ templates
- home.html
- login.html
Ресурсы в общей папке могут быть доступны всем. Я хочу сделать ресурсы в личной папке доступными только для аутентифицированных пользователей.
Например, home.html
могут быть доступны только аутентифицированным пользователям, у которых есть изображение cat.png
. Если неавторизованный пользователь попытается получить прямой доступ к ресурсу через https://localhost:8080/private/images/cat.png
, сервер отклонит запрос.
Мой 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");
}
}
Я также пытался использовать antMatchers.("/resources/private/**").authenticated()
, но он все еще не работает.