반응형

전자정부프레임워크 기반의 애플리케이션에서 OAuth 2.0을 활용하여 소셜 로그인 기능을 구현하는 방법을 학습합니다. 이번 학습을 통해 사용자 인증 및 권한 부여를 안전하게 처리하는 방식을 이해하고 이를 실제 애플리케이션에 통합합니다.


1. OAuth 2.0 개념 이해

1-1. OAuth 2.0이란?

OAuth 2.0은 제3자 애플리케이션이 사용자 데이터를 안전하게 접근할 수 있도록 인증 및 권한 부여를 제공하는 프로토콜입니다.

  • 클라이언트(Client): 애플리케이션 (ex. 우리 웹 애플리케이션)
  • 리소스 소유자(Resource Owner): 사용자
  • 권한 서버(Authorization Server): 인증을 처리하는 서버
  • 리소스 서버(Resource Server): 사용자의 데이터를 저장하고 제공하는 서버

1-2. OAuth 2.0 동작 흐름

  1. 사용자가 소셜 로그인 버튼을 클릭합니다.
  2. 클라이언트는 권한 서버로 인증 요청을 보냅니다.
  3. 사용자가 권한 서버에서 로그인하여 인증을 완료합니다.
  4. 권한 서버는 클라이언트에 Access Token을 발급합니다.
  5. 클라이언트는 리소스 서버에 Access Token을 보내 사용자 데이터를 요청합니다.
  6. 리소스 서버는 Access Token을 검증한 후 데이터를 반환합니다.

2. 소셜 로그인 준비

2-1. 소셜 플랫폼 선택

OAuth 2.0을 지원하는 대표적인 소셜 플랫폼:

  • Google
  • Facebook
  • Naver
  • Kakao

이번 예제에서는 Google OAuth 2.0을 사용하여 로그인 기능을 구현합니다.

2-2. Google API 콘솔 설정

  1. Google Cloud Console에 접속합니다.
  2. 새로운 프로젝트를 생성합니다.
  3. API 및 서비스 > OAuth 동의 화면에서 앱 정보를 등록합니다.
    • 애플리케이션 이름
    • 승인된 도메인
    • 승인된 리디렉션 URI (예: http://localhost:8080/oauth2/callback)
  4. OAuth 2.0 클라이언트 ID를 생성하고 클라이언트 ID와 클라이언트 비밀 키를 복사합니다.

3. Google OAuth 2.0 연동 구현

3-1. 의존성 추가

pom.xml 파일에 OAuth 2.0 클라이언트를 추가합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

3-2. application.yml 설정

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: <구글 클라이언트 ID>
            client-secret: <구글 클라이언트 비밀 키>
            redirect-uri: "{baseUrl}/oauth2/callback"
            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

3-3. OAuth 2.0 로그인 컨트롤러

import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class OAuth2LoginController {

    @GetMapping("/oauth2/callback")
    public String oauthLogin(OAuth2AuthenticationToken authentication, Model model) {
        String userName = authentication.getPrincipal().getAttribute("name");
        String email = authentication.getPrincipal().getAttribute("email");

        model.addAttribute("userName", userName);
        model.addAttribute("email", email);

        return "loginSuccess"; // 로그인 성공 화면
    }
}

3-4. 보안 설정

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
            .authorizeRequests()
                .antMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2Login()
                .loginPage("/login")
                .defaultSuccessURL("/oauth2/callback", true);

        return http.build();
    }
}

3-5. HTML 페이지 추가

  1. 로그인 페이지(login.html):
<!DOCTYPE html>
<html>
<head>
    <title>소셜 로그인</title>
</head>
<body>
    <h1>로그인</h1>
    <a href="/oauth2/authorization/google">Google로 로그인</a>
</body>
</html>
  1. 로그인 성공 페이지(loginSuccess.html):
<!DOCTYPE html>
<html>
<head>
    <title>로그인 성공</title>
</head>
<body>
    <h1>로그인 성공</h1>
    <p>이름: ${userName}</p>
    <p>이메일: ${email}</p>
</body>
</html>

4. 테스트

  1. 애플리케이션 실행:
    • 브라우저에서 http://localhost:8080/login으로 접속합니다.
  2. Google 로그인 버튼 클릭:
    • Google 계정으로 로그인합니다.
  3. 로그인 성공 페이지 확인:
    • 사용자 이름과 이메일이 화면에 표시됩니다.

5. 마무리

오늘 학습한 OAuth 2.0Google 소셜 로그인은 사용자 인증의 필수적인 기능입니다. 다양한 소셜 플랫폼을 연동하여 로그인 옵션을 확장할 수 있습니다. 다음에서는 API 요청 및 토큰 검증에 대해 학습합니다.

반응형

+ Recent posts