|
| 1 | +package com.example.rsa.config; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Value; |
| 4 | +import org.springframework.context.annotation.Bean; |
| 5 | +import org.springframework.context.annotation.Configuration; |
| 6 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 7 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 8 | +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; |
| 9 | +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
| 10 | +import org.springframework.security.crypto.password.PasswordEncoder; |
| 11 | +import org.springframework.web.cors.CorsConfiguration; |
| 12 | +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| 13 | +import org.springframework.web.cors.CorsConfigurationSource; |
| 14 | +import org.springframework.security.web.SecurityFilterChain; |
| 15 | + |
| 16 | +import java.util.List; |
| 17 | + |
| 18 | +import static org.springframework.security.config.Customizer.withDefaults; |
| 19 | + |
| 20 | +@Configuration |
| 21 | +@EnableWebSecurity |
| 22 | +public class SecurityConfig { |
| 23 | + |
| 24 | + @Value("${cors.allowed-origins}") |
| 25 | + private String allowedOrigins; |
| 26 | + |
| 27 | + @Bean |
| 28 | + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { |
| 29 | + http |
| 30 | + .csrf(AbstractHttpConfigurer::disable) |
| 31 | + .authorizeHttpRequests(authorize -> authorize |
| 32 | + .anyRequest().permitAll() |
| 33 | + ) |
| 34 | + .cors(withDefaults()); |
| 35 | + |
| 36 | + return http.build(); |
| 37 | + } |
| 38 | + |
| 39 | + @Bean |
| 40 | + public CorsConfigurationSource corsConfigurationSource() { |
| 41 | + CorsConfiguration configuration = new CorsConfiguration(); |
| 42 | + configuration.setAllowedOrigins(List.of(allowedOrigins)); |
| 43 | + configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); |
| 44 | + configuration.setAllowedHeaders(List.of("*")); |
| 45 | + |
| 46 | + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
| 47 | + source.registerCorsConfiguration("/**", configuration); |
| 48 | + return source; |
| 49 | + } |
| 50 | + |
| 51 | + @Bean |
| 52 | + public PasswordEncoder passwordEncoder() { |
| 53 | + return new BCryptPasswordEncoder(); |
| 54 | + } |
| 55 | +} |
0 commit comments