Skip to content

Commit

Permalink
fix:oAuth2 handler
Browse files Browse the repository at this point in the history
  • Loading branch information
JjungminLee committed Aug 23, 2023
1 parent fde9822 commit c4a5a90
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 80 deletions.
29 changes: 0 additions & 29 deletions src/main/java/com/onna/onnaback/global/config/CorsConfig.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -30,6 +29,7 @@
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.Filter;
import java.util.List;

@Configuration
@EnableWebSecurity
Expand All @@ -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 {
Expand All @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -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;
}



}

0 comments on commit c4a5a90

Please sign in to comment.