1+ package cmf .commitField .global .security ;
2+
3+ import org .springframework .context .annotation .Bean ;
4+ import org .springframework .context .annotation .Configuration ;
5+ import org .springframework .security .config .annotation .web .builders .HttpSecurity ;
6+ import org .springframework .security .config .annotation .web .configuration .EnableWebSecurity ;
7+ import org .springframework .security .config .annotation .web .configurers .AbstractHttpConfigurer ;
8+ import org .springframework .security .config .http .SessionCreationPolicy ;
9+ import org .springframework .security .core .context .SecurityContextHolder ;
10+ import org .springframework .security .oauth2 .core .user .OAuth2User ;
11+ import org .springframework .security .web .SecurityFilterChain ;
12+
13+ @ Configuration
14+ @ EnableWebSecurity
15+ public class SecurityConfig {
16+ @ Bean
17+ protected SecurityFilterChain config (HttpSecurity http ) throws Exception {
18+
19+ //๋ก๊ทธ์ธ ๊ด๋ จ ์ค์
20+ http
21+ .oauth2Login (oauth2 -> oauth2
22+ .loginPage ("/login" ) // ๋ก๊ทธ์ธ ํ์ด์ง ์ง์
23+ .successHandler ((request , response , authentication ) -> {
24+ // ์ธ์ฆ ์ ๋ณด๊ฐ SecurityContext์ ์ถ๊ฐ๋๋ ๊ฒ์ ๋ณด์ฅ
25+ SecurityContextHolder .getContext ().setAuthentication (authentication );
26+
27+ // ๋๋ฒ๊น
: authentication ์ ๋ณด ํ์ธ
28+ System .out .println ("Authentication: " + authentication );
29+ System .out .println ("Principal: " + authentication .getPrincipal ());
30+
31+ if (authentication != null && authentication .getPrincipal () != null ) {
32+ //์ธ๊ฐ๊ฐ ์์ผ๋ฉด ์ ์ ์ ๋ณด๋ฅผ ์ ์ฅ
33+ OAuth2User principal = (OAuth2User ) authentication .getPrincipal ();
34+ String username = principal .getAttribute ("login" );
35+
36+ // ์ธ์
์ ์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์ถ๊ฐ
37+ request .getSession ().setAttribute ("user" , username );
38+
39+ response .sendRedirect ("/" ); // ๋ก๊ทธ์ธ ์ฑ๊ณต ํ ๋ฆฌ๋ค์ด๋ ํธ
40+ } else {
41+ // ์ธ์ฆ ์คํจ ์ ์ฒ๋ฆฌ
42+ response .sendRedirect ("/login?error=authenticationFailed" );
43+ }
44+ })
45+ )
46+ .sessionManagement (session -> session
47+ .sessionCreationPolicy (SessionCreationPolicy .IF_REQUIRED ) // ์ธ์
์ ์ฑ
์ค์
48+ .invalidSessionUrl ("/login?error=invalidSession" ) // ์ธ์
์ด ์ ํจํ์ง ์์ผ๋ฉด ์ด๋ํ URL
49+ .maximumSessions (1 ) // ํ๋์ ๊ณ์ ์ผ๋ก ํ ๋ฒ์ ๋ก๊ทธ์ธํ ์ ์๋๋ก ์ ํ
50+ .expiredUrl ("/login?error=sessionExpired" ) // ์ธ์
๋ง๋ฃ ํ ์ด๋ํ URL ์ค์
51+ );
52+
53+ //๋ก๊ทธ์์ ๊ด๋ จ ์ค์
54+ http
55+ .logout (logout -> logout
56+ .logoutUrl ("/logout" ) // ๋ก๊ทธ์์ URL ์ค์
57+ .logoutSuccessUrl ("/" ) // ๋ก๊ทธ์์ ์ฑ๊ณต ํ ์ด๋ํ URL
58+ .invalidateHttpSession (true ) // ๋ก๊ทธ์์ ์ ์ธ์
๋ฌดํจํ
59+ .clearAuthentication (true ) // ์ธ์ฆ ์ ๋ณด ์ง์ฐ๊ธฐ
60+ .deleteCookies ("JSESSIONID" ) // ์ธ์
์ฟ ํค ์ญ์
61+ );
62+ http
63+ .csrf (
64+ AbstractHttpConfigurer ::disable // CSRF ๋ณดํธ ๋นํ์ฑํ
65+ );
66+
67+ return http .build ();
68+ }
69+ }
0 commit comments