DefaultOAuth2UserService 를 상속해서 커스텀 서비스 클래스 생성하기
loadUser 메서드를 재정의
package com.sample.oauthjwt.service;
import com.sample.oauthjwt.dto.CustomOAuth2User;
import com.sample.oauthjwt.dto.GoggleResponse;
import com.sample.oauthjwt.dto.NaverResponse;
import com.sample.oauthjwt.dto.OAuth2Response;
import com.sample.oauthjwt.dto.UserDto;
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);
// 어떤 소셜에서 온 값인지 (네이버인지, 구글인지) 판별
String registrationId = userRequest.getClientRegistration().getRegistrationId();
OAuth2Response oAuth2Response = null;
if(registrationId.equals("naver")){
oAuth2Response = new NaverResponse(oAuth2User.getAttributes());
}
else if(registrationId.equals("goggle")){
oAuth2Response = new GoggleResponse(oAuth2User.getAttributes());
}
else {
return null;
}
// 로그인 완료했을 때 작업
String username = oAuth2Response.getProvider() + " " + oAuth2Response.getProviderId();
UserDto userDto = new UserDto();
userDto.setName(oAuth2User.getName());
userDto.setUsername(username);
userDto.setRole("ROLE_USER");
// OAuth2User를 상속한 CustomOAuth2User 반환
return new CustomOAuth2User(userDto);
}
}
소셜 로그인 했을 때 각 사이트에서 주는 값
{
resultcode=00, message=success, response={id=123123123, name=개발자유미}
}
{
resultcode=00, message=success, id=123123123, name=개발자유미
}
package com.sample.oauthjwt.dto;
import java.util.Map;
public class NaverResponse implements OAuth2Response{
private final Map<String, Object> attriubute;
// 인자로 받는 attriubute 는 네이버에서 받는 응답 JSON 자체를 말함
public NaverResponse(Map<String, Object> attriubute){
this.attriubute = (Map<String, Object>) attriubute.get("response");
}
@Override
public String getProvider() {
return "naver";
}
@Override
public String getProviderId() {
return attriubute.get("id").toString();
}
@Override
public String getEmail() {
return attriubute.get("email").toString();
}
@Override
public String getName() {
return attriubute.get("name").toString();
}
}