Skip to content

Commit

Permalink
Fix: CORS 오류 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
tioon committed Apr 25, 2024
1 parent 80d5248 commit ca16af1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

import static com.web.baebaeBE.global.security.SecurityConstants.NO_AUTH_LIST;
import static org.springframework.boot.autoconfigure.security.servlet.PathRequest.toH2Console;
Expand Down Expand Up @@ -48,7 +54,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable() // csrf, http로그인, form로그인, 로그아웃 비활성화. (토큰방식으로 인증)
.httpBasic().disable()
.formLogin().disable()
.logout().disable();
.logout().disable()
.cors().configurationSource(corsConfigurationSource()); // cors 활성화

http.sessionManagement() // 세션관리 설정 (Stateless로 설정 -> 세션 사용X)
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
Expand All @@ -67,6 +74,21 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}

// 스프링 시큐리티 CORS 허용
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173")); // 허용할 오리진 설정
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH")); // 허용할 HTTP 메소드 설정
configuration.setAllowedHeaders(Collections.singletonList("*")); // 허용할 HTTP 헤더 설정
configuration.setAllowCredentials(true); // 쿠키를 포함한 요청 허용 설정
configuration.setMaxAge(3600L); // pre-flight 요청의 결과를 캐시하는 시간 설정

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration); // 모든 경로에 대해 위 설정 적용
return source;
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
Expand All @@ -79,8 +101,4 @@ public WebSecurityCustomizer configureH2ConsoleEnable() {
return web -> web.ignoring()
.requestMatchers(PathRequest.toH2Console());
}




}

This file was deleted.

0 comments on commit ca16af1

Please sign in to comment.