본문 바로가기
SpringBoot/보안과 인증

OAuth2 로그인(Google, Kakao 등)

by DEVLIB 2025. 4. 15.
728x90

OAuth2 로그인 기본 흐름

  1. 사용자가 소셜 로그인 버튼 클릭
  2. 클라이언트가 인증 서버(Google 등)로 리디렉션
  3. 사용자 로그인 → 인증 코드 발급
  4. 서버가 인증 코드를 통해 액세스 토큰 발급
  5. 사용자 정보 요청 → 로그인 처리

1. 의존성 추가

build.gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

2. application.yml 설정 (Google 기준)

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: 구글에서발급받은-client-id
            client-secret: 발급받은-secret
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            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

이 설정은 Google 개발자 콘솔에서 클라이언트 등록 후 발급된 정보로 채워야 합니다.


3. 로그인 URL 및 동작

  • 브라우저에서 /oauth2/authorization/google로 접근 시, 자동으로 구글 로그인 페이지로 리디렉션됩니다.
  • 로그인 성공 시: /login/oauth2/code/google 경로로 리디렉션 → 자동 인증 완료

4. OAuth2UserService 구현 (선택 – 사용자 정보 처리)

@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oauth2User = new DefaultOAuth2UserService().loadUser(userRequest);

        String email = oauth2User.getAttribute("email");
        String name = oauth2User.getAttribute("name");

        // 사용자 정보 DB 저장 또는 업데이트
        // ...

        return oauth2User;
    }
}

5. SecurityConfig 구성

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final CustomOAuth2UserService customOAuth2UserService;

    public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) {
        this.customOAuth2UserService = customOAuth2UserService;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests((authz) -> authz
                .requestMatchers("/", "/login", "/css/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .loginPage("/login")
                .userInfoEndpoint(userInfo -> userInfo
                    .userService(customOAuth2UserService)
                )
            );

        return http.build();
    }
}

6. 로그인 성공 후 사용자 정보 확인

@GetMapping("/user")
public String user(@AuthenticationPrincipal OAuth2User oauth2User, Model model) {
    model.addAttribute("email", oauth2User.getAttribute("email"));
    return "user-info";
}

카카오 로그인 추가 방법

  1. Kakao Developer 사이트 → 애플리케이션 생성
  2. Redirect URI 설정: http://localhost:8080/login/oauth2/code/kakao
  3. application.yml에 추가
spring:
  security:
    oauth2:
      client:
        registration:
          kakao:
            client-id: 카카오앱키
            client-secret: ""
            redirect-uri: "{baseUrl}/login/oauth2/code/kakao"
            authorization-grant-type: authorization_code
            client-name: Kakao
            scope:
              - profile_nickname
              - account_email
        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

마무리 요약

항목 설명
필수 라이브러리 spring-boot-starter-oauth2-client
로그인 진입 URL /oauth2/authorization/{provider}
사용자 정보 OAuth2User.getAttributes()로 가져옴
커스터마이징 OAuth2UserService 구현으로 사용자 DB 연동
카카오/네이버 등 Provider 수동 등록 가능 (Google 외)
LIST

'SpringBoot > 보안과 인증' 카테고리의 다른 글

JWT(Json Web Token) 인증  (0) 2025.04.15
로그인 & 회원가입 구현  (0) 2025.04.15
Spring Security 기본 설정  (0) 2025.04.15