11package cmf .commitField .global .security ;
22
3+ import cmf .commitField .domain .user .entity .CustomOAuth2User ;
4+ import cmf .commitField .domain .user .service .CustomOAuth2UserService ;
5+ import org .springframework .context .annotation .Bean ;
36import org .springframework .context .annotation .Configuration ;
7+ import org .springframework .security .config .annotation .web .builders .HttpSecurity ;
48import org .springframework .security .config .annotation .web .configuration .EnableWebSecurity ;
9+ import org .springframework .security .config .annotation .web .configurers .AbstractHttpConfigurer ;
10+ import org .springframework .security .config .http .SessionCreationPolicy ;
11+ import org .springframework .security .core .context .SecurityContextHolder ;
12+ import org .springframework .security .oauth2 .core .user .OAuth2User ;
13+ import org .springframework .security .web .SecurityFilterChain ;
14+ import org .springframework .security .web .util .matcher .AntPathRequestMatcher ;
15+
16+ import static org .springframework .security .config .Customizer .withDefaults ;
517
618@ Configuration
719@ EnableWebSecurity
820public class SecurityConfig {
9- // private final CustomOAuth2UserService customOAuth2UserService;
10- //
11- // public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) {
12- // this.customOAuth2UserService = customOAuth2UserService;
13- // }
14- //
15- // @Bean
16- // protected SecurityFilterChain config(HttpSecurity http) throws Exception {
17- // // 권한 설정
18- // http
19- // .authorizeHttpRequests(auth -> auth
20- // .requestMatchers("/actuator/**").permitAll() // actuator 엔드포인트 허용
21- // .anyRequest().authenticated() // 그 외 모든 요청은 인증 필요
22- // );
23- //
24- // //로그인 관련 설정
25- // http
26- // .oauth2Login(oauth2 -> oauth2
27- // .loginPage("/login") // 로그인 페이지 지정
28- // .successHandler((request, response, authentication) -> {
29- // // 인증 정보가 SecurityContext에 추가되는 것을 보장
30- // SecurityContextHolder.getContext().setAuthentication(authentication);
31- //
32- // CustomOAuth2User customUser = (CustomOAuth2User) authentication.getPrincipal();
33- //
34- // // 디버깅: authentication 정보 확인
35- // System.out.println("Authentication: " + authentication);
36- // System.out.println("Principal: " + authentication.getPrincipal());
37- //
38- // if (authentication != null && authentication.getPrincipal() != null) {
39- // //인가가 있으면 유저 정보를 저장
40- // OAuth2User principal = (OAuth2User) authentication.getPrincipal();
41- // String username = principal.getAttribute("login");
42- //
43- // // 세션에 사용자 정보를 추가
44- // request.getSession().setAttribute("user", username);
45- //
46- // response.sendRedirect("/"); // 로그인 성공 후 리다이렉트
47- // } else {
48- // // 인증 실패 시 처리
49- // response.sendRedirect("/login?error=authenticationFailed");
50- // }
51- // })
52- // )
53- // .sessionManagement(session -> session
54- // .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) // 세션 정책 설정
55- // .invalidSessionUrl("/login?error=invalidSession") // 세션이 유효하지 않으면 이동할 URL
56- // .maximumSessions(1) // 하나의 계정으로 한 번에 로그인할 수 있도록 제한
57- // .expiredUrl("/login?error=sessionExpired") // 세션 만료 후 이동할 URL 설정
58- // );
59- //
60- // //로그아웃 관련 설정
61- // http
62- // .logout(logout -> logout
63- // .logoutUrl("/logout") // 로그아웃 URL 설정
64- // .logoutSuccessUrl("/") // 로그아웃 성공 후 이동할 URL
65- // .invalidateHttpSession(true) // 로그아웃 시 세션 무효화
66- // .clearAuthentication(true) // 인증 정보 지우기
67- // .deleteCookies("JSESSIONID") // 세션 쿠키 삭제
68- // );
69- // http
70- // .csrf(
71- // AbstractHttpConfigurer::disable // CSRF 보호 비활성화
72- // );
73- //
74- // return http.build();
75- // }
21+ private final CustomOAuth2UserService customOAuth2UserService ;
22+
23+ public SecurityConfig (CustomOAuth2UserService customOAuth2UserService ) {
24+ this .customOAuth2UserService = customOAuth2UserService ;
25+ }
26+
27+ @ Bean
28+ protected SecurityFilterChain config (HttpSecurity http ) throws Exception {
29+ // 권한 설정
30+ http
31+ .cors (withDefaults ()) // CORS 설정 활성화
32+ .csrf (csrf -> csrf .disable ())
33+ .authorizeHttpRequests ((authorizeHttpRequests ) -> authorizeHttpRequests
34+ .requestMatchers (new AntPathRequestMatcher ("/**" )).permitAll ())
35+ ;
36+
37+ //로그인 관련 설정
38+ http
39+ .oauth2Login (oauth2 -> oauth2
40+ .loginPage ("/login" ) // 로그인 페이지 지정
41+ .successHandler ((request , response , authentication ) -> {
42+ // 인증 정보가 SecurityContext에 추가되는 것을 보장
43+ SecurityContextHolder .getContext ().setAuthentication (authentication );
44+
45+ CustomOAuth2User customUser = (CustomOAuth2User ) authentication .getPrincipal ();
46+
47+ // 디버깅: authentication 정보 확인
48+ System .out .println ("Authentication: " + authentication );
49+ System .out .println ("Principal: " + authentication .getPrincipal ());
50+
51+ if (authentication != null && authentication .getPrincipal () != null ) {
52+ //인가가 있으면 유저 정보를 저장
53+ OAuth2User principal = (OAuth2User ) authentication .getPrincipal ();
54+ String username = principal .getAttribute ("login" );
55+
56+ // 세션에 사용자 정보를 추가
57+ request .getSession ().setAttribute ("user" , username );
58+
59+ response .sendRedirect ("/" ); // 로그인 성공 후 리다이렉트
60+ } else {
61+ // 인증 실패 시 처리
62+ response .sendRedirect ("/login?error=authenticationFailed" );
63+ }
64+ })
65+ )
66+ .sessionManagement (session -> session
67+ .sessionCreationPolicy (SessionCreationPolicy .IF_REQUIRED ) // 세션 정책 설정
68+ .invalidSessionUrl ("/login?error=invalidSession" ) // 세션이 유효하지 않으면 이동할 URL
69+ .maximumSessions (1 ) // 하나의 계정으로 한 번에 로그인할 수 있도록 제한
70+ .expiredUrl ("/login?error=sessionExpired" ) // 세션 만료 후 이동할 URL 설정
71+ );
72+
73+ //로그아웃 관련 설정
74+ http
75+ .logout (logout -> logout
76+ .logoutUrl ("/logout" ) // 로그아웃 URL 설정
77+ .logoutSuccessUrl ("/" ) // 로그아웃 성공 후 이동할 URL
78+ .invalidateHttpSession (true ) // 로그아웃 시 세션 무효화
79+ .clearAuthentication (true ) // 인증 정보 지우기
80+ .deleteCookies ("JSESSIONID" ) // 세션 쿠키 삭제
81+ );
82+ http
83+ .csrf (
84+ AbstractHttpConfigurer ::disable // CSRF 보호 비활성화
85+ );
86+
87+ return http .build ();
88+ }
7689}
0 commit comments