-
Notifications
You must be signed in to change notification settings - Fork 0
bug(#80) : session 오류 해결 #81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,21 +3,17 @@ | |
| import hello.cluebackend.domain.user.service.CustomOAuth2UserService; | ||
| import hello.cluebackend.global.security.jwt.RefreshTokenService; | ||
| import jakarta.servlet.http.Cookie; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.core.annotation.Order; | ||
| import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; | ||
| import org.springframework.security.config.Customizer; | ||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
| import org.springframework.security.config.http.SessionCreationPolicy; | ||
| import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.web.cors.CorsConfiguration; | ||
| import org.springframework.web.cors.CorsConfigurationSource; | ||
|
|
||
| import java.util.Collections; | ||
|
|
||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
|
|
@@ -26,34 +22,64 @@ public class SecurityConfig { | |
| private final CustomOAuth2UserService customOAuth2UserService; | ||
| private final CustomSuccessHandler customSuccessHandler; | ||
| private final JWTUtil jwtUtil; | ||
| private final RefreshTokenService refreshTokenService; | ||
|
|
||
| public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomSuccessHandler customSuccessHandler, JWTUtil jwtUtil) { | ||
| public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, | ||
| CustomSuccessHandler customSuccessHandler, | ||
| JWTUtil jwtUtil, | ||
| RefreshTokenService refreshTokenService) { | ||
| this.customOAuth2UserService = customOAuth2UserService; | ||
| this.customSuccessHandler = customSuccessHandler; | ||
| this.jwtUtil = jwtUtil; | ||
| this.refreshTokenService = refreshTokenService; | ||
| } | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http, RefreshTokenService refreshTokenService) throws Exception { | ||
| @Order(0) | ||
| public SecurityFilterChain loginChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .securityMatcher("/oauth2/**", "/login/oauth2/**", "/first-register", "/register", "/api/timetable/**") | ||
| .cors(Customizer.withDefaults()) | ||
| .csrf(csrf -> csrf.disable()) | ||
| .authorizeHttpRequests(a -> a | ||
| .requestMatchers("/oauth2/**", "/login/oauth2/**", "/first-register", "/register", "/api/timetable/**") | ||
| .permitAll() | ||
| .anyRequest().permitAll() | ||
| ) | ||
| .oauth2Login(o -> o | ||
| .userInfoEndpoint(u -> u.userService(customOAuth2UserService)) | ||
| .successHandler(customSuccessHandler) | ||
| ) | ||
| .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)); | ||
|
|
||
| return http.build(); | ||
| } | ||
|
|
||
| @Bean | ||
| @Order(1) | ||
| public SecurityFilterChain apiChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .cors(Customizer.withDefaults()) | ||
| .csrf(csrf -> csrf.disable()) | ||
| .logout(logout -> logout | ||
| .logoutUrl("/logout") | ||
| .addLogoutHandler((request, response, authentication) -> { | ||
| String refreshToken = null; | ||
| Cookie[] cookies = request.getCookies(); | ||
| if (cookies == null) return; | ||
| for (Cookie cookie : cookies) { | ||
| if (cookie.getName().equals("refresh_token")) { | ||
| refreshToken = cookie.getValue(); | ||
| if (cookies != null) { | ||
| for (Cookie cookie : cookies) { | ||
| if ("refresh_token".equals(cookie.getName())) { | ||
| refreshToken = cookie.getValue(); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| if (refreshToken == null) { | ||
| throw new AuthenticationCredentialsNotFoundException("refresh_token 쿠키가 존재하지 않습니다."); | ||
| } | ||
| refreshTokenService.deleteByRefresh(refreshToken); | ||
| String accessToken = ""; | ||
| response.setHeader("Authorization", "Bearer " + accessToken); | ||
|
|
||
| response.setHeader("Authorization", "Bearer "); | ||
|
|
||
| Cookie refreshTokenCookie = new Cookie("refresh_token", null); | ||
| refreshTokenCookie.setMaxAge(0); | ||
|
|
@@ -63,77 +89,18 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http, RefreshTokenSe | |
| .deleteCookies("JSESSIONID", "refresh_token") | ||
| .invalidateHttpSession(true) | ||
| .clearAuthentication(true) | ||
| .logoutSuccessHandler((request, response, authentication) -> { | ||
| response.setStatus(HttpServletResponse.SC_OK); | ||
| }) | ||
|
|
||
| ); | ||
|
|
||
| http | ||
| .cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() { | ||
| @Override | ||
| public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { | ||
| CorsConfiguration configuration = new CorsConfiguration(); | ||
| configuration.setAllowedOriginPatterns(Collections.singletonList("http://localhost:3000")); | ||
| configuration.setAllowedMethods(Collections.singletonList("*")); | ||
| configuration.setAllowedHeaders(Collections.singletonList("*")); | ||
| configuration.setExposedHeaders(Collections.singletonList("Authorization")); | ||
| configuration.setAllowCredentials(true); | ||
| configuration.setMaxAge(3600L); | ||
| return configuration; | ||
| } | ||
| })); | ||
|
|
||
| // csrf disable | ||
| http | ||
| .csrf(auth->auth.disable()); | ||
|
|
||
| // Form 로그인 방식 disable | ||
| http | ||
| .formLogin(auth->auth.disable()); | ||
|
|
||
| // HTTP Basic 인증 방식 disable | ||
| http | ||
| .httpBasic(auth->auth.disable()); | ||
|
|
||
| // JWTFilter 추가 | ||
| http | ||
| // JWT 토큰 만료시 다시 로그인을 할 경우 JWT 토큰이 없어서 거절하게 되어 무한루프에 빠지게 됨 | ||
| // .addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class); | ||
| .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class); | ||
| // .addFilterAfter(new JWTFilter(jwtUtil),OAuth2LoginAuthenticationFilter.class); | ||
|
|
||
| // oauth2 | ||
| http | ||
| // .oauth2Login(Customizer.withDefaults()); | ||
| .oauth2Login(oauth2 -> oauth2 | ||
| .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig | ||
| .userService(customOAuth2UserService)) | ||
| .successHandler(customSuccessHandler)); | ||
|
|
||
| // 경로별 인가 작업 | ||
| http | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers("/", "/refresh-token", "/register", "/first-register", "/api/timetable/**", "/test", | ||
| "/h2-console/**", | ||
| "/favicon.ico", | ||
| "/error", | ||
| "/swagger-ui/**", | ||
| "/swagger-resources/**", | ||
| "/v3/api-docs/**").permitAll() | ||
|
|
||
| .anyRequest().authenticated()); | ||
|
|
||
|
|
||
| http | ||
| .securityMatcher("/first-register", "/register","api/timetable/**") | ||
| .sessionManagement(session -> | ||
| session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) | ||
| .logoutSuccessHandler((request, response, authentication) -> response.setStatus(HttpServletResponse.SC_OK)) | ||
| ) | ||
| .authorizeHttpRequests(a -> a | ||
| .requestMatchers( | ||
| "/", "/refresh-token", "/h2-console/**", | ||
| "/favicon.ico", "/error", | ||
| "/swagger-ui/**", "/swagger-resources/**", "/v3/api-docs/**" | ||
| ).permitAll() | ||
| .anyRequest().authenticated() | ||
| ) | ||
| .securityMatcher("/**") | ||
| .sessionManagement(session -> | ||
| session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
| ); | ||
| .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class) | ||
| .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); | ||
|
Comment on lines
+102
to
+103
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion JWT 필터 삽입 위치를
아래와 같이 수정하고 import를 추가하세요. +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
...
- .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class)
+ .addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class)🤖 Prompt for AI Agents |
||
|
|
||
| return http.build(); | ||
| } | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,4 +10,4 @@ spring: | |
|
|
||
| logging: | ||
| level: | ||
| root: debug | ||
| root: debug | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
login 체인에 API 경로 포함 — 인증 우회 위험.
loginChain.securityMatcher와authorizeHttpRequests에/api/timetable/**가 포함되어 Order(0) 체인이 먼저 매치되면 JWT가 적용되는apiChain까지 도달하지 못하고 무조건 permitAll이 됩니다. 의도치 않은 익명 접근/권한 우회가 발생할 수 있습니다.다음과 같이
/api/timetable/**를 login 체인에서 제거하고, 공개가 필요하다면 api 체인에서 명시적으로 permitAll 하십시오.그리고 api 체인 쪽에 공개가 맞다면 추가:
📝 Committable suggestion
🤖 Prompt for AI Agents