Springboot 3.x 버전에서는 뭔가 많이 바꼈다. 이번 프로젝트를 진행해보며 CORS 문제를 해결을 어떻게 했는지 써보겠다!
프론트에서 우회하는 방식도 있지만 스프링부트에서 해결하는 방식으로 진행했다.
일단 나는 Spring Security를 사용중에 있으므로 Security를 사용했을때를 기준으로 설명하겠다.
public class SecurityConfig {
...
CorsConfigurationSource corsConfigurationSource() {
return request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedOriginPatterns(new ArrayList<String>() {{
add("http://localhost:3000");
}});
config.setAllowCredentials(true);
return config;
};
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
// 여기서 위에서 Cors 설정을 해준걸 추가!!
.cors(corsConfigurer -> corsConfigurer.configurationSource(corsConfigurationSource()))
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/api/v1/user/**").hasRole("USER")
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.requestMatchers("/api/v1/member/**").hasAnyRole("USER", "ADMIN")
.anyRequest().permitAll()
)
.httpBasic(Customizer.withDefaults())
.exceptionHandling((httpSecurityExceptionHandlingConfigurer) -> httpSecurityExceptionHandlingConfigurer
.accessDeniedHandler(new CustomAccessDeniedHandler())
.authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.build();
}
...
}
이렇게 해주고 만약 IP를 추가해주고 싶다면 setAllowedOriginPatterns에 add해주면 된다!
아주아주 간단하다.
'스프링부트' 카테고리의 다른 글
RestTemplate를 RestClient로 ?! (0) | 2024.07.01 |
---|---|
Redis를 이용한 캐싱과 캐싱전략 (0) | 2024.07.01 |
@Qualifier와 @Autowired (1) | 2024.01.09 |
Springboot JPA BigText 설정하기 (0) | 2024.01.09 |