Social Login - 코드 구현 - Model
서비스 제공자 별로(
Google,Naver,Keycloak) 사용자 정보를 담는 클래스를 만들어야 한다.서비스 제공자 마다 사용자의 속성을 가져오는 방식에 차이가 있다.
ProviderUser
public interface ProviderUser {
String getId();
String getUsername();
String getPassword();
String getEmail();
String getProvider();
List<? extends GrantedAuthority> getAuthorities();
Map<String, Object> getAttributes();
}공통적인 속성을 가져오는 인터페이스
OAuth2ProviderUser
public abstract class OAuth2ProviderUser implements ProviderUser{
protected Map<String, Object> attributes;
protected OAuth2User oAuth2User;
protected ClientRegistration clientRegistration;
public OAuth2ProviderUser(Map<String, Object> attributes, OAuth2User oAuth2User, ClientRegistration clientRegistration) {
this.attributes = attributes;
this.oAuth2User = oAuth2User;
this.clientRegistration = clientRegistration;
}
@Override
public String getPassword() {
return UUID.randomUUID().toString().substring(0, 8);
}
@Override
public String getProvider() {
return clientRegistration.getRegistrationId();
}
@Override
public String getEmail() {
return (String) getAttributes().get("email");
}
@Override
public List<? extends GrantedAuthority> getAuthorities() {
return oAuth2User.getAuthorities()
.stream()
.map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
.toList();
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
}
서비스 제공자가 사용자의 정보를 전달할 때 공통적으로 사용하는 동일한 속성과 약간씩 차이나는 속성들이 있다.
공통적인 부분은 하나의 추상 클래스로 묶어주고, 각각 차이나는 속성은 개별 클래스에서 정의하도록 한다.
이 부모 클래스의 속성들은 자식 클래스의 생성자에서 넘어온 정보들이다.
GoogleUser
생성자에서 부모 클래스에게 OAuth2User에 담긴
Attributes(사용자 정보)를 넘겨주었기 때문에 자식 클래스에서 자신에게 맞는Attributes를 참조할 수 있다.
NaverUser
네이버 같은 경우 사용자의 정보가
response로 한 번 감싸져 응답이 오기 때문에 부모 클래스에게attributes를 넘길 때response를 풀어주어야 한다.그래야 원하는 속성에 접근할 수 있다.
KeycloakUser
User
데이터베이스에 저장될 User 객체
Last updated