오래 못 할 짓 하지 않기

[ Spring boot Security ] [ Token X ] 3. Oauth 처리 Service stage 본문

혼자하기/연습 1) OAuth

[ Spring boot Security ] [ Token X ] 3. Oauth 처리 Service stage

쫑알bot 2024. 3. 3. 14:17
728x90

저번 시간에 구글 로그인까지는 됐다.

근데 로그인 됐는데 그 정보는 들어온 순간 휘발되어 날라감.

 

그걸 처리하는 service단이 필요하다.

 

 

 

 

로그인한 유저가 들어와서 Provider가 naver인지 google인지 구분하여 그에 맞게 처리를 한다.

 

 

구분해야 하는 이유는??

 

구글과 네이버에서 주는 데이터 형식이 다르기 때문에

 

코드▼

더보기
package com.example.oauthnojwt.service;

import com.example.oauthnojwt.dto.GoogleResponse;
import com.example.oauthnojwt.dto.NaverResponse;
import com.example.oauthnojwt.dto.OAuth2Response;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {

        OAuth2User oAuth2User = super.loadUser(userRequest);
        System.out.println(oAuth2User.getAttributes());

        String registrationId = userRequest.getClientRegistration().getRegistrationId();
        OAuth2Response oAuth2Response = null;
        if (registrationId.equals("naver")) {

            oAuth2Response = new NaverResponse(oAuth2User.getAttributes());
        }
        else if (registrationId.equals("google")) {

            oAuth2Response = new GoogleResponse(oAuth2User.getAttributes());
        }
        else {

            return null;
        }


        //추후 작성
    }
}

 


 

가장 먼저 OAuth로그인을 했을 때 처리해야하는 정보들에 대한 로직을 Interface로 만들고 

 

네이버, 구글에서 이를 implements해서 사용한다.

 

 

네이버에서 들어온 정보 처리

 

 

구글에서 들어온 정보 처리

 

다른 점

 

1) 

네이버 : Constructor 를 호출할 때 attribute에 response 라는 key의 값을 가져옴

구글    : 그냥 attibute 가져옴

 

2) 

네이버 : providerId = id

구글 : providerId = sub

 

 


 

여기까지 했으면 security config에 등록을 해줘야한다.

 

이건 나도 식을 모르겠으니 그냥 긁어가자

 

    http.oauth2Login(
        (oauth2) ->
            oauth2.userInfoEndpoint(
                (userInfoEndpointConfig ->
                    userInfoEndpointConfig.userService(customOAuth2UserService))));