본문 바로가기

백엔드 스터디

스프링 OAuth2 로그인 구현하기 1

최근 프로젝트에서  많은 서비스에서 활용하는 OAuth2 소셜 로그인 방식을 사용해보기로 해서 Spring Boot에서 직접 구현해보기로 결심했습니다.

 

OAuth2 로그인을 직접 만들어보는 건 처음이라서 혼자 공식문서만 보고 따라가기엔 조금 막막하더라고요.
그래서 이번에는 유튜브 “개발자 유미” 님의 스프링 OAuth2 소셜 로그인 강의를 참고해서 한 단계씩 실습해봤어요.

 

https://www.youtube.com/playlist?list=PLJkjrxxiBSFBGk0b931ZkCVlNUo7sFisu

 

스프링 OAuth2 클라이언트 세션

스프링 시큐리티에서 OAuth2를 활용한 소셜 로그인을 진행하고 인가 받은 권한을 세션 및 DB에 저장하는 방법을 구현하는 프로젝트입니다.

www.youtube.com

실습 순서 

대략적인 실습 순서는 다음과 같습니다.

 

  •  1 : 실습 목표 및 간단 동작 원리
    • 전체적인 목표와 OAuth2 인증의 개념 설명
  •  2 : 프로젝트 생성 및 의존성 추가
    • 스프링 부트 프로젝트 생성
    • Gradle/Maven에서 필요한 라이브러리 추가
  •  3 : 동작 모식도
    • OAuth2 로그인 플로우(모식도) 이해
  •  4 : 변수 역할
    • application.yml/properties에 들어가는 변수 의미와 역할 설명
  •  5 : Security Config 설정
    • 스프링 시큐리티 보안 설정 적용 방법
  •  6 : 네이버 소셜 로그인 신청
    • 네이버 개발자 센터에서 앱 등록 및 Client ID/Secret 발급
  •  7 : 구글 소셜 로그인 신청
    • 구글 개발자 콘솔에서 OAuth2 등록 및 정보 발급
  •  8 : OAuth2UserService 구현
    • CustomOauth2UserService 클래스 직접 구현
    • 구글/네이버에서 받은 유저 정보 가공
  •  9 : 로그인 완료
    • 로그인 후 사용자 정보 받아서 화면에 표시
  •  10 : 유저 정보 DB 저장
    • 로그인한 사용자 정보를 데이터베이스에 저장
  •  11 : 로그인 및 DB 저장 테스트
    • 실제 동작 테스트
  •  12 : 커스텀 로그인 페이지
    • 기본 제공 로그인 화면 대신 내 페이지로 커스터마이즈
  •  13 : Client Registration
    • 클라이언트 등록 개념 및 설정 방법
  •  14 : OAuth2AuthorizationRequestRedirectFilter
    • 인증 요청 리다이렉트 처리 필터 동작 설명
  •  15 : OAuth2LoginAuthenticationFilter
    • 인증 결과 처리 필터의 동작
  •  16 : OAuth2AuthorizedClientService
    • 인증된 클라이언트 정보 관리 서비스 설명

 

 

오늘은 먼저 소셜 로그인 신청 파트까지 실습해봤습니다.

 

1. 의존성 추가

일단 프로젝트를 생성할 때 필요한 의존성들을 추가해줬습니다.

dependencies {
	//implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
	implementation 'org.springframework.boot:spring-boot-starter-security'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	//runtimeOnly 'com.mysql:mysql-connector-j'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework.security:spring-security-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

 

2. 네이버, 구글 클라이언트 ID 발급 받기

 

그 후에 네이버 Developers 사이트에서 애플리케이션 등록했습니다. https://developers.naver.com/main/ 

클라이언트 ID를 발급받을 수 있습니다.

 

구글도 해당 사이트에서 클라이언트 ID를 받을 수 있습니다. https://cloud.google.com/

구글 테스트 완료

 

3. application.properties 설정

spring.application.name=OAuthSession

#registration
spring.security.oauth2.client.registration.naver.client-name=naver
spring.security.oauth2.client.registration.naver.client-id=cPtVOubBnndSYDFiAXdB
spring.security.oauth2.client.registration.naver.client-secret=Jtyjm7nKiY
spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver
spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.naver.scope=name,email

#provider
spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize
spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token
spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me
spring.security.oauth2.client.provider.naver.user-name-attribute=response


#registration
spring.security.oauth2.client.registration.google.client-name=google
spring.security.oauth2.client.registration.google.client-id=201341637130-lmpfoaogsempij2b0b42oaclr8d8a16d.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=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
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.google.scope=profile,email

 

네이버와 구글의 소셜 로그인 설정을 해주었습니다.


네이버는 식 Provider가 아니라서 별도의 provider URI들을 반드시 추가해줘야 합니다.

구글은 공식 Provider라서 provider 관련 추가 설정이 필요 없었습니다.

 

실습하면서 느낀 점

  • 네이버는 provider 설정을 빼먹으면 에러가 발생하고,
    구글은 비교적 설정은 단순했지만 api 키를 발급받는 과정이 더 복잡했습니다.
  • 각 플랫폼마다 redirect URI가 달라서 콘솔과 프로젝트 설정(application.properties)이 반드시 맞아야 합니다.