Spring Security как настроить права доступа
Я новичок. Пытаюсь сделать по туториалу приложение на Spring Boot с Spring Security, но так, чтобы регистрация и аутентификации не были обязательными для просмотра страниц. Пытался искать решение в интернете, но либо ничего не понял, либо сделал, но не работает (например выставил anyRequest().permitAll()
) и все равно перебрасывает на страницу login. Вот мой WebSecurityConfig:
package config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import service.UserService;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@SuppressWarnings("removal")
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.
csrf((csrf) -> csrf.disable())
.authorizeHttpRequests(authz -> authz.anyRequest().permitAll()
//Доступ только для не зарегистрированных пользователей
.requestMatchers("/registration").not().fullyAuthenticated()
//Доступ только для пользователей с ролью Администратор
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
//Настройка для входа в систему
.formLogin()
.loginPage("/login")
//Перенарпавление на главную страницу после успешного входа
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/"));
}
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder());
}
}
UPD. Попробовал еще добавить .requestMatchers("/**").permitAll()
- то же самое
UPD. Я только сейчас заметил, что я скорее всего напортачил где-то в другом месте, так как если я пытаюсь запретить доступ к login странице, приложение на это не реагирует и все равно разрешает к ней доступ: .formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll().
Где я еще мог что-то не так сделать?