Spring Boot · 2025-12-31

Spring Security로 OAuth2(Google·GitHub) 로그인 연동

Spring Security로 Google과 GitHub OAuth2 로그인을 연동하는 설정과 예제 코드, 인증 흐름과 사용자 정보 매핑 등 핵심 구성 요소 설명

작성일 : 2025-12-31 ㆍ 작성자 : 관리자
post
목차

개요

Spring Security로 OAuth2 로그인 연동은 외부 인증 제공자를 통해 간편한 로그인 경험을 제공한다. 이 글에서는 spring security oauth2 로그인 방식의 기본 원리와 Spring Boot에서 Google, GitHub 연동을 위한 설정과 코드 예제를 단계별로 정리한다. 처음 접하는 개발자도 이해하기 쉽도록 흐름 중심으로 설명한다.

사전 준비

필수 항목

  • Spring Boot 2.4 이상 권장
  • 프로젝트에 spring-boot-starter-oauth2-client 의존성 추가
  • Google과 GitHub에 OAuth 애플리케이션 등록
  • 리디렉션 URI는 /login/oauth2/code/{registrationId} 형태 사용

OAuth 클라이언트 등록

Google, GitHub 애플리케이션 생성

  • Google: Google Cloud Console에서 OAuth 동의 화면과 OAuth 클라이언트 ID 생성
  • GitHub: Developer settings의 OAuth Apps에서 새 앱 생성
  • 클라이언트 ID와 시크릿, 리디렉션 URI를 기록

의존성

implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'

application.yml 예제

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_GOOGLE_CLIENT_ID
            client-secret: YOUR_GOOGLE_CLIENT_SECRET
            scope:
              - openid
              - profile
              - email
          github:
            client-id: YOUR_GITHUB_CLIENT_ID
            client-secret: YOUR_GITHUB_CLIENT_SECRET
            scope:
              - read:user
        provider:
          github:
            authorization-uri: https://github.com/login/oauth/authorize
            token-uri: https://github.com/login/oauth/access_token
            user-info-uri: https://api.github.com/user
            user-name-attribute: id

보안 설정 (새 방식)

Spring Security 5.7 이후 WebSecurityConfigurerAdapter 대신 SecurityFilterChain 빈을 사용한다. 아래 설정은 OAuth2 로그인과 로그인 성공 후 리다이렉트 처리, 공개 경로 설정을 포함한다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/login", "/css/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .defaultSuccessUrl("/", true)
            );

        return http.build();
    }
}

사용자 정보 매핑

OAuth2는 제공자마다 사용자 속성 형식이 다르다. 공통 User 엔티티로 매핑하려면 OAuth2UserService를 구현해 제공자별 속성을 변환하면 편리하다.

import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.user.OAuth2User;

public class CustomOAuth2UserService extends DefaultOAuth2UserService {
    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) {
        OAuth2User user = super.loadUser(userRequest);
        String registrationId = userRequest.getClientRegistration().getRegistrationId();
        // registrationId에 따라 속성 매핑 처리 (google, github 등)
        return user; // 필요 시 사용자 저장 로직 추가
    }
}

컨트롤러 예제

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;

@Controller
public class HomeController {

    @GetMapping("/")
    public String index(Model model, @AuthenticationPrincipal OAuth2User principal) {
        if (principal != null) {
            model.addAttribute("name", principal.getAttribute("name"));
        }
        return "index";
    }
}

인증 흐름 요약

  • 사용자가 /oauth2/authorization/{registrationId}로 접근
  • Spring Security가 공급자 인증 페이지로 리디렉션
  • 공급자가 인증 후 콜백으로 코드 전달
  • Spring Security가 토큰을 교환하고 사용자 정보 조회
  • OAuth2UserService가 사용자 정보를 애플리케이션 사용자로 변환

테스트와 문제 해결

  • 리디렉션 URI 불일치가 가장 흔한 오류
  • client-id와 client-secret의 오타 확인
  • scope 설정이 부족하면 필요한 사용자 정보 미수신
  • 로그에서 spring.security.oauth2 관련 디버그 로그 활성화 후 원인 파악

마무리

Spring Boot와 Spring Security를 이용하면 Google과 GitHub OAuth2 연동이 비교적 간단하다. spring boot oauth2 google 연동과 spring security github oauth 예제에서 제시한 설정을 기반으로, 사용자 매핑과 권한 처리를 확장하면 실무 수준의 인증 기능을 구현할 수 있다. 추가로 사용자 저장 전략이나 권한 매핑을 고민하면 보안과 사용자 경험 모두 개선 가능하다.

spring security oauth2 로그인 spring boot oauth2 google 연동 spring security github oauth 예제 spring security oauth2 로그인 spring boot security google oauth2 github oauth2