package org.example.sweater.config; import org.example.sweater.service.UserService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; @Configuration @EnableWebSecurity @EnableMethodSecurity public class WebSecurityConfig { public WebSecurityConfig(UserService userService) { this.userService = userService; } private final UserService userService; @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath("classpath:/templates/"); return configurer; } @Bean FreeMarkerViewResolver freeMarkerViewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setCache(true); resolver.setPrefix(""); resolver.setSuffix(".ftl"); resolver.setOrder(1); return resolver; } @Bean public SecurityFilterChain securityFilterChain( HttpSecurity http ) throws Exception { http .authorizeHttpRequests((requests) -> requests .requestMatchers("/", "/registration") .permitAll() .anyRequest() .authenticated() ) .formLogin((form) -> form .loginPage("/login") .permitAll() ) .logout((logout) -> logout.permitAll()) .csrf((csrf) -> csrf .csrfTokenRepository( CookieCsrfTokenRepository.withHttpOnlyFalse() ) ); return http.build(); } @Bean public AuthenticationManager authenticationManager( AuthenticationConfiguration authenticationConfiguration ) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userService); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; } }