Spring

[Spring] Spring Security와 OAuth 2.0으로 구글 소셜 로그인 구현(1)

Kyko 2023. 8. 11. 18:20

 

이동욱 님의 '스프링부트와 aws로 혼자 구현하는 웹 서비스'를 참고하였습니다.

구글 로그인 기능과 소셜 서비스 기능을 사용하기 위해서는 구글 클라우드 플랫폼에서 신규 서비스를 등록해야 합니다.

신규 서비스를 등록하는 방법은 아래 참고자료에 잘 나와있습니다.

 

프로젝트 설정


 

1. application-oauth.yml 파일을 생성하고 발급받은 클라이언트 ID와 클라이언트 보안 비밀번호를 등록합니다.

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: 클라이언트 ID
            client-secret: 보안 비밀번호
            scope:
              - email
              - profile

 

2. application.yml에 application-oauth.yml의 설정들을 가져옵니다.

spring.profiles.include: oauth

 

구글 로그인 연동하기 - 유저 도메인 생성


1. 사용자 정보를 담당할 User Entity 생성합니다. (picture은 프로필 이미지를 의미)

@Getter
@NoArgsConstructor
@Entity
public class User extends BaseTimeEntiy {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = true)
    private String email;

    @Column
    private String picture;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Role role;

    @Builder
    public User(String name, String email, String picture, Role role) {
        this.name = name;
        this.email = email;
        this.picture = picture;
        this.role = role;
    }

    public User update(String name, String picture){
        this.name = name;
        this.picture = picture;
        return this;
    }

    public String getRoleKey(){
        return this.role.getKey();
    }
}

2. 각 사용자의 권한을 관리할 Role 클래스 생성

@Getter
@RequiredArgsConstructor
public enum Role {
    GUEST("ROLE_GUEST", "손님"), USER("ROLE_USER", "일반 사용자");
    private final String key;
    private final String title;
}

3. UserRepository 생성. findByEmail 메서드는 소셜 로그인으로 반환된 email을 통해 이미 생성된 사용자인지 여부 판단

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
}

 

참고자료


 

[Spring] 스프링 Oauth2 구글 로그인과 jpa 사용하여 유저 정보 데이터베이스에 저장 (OAuth2 스프링 1편

OAuth2 구글 로그인을 해 볼 예정인데 mysql 데이터베이스와 jpa를 사용하여 데이터베이스에 유저 정보를 저장해보려 한다. 먼저 OAuth2에 대해 간단하게 알아보자면 로그인, 회원가입 구현 과정의 번

growth-coder.tistory.com