OAuth 2.0 ( 구글 로그인 구현 )

TopOfTheHead·2026년 5월 21일

Spring OAuth

목록 보기
2/11

OAuth 2.0

Google Cloud Console에서 `OAuth 2.0을 위한 프로젝트 생성 후 Client-IDClient Secret Key 확인

  • Google Cloud Console -> 콘솔 -> 새 프로젝트를 통해 프로젝트 생성


  • API 및 서비스 -> OAuth 동의 화면 에서 Google 인증 플랫폼 정의 후 OAuth 클라이언트 생성


    대상 : 외부 설정 하여 OAuth 정의 후 OAuth 클라이언트 생성


    어플리케이션 유형 : 웹 어플리케이션
    이름의 경우 Google 로그인 시 어디로 로그인하는지 지시

    승인된 리디렉션 URI : http://localhost:8080/login/oauth2/code/google로 설정
    Spring Application 사용 시 기본적으로 고정된 Redirection URI

    。이후 OAuth 클라이언트 생성 시 Client IDClient Secret Key 를 따로 기입
    Client-id / Client Secret Key를 통해 구글 ( Authorization Server )에서 클라이언트 ( 백엔드 )를 식별

    ▶ 생성된 Google OAuth 2.0 클라이언트

Spring Project 생성

  • Spring Starter 지정 시 OAuth2 Client, Spring Security 정의
    OAuth2 Client만 정의가 필요


  • application.yml 파일OAuth 2.0 설정 정보 정의
    googleSpring OAuth에서 공식 지원하는 OAuth Provider이므로 application.yml 설정이 간편
    ▶ 공식 지원하지 않는 kakao 등의 서비스에 비해 설정량이 적다.
spring:
  application:
    name: demo-oauth2-trash
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/bblog
    username: ${dbUserId}
    password: ${dbPassword}
  jpa:
    hibernate:
      ddl-auto: create
  security:
    oauth2:
      client:
        registration:
          google:
          	client-name: Google
            client-id: ${clientId}
            client-secret: ${clientSecretKey}
			redirect-uri: "{baseUrl}/{action}/oauth2/code/{registrationId}"
            scope:
              - email
              - profile
  • Spring Security에서 @Configuration 클래스 정의
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http){
        return http
                .csrf(csrf -> csrf.disable())
                .cors( cors -> cors.disable() )
                .oauth2Login(Customizer.withDefaults())
                .authorizeHttpRequests(
                        auth -> auth
                                .requestMatchers("/login", "/sign-up")
                                .anonymous()
                                .requestMatchers("/user/**")
                                .hasAnyAuthority("USER", "ADMIN")
                                .requestMatchers("/admin/**")
                                .hasAuthority("ADMIN")
                                .anyRequest()
                                .authenticated()
                ).build();
    }
}

HTTPSecurity객체.oauth2Login(Customizer.withDefaults())
Spring Security에서 Oauth 2.0 로그인 기능을 활성화하는 메서드

▶ 다음 설정을 끝낸 후 localhost:8080/login 접속 시 해당 API보호하기위해 application.yml에 등록된 OAuth2 Provider ( ex. Google 등 )에 의해 로그인 옵션이 자동으로 표시됨.

profile
공부기록 블로그

0개의 댓글