package com.workflow;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.cors(cors -> {}) // 아래 CORS Bean 필요
// ✅ React 연동 중엔 폼로그인/기본인증 끄기 (리다이렉트 방지)
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
// ✅ 인증 실패시 302 말고 401/403
.exceptionHandling(ex -> ex
.authenticationEntryPoint((req, res, e) -> res.sendError(401))
.accessDeniedHandler((req, res, e) -> res.sendError(403))
)
// ✅ 지금은 일단: auth API만 열고, 나머지 API 보호
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
);
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("<http://localhost:5173>"));
config.setAllowedMethods(List.of("GET","POST","PUT","PATCH","DELETE","OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setExposedHeaders(List.of("Authorization"));
config.setAllowCredentials(false); // JWT를 헤더로만 쓸 거면 false 권장
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
VS code에 추가(vite.config.js)
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': '<http://localhost:8081>'
}
}
})
그럼 리액트에서 아래와 같이 호출하면 됨.
fetch("/api/health")
연결 확인용 코드 추가
JWT를 붙일 때 추가 할것
// 세션 끄기
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// JST 필터 추가
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)