배너 이미지

OAuth2 기반 Google & Kakao 로그인 구축 방법

2025. 6. 30. 23:47·CS공부/Java & Spring

✅ 사전 준비

📌 공통

  • Spring Boot (spring-boot-starter-oauth2-client)
  • Redirect URI: https://yourdomain.com/login/oauth2/code/{provider}

🧩 1. Google OAuth2 로그인 구축

🔧 Google Cloud 설정

  1. Google Cloud Console 접속

  2. OAuth 동의 화면 구성 (앱 이름, 사용자 이메일 등)

  3. OAuth 2.0 클라이언트 ID 생성

    • 애플리케이션 유형: 웹 애플리케이션
    • 승인된 리디렉션 URI:
      https://yourdomain.com/login/oauth2/code/google
  4. 클라이언트 ID, 클라이언트 시크릿 발급

⚙️ application.yml 설정

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_GOOGLE_CLIENT_ID
            client-secret: YOUR_GOOGLE_CLIENT_SECRET
            scope: profile, email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
            user-name-attribute: sub

🧩 2. Kakao OAuth2 로그인 구축

🔧 Kakao 개발자 설정

  1. Kakao Developers 접속

  2. 애플리케이션 생성

  3. 플랫폼 > 웹 사이트 도메인 등록: https://yourdomain.com

  4. Redirect URI 등록:
    https://yourdomain.com/login/oauth2/code/kakao

  5. REST API 키 획득

⚙️ application.yml 설정

spring:
  security:
    oauth2:
      client:
        registration:
          kakao:
            client-id: YOUR_KAKAO_REST_API_KEY
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            client-authentication-method: POST
            authorization-grant-type: authorization_code
            scope:
              - profile_nickname
              - account_email
            client-name: Kakao
        provider:
          kakao:
            authorization-uri: https://kauth.kakao.com/oauth/authorize
            token-uri: https://kauth.kakao.com/oauth/token
            user-info-uri: https://kapi.kakao.com/v2/user/me
            user-name-attribute: id

🎯 커스터마이징

✅ 사용자 정보 매핑 (OAuth2UserService)

@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        String registrationId = userRequest.getClientRegistration().getRegistrationId();

        Map<String, Object> attributes = oAuth2User.getAttributes();
        if (registrationId.equals("kakao")) {
            attributes = (Map<String, Object>) attributes.get("kakao_account");
        }

        return new DefaultOAuth2User(
            Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
            attributes,
            "email"
        );
    }
}

✅ Security 설정

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests()
                .requestMatchers("/", "/login/**", "/oauth2/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .oauth2Login()
                .userInfoEndpoint()
                    .userService(customOAuth2UserService);
        return http.build();
    }

    @Autowired
    private CustomOAuth2UserService customOAuth2UserService;
}

🔐 실무 팁

  • Redirect URI는 반드시 https 기반이어야 함
  • HttpOnly + Secure 쿠키 사용 고려
  • JWT 발급 연동 시 OAuth 로그인 후 accessToken 생성하도록 구현 가능
  • 회원가입 연동 시 이메일 중복 처리 / 닉네임 생성 로직 필요

'CS공부 > Java & Spring' 카테고리의 다른 글

collect(Collectors.toList()) vs Stream.toList()  (1) 2025.06.07
문자열 클래스 정리: String vs StringBuffer vs StringBuilder  (0) 2025.05.25
JWT 인증 및 토큰 기반 인증 시스템 정리  (0) 2025.04.28
즉시 로딩(Eager Loading)과 지연 로딩(Lazy Loading)  (0) 2025.04.23
Spring Boot의 Bean과 어노테이션  (1) 2025.04.23
'CS공부/Java & Spring' 카테고리의 다른 글
  • collect(Collectors.toList()) vs Stream.toList()
  • 문자열 클래스 정리: String vs StringBuffer vs StringBuilder
  • JWT 인증 및 토큰 기반 인증 시스템 정리
  • 즉시 로딩(Eager Loading)과 지연 로딩(Lazy Loading)
quokkaST
quokkaST
  • quokkaST
    stquokka
    quokkaST
    • 개발자 (77)
      • n8n (2)
      • CS공부 (46)
        • Java & Spring (15)
        • 인프라 (7)
        • 운영체제 & 시스템 (9)
        • 기타 CS지식 (7)
        • 네트워크 (6)
        • 데이터베이스 (2)
      • 알고리즘 (16)
      • 프로젝트 (8)
        • 감정&금융챗봇 (8)
      • 리팩토링 (5)
        • horong (5)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
상단으로

티스토리툴바