Commit cab20856 by Patryk Czarnik

requestMatchers i reguły dostępu

parent 3bf9b1b4
......@@ -10,6 +10,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import jakarta.servlet.DispatcherType;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
......@@ -19,11 +21,26 @@ public class SecurityConfig {
// - sposób uwierzytelniania
// (czy tradycyjny formularz logowania, czy HttpBasic, czy OAuth2, ...)
// W tej wersji jawnie wpisujemy takie ustawienia, które są ustawieniami domyślnymi.
// W tej wersji różnym rolom dajemy różne poziomy dostępu.
// (inaczej mówiąc: dla róznych adresów mamy różne wymagania)
// To pomogło mi napisać poprawną konfigurację w "nowym stylu":
// https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html
// Kluczowe było dodanie linii z DispatcherType.FORWARD → bez tego Spring wymagał autentykacji na etapie przechodzenia do szablonu jsp (FORWARD) lub wyświetlenia błędu
@Bean
SecurityFilterChain configHttpSecurity(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeHttpRequests(authz -> authz
.anyRequest().authenticated()
// zezwalamy na działanie przekierowań wewnętrznych (szablony) i błędów
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers("/", "/whoami", "/*.css").permitAll()
.requestMatchers("/hello", "/time").permitAll()
.requestMatchers("/alt?/**").authenticated() // zalogowany jako ktokolwiek
.requestMatchers("/products/new", "/products/*/edit").hasAuthority("ROLE_manager")
.requestMatchers("/products/**").permitAll() // kolejność reguł ma znaczenie
.requestMatchers("/customers/new", "/customers/*/edit").hasRole("manager") // skrót na hasAuthority("ROLE_...")
.requestMatchers("/customers/**").authenticated()
.anyRequest().denyAll() // dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
).formLogin(Customizer.withDefaults())
;
return httpSecurity.build();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment