From c4a5a902a6fed9e2aae34d101e8b4ddad4cb7166 Mon Sep 17 00:00:00 2001 From: JjungminLee Date: Wed, 23 Aug 2023 11:09:26 +0900 Subject: [PATCH] fix:oAuth2 handler --- .../onnaback/global/config/CorsConfig.java | 29 ------------ .../handler/OAuth2LoginSuccessHandler.java | 47 +------------------ .../global/security/SecurityConfig.java | 25 +++++++--- 3 files changed, 21 insertions(+), 80 deletions(-) delete mode 100644 src/main/java/com/onna/onnaback/global/config/CorsConfig.java diff --git a/src/main/java/com/onna/onnaback/global/config/CorsConfig.java b/src/main/java/com/onna/onnaback/global/config/CorsConfig.java deleted file mode 100644 index 54e41d6..0000000 --- a/src/main/java/com/onna/onnaback/global/config/CorsConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.onna.onnaback.global.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; - -import java.util.List; - -@Configuration -public class CorsConfig { - - @Bean - public CorsConfigurationSource corsConfigurationSource() { - CorsConfiguration config = new CorsConfiguration(); - - config.setAllowCredentials(true); - config.setAllowedOrigins(List.of("http://localhost:3000")); - config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); - config.setAllowedHeaders(List.of("*")); - config.setExposedHeaders(List.of("*")); - - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", config); - return source; - } -} diff --git a/src/main/java/com/onna/onnaback/global/oauth/handler/OAuth2LoginSuccessHandler.java b/src/main/java/com/onna/onnaback/global/oauth/handler/OAuth2LoginSuccessHandler.java index decca63..1ba9484 100644 --- a/src/main/java/com/onna/onnaback/global/oauth/handler/OAuth2LoginSuccessHandler.java +++ b/src/main/java/com/onna/onnaback/global/oauth/handler/OAuth2LoginSuccessHandler.java @@ -32,52 +32,9 @@ public class OAuth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHan @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { log.info("OAuth2 Login 성공!"); - try { - CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal(); - - // User의 Role이 GUEST일 경우 처음 요청한 회원이므로 회원가입 페이지로 리다이렉트 - if(oAuth2User.getRole() == Role.GUEST) { -// String accessToken = jwtService.createAccessToken(oAuth2User.getEmail()); -// response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken); -// response.sendRedirect("oauth2/sign-up"); // 프론트의 회원가입 추가 정보 입력 폼으로 리다이렉트 -// -// jwtService.sendAccessAndRefreshToken(response, accessToken, null); - String targetUrl = UriComponentsBuilder.fromUriString(redirectUrl) - .queryParam("email", (String) oAuth2User.getAttribute("email")) - .build() - .encode(StandardCharsets.UTF_8) - .toUriString(); - // 회원가입 페이지로 리다이렉트 시킨다. - getRedirectStrategy().sendRedirect(request, response, targetUrl); - - } else { -// loginSuccess(response, oAuth2User); // 로그인에 성공한 경우 access, refresh 토큰 생성 - // accessToken을 쿼리스트링에 담는 url을 만들어준다. - System.err.println(redirectUrl); - String targetUrl = UriComponentsBuilder.fromUriString(redirectUrl) - .queryParam("accessToken", jwtService.createAccessToken(oAuth2User.getEmail())) - .build() - .encode(StandardCharsets.UTF_8) - .toUriString(); - log.info("redirect 준비"); - // 로그인 확인 페이지로 리다이렉트 시킨다. - getRedirectStrategy().sendRedirect(request, response, targetUrl); - } - } catch (Exception e) { - throw e; - } + CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal(); + response.getWriter().write( "Bearer "+jwtService.createAccessToken(oAuth2User.getEmail())); } - - - private void loginSuccess(HttpServletResponse response, CustomOAuth2User oAuth2User) throws IOException { - String accessToken = jwtService.createAccessToken(oAuth2User.getEmail()); - String refreshToken = jwtService.createRefreshToken(); - response.addHeader(jwtService.getAccessHeader(), "Bearer " + accessToken); - response.addHeader(jwtService.getRefreshHeader(), "Bearer " + refreshToken); - - jwtService.sendAccessAndRefreshToken(response, accessToken, refreshToken); - jwtService.updateRefreshToken(oAuth2User.getEmail(), refreshToken); - } } diff --git a/src/main/java/com/onna/onnaback/global/security/SecurityConfig.java b/src/main/java/com/onna/onnaback/global/security/SecurityConfig.java index 7c65fcb..ffa3554 100644 --- a/src/main/java/com/onna/onnaback/global/security/SecurityConfig.java +++ b/src/main/java/com/onna/onnaback/global/security/SecurityConfig.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.onna.onnaback.domain.member.adapter.out.persistence.MemberRepository; -import com.onna.onnaback.global.config.CorsConfig; import com.onna.onnaback.global.jwt.JwtService; import com.onna.onnaback.global.jwt.LoginService; import com.onna.onnaback.global.jwt.filter.CustomJsonUsernameAuthenticationFilter; @@ -30,6 +29,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import javax.servlet.Filter; +import java.util.List; @Configuration @EnableWebSecurity @@ -43,7 +43,6 @@ public class SecurityConfig { private final OAuth2LoginFailureHandler oAuth2LoginFailureHandler; private final CustomOAuth2UserService customOAuth2UserService; - private final CorsConfig corsConfig; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @@ -53,9 +52,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin().disable() // FormLogin 사용 X .httpBasic().disable() // httpBasic 사용 X .csrf().disable() // csrf 보안 사용 X - .cors() - .and() - .headers().frameOptions().disable() + .cors().configurationSource(corsConfigurationSource()) .and() // 세션 사용하지 않으므로 STATELESS로 설정 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) @@ -66,7 +63,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //== URL별 권한 관리 옵션 ==// .authorizeRequests() .antMatchers("/swagger-ui/**","/v3/api-docs", "/swagger-resources/**").permitAll() - .antMatchers("/login/*","/login/oauth2/code/*","/login/success/*").permitAll() + .antMatchers("/login/*","/login/oauth2/code/*","/login/success/**").permitAll() .antMatchers("/sign-up").permitAll() // 회원가입 접근 가능 .anyRequest().authenticated() // 위의 경로 이외에는 모두 인증된 사용자만 접근 가능 .and() @@ -141,6 +138,22 @@ public Filter jwtAuthenticationProcessingFilter() { return jwtAuthenticationFilter; } + // CORS 허용 적용 + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration config = new CorsConfiguration(); + + config.setAllowCredentials(true); + config.setAllowedOrigins(List.of("http://localhost:3000")); + config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")); + config.setAllowedHeaders(List.of("*")); + config.setExposedHeaders(List.of("*")); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + return source; + } + } \ No newline at end of file