whynot-here / whynot-here-api-server

whynot-here 서비스 API 서버
3 stars 0 forks source link

[BE] OAuth2 구글 로그인 구현 #98

Closed osj3474 closed 2 years ago

osj3474 commented 2 years ago

https://github.com/callicoder/spring-boot-react-oauth2-social-login-demo 를 참고하여 구현하였습니다.

< 서비스 로직 >

  1. SecurityConfig의 OAuth 설정으로 인하여 OAuth2LoginAuthenticationFilter 가 filter chain에 등록이 되고 ClientRegistrationRepository(우리 앱이 쓰는 client key, secret key 등의 정보), OAuth2AuthorizedClientRepository(다른 웹 요청이 와도 동일한 OAuth2 사용자 유지) 이 세팅 됩니다.

  2. {serverURL}/auth/login/google?redirect_uri={frontURL}로 OAuth2 로그인 요청을 받게 되면, clientID, redirectURL 등이 담긴 OAuth2AuthorizationRequest 를 바이트로 변환하여 인코딩 합니다. 그 값을 쿠키에 담아서 클라이언트로 전달합니다.

  3. 사용자가 자신의 ID, PW를 입력하여 로그인을 시도하면 OAuth2LoginAuthenticationFilter 의 attemptAuthentication 메서드를 통해서 로그인 처리를 합니다. 로그인에 성공을 했다면 OAuth2 제공자(구글)로 부터 state, code, scope 등을 전달받습니다. 그 뒤에 아까 클라이언트에 저장해두었던 OAuth2AuthorizationRequest 값을 HttpServletRequest의 쿠키에서 꺼내옵니다. null이 아니라면 받아온 state, code를 기반으로 직렬화를 거쳐 최종적으로 Authentication 객체를 반환하게 됩니다. (이 부분의 정확한 처리를 확인하고자 하신다면 OAuth2LoginAuthenticationFilter를 참고해주세요)

  4. 그렇게 로그인에 성공하면 OAuth2SuccessHandler 로 이동하게 되고, redirect_uri 를 넘겨 받았다면 그쪽으로 redirect_uri 를 넘겨 받지 않았다면 server에서 지정한 URL로 리다이렉트 시킵니다.