HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🪆
로그인 개선
🪆

로그인 개선

작성자
태그
Dev
속성
Aug 5, 2022 08:20 PM
 

1. 현재 로그인 코드 분석 및 문제점

 
현재 구글 소셜 로그인 코드 흐름
 
프론트에서 구글 로그인 url 요청 http://localhost:8080/oath2/authorization/google →
구글 인증 서버 인증 → 구글 리소스 서버 접근 → 유저 정보 저장 및 토큰 생성 → 토큰은 redirect URL에 Query String으로 발급
 
현재 redirectUrl은 bidmarket.vercel.app/auth?token=~~ 으로 하드코딩 되어있는상태
 
  • 현재 상황에서 토큰을 쿠키에 http only 옵션을 줘서 저장하고 메인페이지로 리다이렉트 시켜주고 싶음
  • 우선 현재 코드가 어떻게 작동하는지 파악 할것임
 

현재 security 코드 분석

WebSecurityConfig 파일
@Configuration @EnableWebSecurity public class WebSecurityConfig { ...생략 @Bean public SecurityFilterChain filterChain(Jwt jwt, HttpSecurity http, OAuth2AuthorizedClientRepository repository, OAuth2AuthenticationSuccessHandler handler ) throws Exception { http.authorizeRequests() ...생략 /** * OAuth2 설정 */ .oauth2Login() .authorizationEndpoint() .authorizationRequestRepository(authorizationRequestRepository()) .and() .successHandler(handler) .authorizedClientRepository(repository) .and() ...생략 return http.build(); } }
OAuth2AuthenticationSuccessHandler 파일
package com.saiko.bidmarket.common.oauth2; import java.io.IOException; import java.nio.charset.StandardCharsets; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import com.saiko.bidmarket.common.jwt.Jwt; import com.saiko.bidmarket.user.entity.User; import com.saiko.bidmarket.user.service.UserService; public class OAuth2AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Jwt jwt; private final UserService userService; public OAuth2AuthenticationSuccessHandler(Jwt jwt, UserService userService) { this.jwt = jwt; this.userService = userService; } @Override public void onAuthenticationSuccess( HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { if (authentication instanceof OAuth2AuthenticationToken) { OAuth2AuthenticationToken oauth2Token = (OAuth2AuthenticationToken)authentication; OAuth2User principal = oauth2Token.getPrincipal(); log.debug("Message {}, {}", principal.getName(), principal.getAttributes()); String registrationId = oauth2Token.getAuthorizedClientRegistrationId(); User user = processUserOAuth2UserJoin(principal, registrationId); String loginSuccessJson = generateLoginSuccessJson(user); response.setContentType("application/json;charset=UTF-8"); response.setContentLength(loginSuccessJson.getBytes(StandardCharsets.UTF_8).length); response.sendRedirect("http://localhost:3000/auth?" + loginSuccessJson); } } private User processUserOAuth2UserJoin(OAuth2User oAuth2User, String registrationId) { return userService.join(oAuth2User, registrationId); } private String generateLoginSuccessJson(User user) { String token = generateToken(user); log.debug("Jwt({}) created for oauth2 login user {}", token, user.getId()); return "token=" + token; } private String generateToken(User user) { return jwt.sign(Jwt.Claims.from(user.getId(), new String[]{"ROLE_USER"})); } }
 
  1. 로그인 요청 URL http://localhost:8080/oauth2/authorization/google
 
HttpCookieOAuth2AuthorizationRequestRepository 에 걸린 디버그
notion image
notion image
notion image
 
 
 
  • authorization_uri = https://accounts.google.com/o/oauth2/v2/auth
  • redirect_uri = http://localhost:8080/login/oauth2/code/google
AUTHORIZATION_REQUEST 쿠키 생성
구글 서버에 AUTHORIZATION_CODE를 요청하는 쿠키를 생성
notion image
 
OAuth2 사용해서 react와 함께 소셜로그인 기능 만들기
로그인 창에서 많이 볼 수 있는 소셜로그인 기능을 만들어보자. 여기서 인증이 완료된 후 생성한 토큰을 어떻게 프론트엔드로 다시 보낼까에 대한 부분이 어려웠다 😵‍💫 (결론은 쿠키를 통해서 확인된 uri에 생성된 토큰 붙인 새로운 uri 생성하고 다시 보내기...!) 구글 프로젝트 계정 만들기 https://console.cloud.google.com/apis 먼저 홈페이지에 들어가서 로그인을 해준 후 , API 및 서비스 항목으로 들어간다.
OAuth2 사용해서 react와 함께 소셜로그인 기능 만들기
https://dodop-blog.tistory.com/249
OAuth2 사용해서 react와 함께 소셜로그인 기능 만들기
 
github.dev
https://github.dev/callicoder/spring-boot-react-oauth2-social-login-demo/blob/master/spring-social/src/main/java/com/example/springsocial/SpringSocialApplication.java
스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현
스프링 시큐리티(Spring Security)는 막강한 인증과 인과(혹인 권한 부여) 기능을 가진 프레임워크입니다. 사실상 스프링 기반의 애플리케이션에서는 보안을 위한 표준이라고 보면 됩니다. 필터 기반의 보안 기능을 구현하는 것보다 스프링 시큐리티를 통해 구현하는 것을 적극적으로 권하고 있습니다. OAuth 하지만 오픈 아이디는 표준스펙이 존재하지 않았기 때문에 제공자마다 서로 다른 프로토콜을 제공하여 여러 오픈 아이디를 제공하기 위해선 각 규격별로 연동을 만들어야 했고, 일부 프로토콜에선 보안 이슈가 많이 나오기도 했습니다.
스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현
https://velog.io/@swchoi0329/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0%EC%99%80-OAuth-2.0%EC%9C%BC%EB%A1%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EA%B8%B0%EB%8A%A5-%EA%B5%AC%ED%98%84
스프링 시큐리티와 OAuth 2.0으로 로그인 기능 구현
www.baeldung.com
https://www.baeldung.com/spring-security-5-oauth2-login