React + Spring Boot (Kotlin) OAuth 구현
client_secret 방식 예제
이 예제는 백엔드가 있는 기밀 클라이언트의 정식 방식인 client_secret 방식을 사용합니다.
시크릿은 백엔드 환경 변수에만 두고 프론트엔드 코드나 번들에 넣지 않습니다.
PKCE를 함께 쓰려면 React + Spring Boot (BFF) 예제와 PKCE 가이드를 참고하세요.
시나리오
프론트엔드(React)는 인가 시작과 콜백 처리만 담당하고, 서버(Spring Boot Kotlin)가 client_secret으로 Token을 교환한 뒤 사용자 데이터를 조회해 자체 JWT를 발급하는 OAuth 구현 예제입니다.
이 방식은 SPA 환경에서도 client_secret과 DataGSM 토큰을 브라우저에 노출하지 않고 서버에서 사용자 인증을 처리합니다.
아키텍처 개요
시스템 구성도
데이터 플로우
전체 인증 프로세스는 다음 순서로 진행됩니다.
책임 분리
각 레이어의 명확한 책임 분리로 보안과 유지보수성을 확보합니다.
프론트엔드 (React)
| 책임 | 설명 |
|---|---|
| UI 렌더링 | 로그인 페이지, 로딩 상태, 에러 처리 UI |
| 리다이렉트 처리 | DataGSM 로그인 페이지로 이동 및 콜백 받기 |
| 콜백 처리 | state를 검증하고 access_denied를 처리한 뒤 URL 파라미터에서 code 추출 |
| 백엔드 API 호출 | Code를 서버로 전달하고 JWT 받기 |
| 토큰 관리 | JWT를 sessionStorage에 저장 및 관리 |
| 인증 상태 관리 | 로그인 여부에 따른 UI 분기 처리 |
백엔드 (Spring Boot - Kotlin)
| 책임 | 설명 |
|---|---|
| Client Secret 보호 | 환경 변수로 관리하고 서버에서만 사용 |
| 토큰 교환 | Authorization Code를 Access Token으로 교환 |
| 사용자 데이터 조회 | DataGSM API에서 사용자 데이터 획득 |
| DB 동기화 | 사용자 데이터를 자체 DB에 저장/업데이트 |
| 자체 JWT 발급 | 애플리케이션 인증용 JWT 생성 |
| 비즈니스 로직 | 사용자 권한 관리, 리소스 접근 제어 |
서버가 Token을 교환하는 이유
이 아키텍처에서 토큰 교환을 서버가 수행하는 이유는 다음과 같습니다.
| 이유 | 설명 |
|---|---|
| Client Secret 보호 | 프론트엔드 번들에 들어간 값은 누구나 볼 수 있으므로 시크릿은 서버에만 둡니다 |
| CORS 제한 | 인가 서버의 CORS 허용 출처는 DataGSM 자사 서비스로 제한되어 브라우저에서 /v1/oauth/token을 호출할 수 없습니다 |
| 토큰 격리 | DataGSM 토큰을 브라우저에 전달하지 않고 앱 전용 JWT만 전달합니다 |
보안 고려사항
이 아키텍처에서 구현된 주요 보안 요소입니다.
| 보안 요소 | 구현 위치 | 설명 |
|---|---|---|
| Client Secret 관리 | Spring Boot (환경 변수) | 프론트엔드 코드와 번들에 넣지 않음 |
| HTTPS 강제 | 전체 시스템 | 프로덕션에서 모든 통신은 HTTPS 사용 |
| State 파라미터 | React | CSRF 공격 방지를 위한 랜덤 토큰 생성 및 검증 |
| 토큰 분리 | 양쪽 | DataGSM 토큰은 서버에서만 사용, JWT는 앱 인증용 |
| JWT 검증 | Spring Boot | 모든 API 요청에서 JWT 서명 및 만료 검증 |
Step 1: 프론트엔드 (React + TypeScript)
프로젝트 구조
OAuth 로그인 Hook
인가 요청을 시작하는 커스텀 Hook입니다. client_secret은 프론트엔드에서 사용하지 않습니다.
import { useState, useCallback } from 'react';
interface OAuthConfig {
clientId: string;
redirectUri: string;
authUrl: string;
scope: string;
}
interface UseOAuthLoginReturn {
login: () => void;
isLoading: boolean;
error: string | null;
}
export const useOAuthLogin = (config: OAuthConfig): UseOAuthLoginReturn => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const login = useCallback(() => {
setIsLoading(true);
setError(null);
try {
// State 파라미터 생성 (CSRF 방지)
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);
// DataGSM 인가 페이지로 리다이렉트
const authUrl = new URL(config.authUrl);
authUrl.searchParams.append('client_id', config.clientId);
authUrl.searchParams.append('redirect_uri', config.redirectUri);
authUrl.searchParams.append('scope', config.scope);
authUrl.searchParams.append('state', state);
window.location.href = authUrl.toString();
} catch (err) {
setError(err instanceof Error ? err.message : '알 수 없는 오류가 발생했습니다.');
setIsLoading(false);
}
}, [config]);
return { login, isLoading, error };
};OAuth 서비스
콜백에서 받은 code를 백엔드로 전달하는 서비스입니다. 토큰 교환은 백엔드가 수행합니다.
export interface AppUser {
id: number;
email: string;
name: string;
objectType: 'STUDENT' | 'TEACHER' | null;
grade: number;
classNum: number;
number: number;
profileImage: string | null;
}
export interface AuthResponse {
token: string;
user: AppUser;
}
class OAuthService {
private readonly backendUrl: string;
constructor() {
this.backendUrl = process.env.REACT_APP_BACKEND_URL || 'http://localhost:8080';
}
/**
* Authorization Code를 서버에 전달하여 JWT 받기
*/
async loginWithCode(code: string): Promise<AuthResponse> {
const response = await fetch(this.backendUrl + '/api/auth/callback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || '서버 인증에 실패했습니다.');
}
return response.json();
}
}
export const oauthService = new OAuthService();로그인 페이지
import React from 'react';
import { useOAuthLogin } from '../hooks/useOAuthLogin';
const LoginPage: React.FC = () => {
const { login, isLoading, error } = useOAuthLogin({
clientId: process.env.REACT_APP_DATAGSM_CLIENT_ID || '',
redirectUri: process.env.REACT_APP_REDIRECT_URI || 'http://localhost:3000/callback',
authUrl: 'https://oauth.authorization.datagsm.kr/v1/oauth/authorize',
scope: 'datagsm:account_read datagsm:student_read',
});
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
<div className="max-w-md w-full space-y-8 p-10 bg-white rounded-2xl shadow-xl">
<div className="text-center">
<h1 className="text-4xl font-bold text-gray-900 mb-2">
환영합니다
</h1>
<p className="text-gray-600">
DataGSM 계정으로 로그인하세요
</p>
</div>
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<div className="flex">
<div className="flex-shrink-0">
<svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
</div>
<div className="ml-3">
<p className="text-sm text-red-800">{error}</p>
</div>
</div>
</div>
)}
<div>
<button
onClick={login}
disabled={isLoading}
className="w-full flex justify-center items-center py-4 px-6 border border-transparent
rounded-xl shadow-md text-lg font-semibold text-white
bg-gradient-to-r from-blue-600 to-indigo-600
hover:from-blue-700 hover:to-indigo-700
focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500
disabled:from-gray-400 disabled:to-gray-500 disabled:cursor-not-allowed
transition-all duration-200 transform hover:scale-105 active:scale-95"
>
{isLoading ? (
<span className="flex items-center">
<svg className="animate-spin -ml-1 mr-3 h-6 w-6 text-white"
xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10"
stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
처리 중...
</span>
) : (
<span className="flex items-center">
<svg className="w-6 h-6 mr-2" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clipRule="evenodd" />
</svg>
DataGSM으로 로그인
</span>
)}
</button>
</div>
<div className="text-center">
<p className="text-sm text-gray-600">
로그인함으로써 <a href="/terms" className="text-blue-600 hover:underline">서비스 이용약관</a>과{' '}
<a href="/privacy" className="text-blue-600 hover:underline">개인정보 처리방침</a>에 동의합니다.
</p>
</div>
</div>
</div>
);
};
export default LoginPage;OAuth 콜백 페이지
DataGSM 인증 후 리다이렉트되는 페이지입니다. state를 먼저 검증하고, 사용자가 동의를 거부해 error=access_denied로 돌아온 경우를 처리한 뒤 Authorization Code를 백엔드로 전달합니다.
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { oauthService } from '../services/oauthService';
const CallbackPage: React.FC = () => {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const [error, setError] = useState<string | null>(null);
const [progress, setProgress] = useState<string>('인증 데이터 확인 중...');
const handledRef = useRef(false);
useEffect(() => {
// 개발 모드의 Strict Mode에서 effect가 두 번 실행되어도 한 번만 처리합니다.
if (handledRef.current) {
return;
}
handledRef.current = true;
const handleCallback = async () => {
try {
// URL에서 code, state, error 추출
const code = searchParams.get('code');
const state = searchParams.get('state');
const oauthError = searchParams.get('error');
// State 검증 (CSRF 방지). 오류 응답에도 state가 포함되므로 error보다 먼저 확인합니다.
const savedState = sessionStorage.getItem('oauth_state');
sessionStorage.removeItem('oauth_state');
if (!savedState || state !== savedState) {
throw new Error('State 파라미터가 일치하지 않습니다. CSRF 공격이 의심됩니다.');
}
// 동의를 거부하면 code 없이 error=access_denied로 돌아옵니다.
if (oauthError === 'access_denied') {
throw new Error('권한 요청을 거부했습니다. 로그인하려면 권한을 허용해 주세요.');
}
if (oauthError) {
throw new Error('로그인에 실패했습니다. 다시 시도해 주세요.');
}
if (!code) {
throw new Error('Authorization code가 없습니다.');
}
// 서버가 토큰을 교환하고 JWT를 발급합니다.
setProgress('서버에서 인증 데이터를 확인하는 중...');
const authResponse = await oauthService.loginWithCode(code);
// JWT를 sessionStorage에 저장
sessionStorage.setItem('auth_token', authResponse.token);
sessionStorage.setItem('user', JSON.stringify(authResponse.user));
// 성공 메시지
setProgress('로그인 완료! 메인 페이지로 이동합니다...');
// 메인 페이지로 이동
setTimeout(() => {
navigate('/');
}, 1000);
} catch (err) {
console.error('OAuth callback error:', err);
setError(err instanceof Error ? err.message : '알 수 없는 오류가 발생했습니다.');
// 3초 후 로그인 페이지로 이동
setTimeout(() => {
navigate('/login');
}, 3000);
}
};
handleCallback();
}, [searchParams, navigate]);
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full p-8 bg-white rounded-lg shadow-md">
<div className="text-center">
<div className="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-red-100 mb-4">
<svg className="h-10 w-10 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
<h3 className="text-xl font-semibold text-gray-900 mb-2">로그인 실패</h3>
<p className="text-base text-gray-600 mb-4">{error}</p>
<p className="text-sm text-gray-400">잠시 후 로그인 페이지로 이동합니다...</p>
</div>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full p-8 bg-white rounded-lg shadow-md">
<div className="text-center">
<svg className="animate-spin mx-auto h-16 w-16 text-blue-600 mb-4"
xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10"
stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
<h3 className="text-xl font-semibold text-gray-900 mb-2">로그인 처리 중</h3>
<p className="text-base text-gray-600">{progress}</p>
</div>
</div>
</div>
);
};
export default CallbackPage;Step 2: 백엔드 (Spring Boot - Kotlin)
프로젝트 구조
AuthController
Authorization Code를 받아 로그인을 처리하고 JWT를 발급하는 컨트롤러입니다.
package com.example.app.controller
import com.example.app.dto.OAuthCallbackRequest
import com.example.app.service.OAuthService
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
@RestController
@RequestMapping("/api/auth")
class AuthController(
private val oAuthService: OAuthService
) {
private val logger = LoggerFactory.getLogger(AuthController::class.java)
/**
* OAuth 콜백 처리 및 JWT 발급
*
* @param request Authorization Code를 포함한 요청
* @return JWT 토큰 및 사용자 데이터
*/
@PostMapping("/callback")
fun handleCallback(
@RequestBody request: OAuthCallbackRequest
): ResponseEntity<*> {
return try {
val response = oAuthService.processOAuthCallback(request.code)
ResponseEntity.ok(response)
} catch (e: ResponseStatusException) {
// 429를 포함한 상태 코드와 안내 문구를 프론트엔드로 전달합니다.
ResponseEntity.status(e.statusCode)
.body(mapOf("message" to e.reason))
} catch (e: Exception) {
logger.error("OAuth callback failed", e)
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(mapOf("message" to "로그인 처리 중 오류가 발생했습니다."))
}
}
/**
* 현재 로그인한 사용자 데이터 조회
*
* @param authHeader Authorization 헤더 (Bearer 토큰)
* @return 사용자 데이터
*/
@GetMapping("/me")
fun getCurrentUser(
@RequestHeader("Authorization") authHeader: String
): ResponseEntity<*> {
return try {
if (!authHeader.startsWith("Bearer ")) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(mapOf("message" to "Invalid token format"))
}
val token = authHeader.substring(7)
val user = oAuthService.getUserFromToken(token)
ResponseEntity.ok(user)
} catch (e: Exception) {
ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(mapOf("message" to "Invalid or expired token"))
}
}
/**
* 로그아웃
*
* @param authHeader Authorization 헤더
* @return 성공 메시지
*/
@PostMapping("/logout")
fun logout(
@RequestHeader("Authorization") authHeader: String
): ResponseEntity<*> {
return try {
val token = authHeader.substring(7)
oAuthService.invalidateToken(token)
ResponseEntity.ok(mapOf("message" to "Logged out successfully"))
} catch (e: Exception) {
ResponseEntity.badRequest().build<Any>()
}
}
}OAuthService
client_secret으로 토큰을 교환하고 사용자 데이터 조회, JWT 발급을 담당하는 핵심 서비스입니다. DataGSM 토큰은 프론트엔드로 전달하지 않습니다.
package com.example.app.service
import com.example.app.dto.AuthResponse
import com.example.app.dto.DataGsmUserInfo
import com.example.app.dto.TokenResponse
import com.example.app.dto.UserInfoResponse
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
@Service
class OAuthService(
private val userService: UserService,
private val jwtService: JwtService,
private val objectMapper: ObjectMapper,
@Value("\${datagsm.oauth.token-url}") private val tokenUrl: String,
@Value("\${datagsm.oauth.userinfo-url}") private val userInfoUrl: String,
@Value("\${datagsm.oauth.client-id}") private val clientId: String,
@Value("\${datagsm.oauth.client-secret}") private val clientSecret: String,
@Value("\${datagsm.oauth.redirect-uri}") private val redirectUri: String
) {
private val logger = LoggerFactory.getLogger(OAuthService::class.java)
private val httpClient: HttpClient = HttpClient.newHttpClient()
/**
* OAuth 콜백 처리 및 JWT 발급
*
* 1. Authorization Code를 Access Token으로 교환
* 2. Access Token으로 DataGSM에서 사용자 데이터 조회
* 3. DB에 사용자 데이터 동기화
* 4. 자체 JWT 발급
*/
@Transactional
fun processOAuthCallback(code: String): AuthResponse {
// 1. Authorization Code를 Access Token으로 교환
val tokenResponse = exchangeCodeForToken(code)
// 2. Access Token으로 사용자 데이터 조회
val userInfo = fetchUserInfo(tokenResponse.accessToken)
// 3. DB에 사용자 데이터 저장/업데이트
val user = userService.syncUser(userInfo)
// 4. 자체 JWT 발급
val jwt = jwtService.generateToken(user)
logger.info("Successfully issued JWT for user: {}", user.email)
// 5. 응답 생성
return AuthResponse(
token = jwt,
user = UserInfoResponse.from(user)
)
}
/**
* Authorization Code를 Access Token으로 교환
*/
private fun exchangeCodeForToken(code: String): TokenResponse {
val requestBody = objectMapper.writeValueAsString(
mapOf(
"grant_type" to "authorization_code",
"code" to code,
"client_id" to clientId,
"client_secret" to clientSecret,
"redirect_uri" to redirectUri
)
)
val request = HttpRequest.newBuilder()
.uri(URI.create(tokenUrl))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build()
val response = httpClient.send(
request,
HttpResponse.BodyHandlers.ofString()
)
assertSuccess(response, "exchange token")
return objectMapper.readValue(response.body(), TokenResponse::class.java)
}
/**
* Access Token으로 DataGSM 사용자 데이터 조회
*/
private fun fetchUserInfo(accessToken: String): DataGsmUserInfo {
val request = HttpRequest.newBuilder()
.uri(URI.create(userInfoUrl))
.header("Authorization", "Bearer $accessToken")
.GET()
.build()
val response = httpClient.send(
request,
HttpResponse.BodyHandlers.ofString()
)
assertSuccess(response, "fetch user info")
return objectMapper.readValue(response.body(), DataGsmUserInfo::class.java)
}
/**
* DataGSM 응답 상태 확인
* 429는 요청 한도 초과이므로 잠시 후 재시도를 안내합니다.
*/
private fun assertSuccess(response: HttpResponse<String>, action: String) {
if (response.statusCode() == 200) {
return
}
logger.error("Failed to {}: status={}, body={}", action, response.statusCode(), response.body())
if (response.statusCode() == 429) {
throw ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS, "요청이 많습니다. 잠시 후 다시 시도해 주세요.")
}
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "로그인에 실패했습니다. 다시 시도해 주세요.")
}
/**
* JWT에서 사용자 데이터 추출
*/
fun getUserFromToken(token: String): UserInfoResponse {
val userId = jwtService.extractUserId(token)
val user = userService.findById(userId)
return UserInfoResponse.from(user)
}
/**
* 토큰 무효화 (로그아웃)
*/
fun invalidateToken(token: String) {
// JWT는 stateless하므로 블랙리스트에 추가하거나
// Redis 같은 캐시에 만료 처리할 수 있습니다.
logger.info("Token invalidated")
}
}UserService
사용자 데이터를 DB에 동기화하고 관리하는 서비스입니다.
package com.example.app.service
import com.example.app.dto.DataGsmUserInfo
import com.example.app.entity.User
import com.example.app.repository.UserRepository
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
@Service
class UserService(
private val userRepository: UserRepository
) {
private val logger = LoggerFactory.getLogger(UserService::class.java)
/**
* DataGSM 사용자 데이터를 DB에 동기화
*
* - 신규 사용자: 생성
* - 기존 사용자: 데이터 업데이트
*/
@Transactional
fun syncUser(userInfo: DataGsmUserInfo): User {
return userRepository.findByEmail(userInfo.email)
?.let { updateUser(it, userInfo) }
?: createUser(userInfo)
}
/**
* 신규 사용자 생성
*/
private fun createUser(userInfo: DataGsmUserInfo): User {
val s = userInfo.student
val user = User(
email = userInfo.email,
name = resolveName(userInfo),
objectType = userInfo.objectType,
grade = s?.grade ?: 0,
classNum = s?.classNum ?: 0,
number = s?.number ?: 0,
createdAt = LocalDateTime.now(),
updatedAt = LocalDateTime.now()
)
val saved = userRepository.save(user)
logger.info("Created new user: {}", saved.email)
return saved
}
/**
* 기존 사용자 데이터 업데이트
*/
private fun updateUser(user: User, userInfo: DataGsmUserInfo): User {
user.apply {
name = resolveName(userInfo)
objectType = userInfo.objectType
userInfo.student?.let { s ->
grade = s.grade ?: 0
classNum = s.classNum ?: 0
number = s.number ?: 0
}
updatedAt = LocalDateTime.now()
}
val updated = userRepository.save(user)
logger.info("Updated user: {}", updated.email)
return updated
}
/**
* objectType에 따라 표시 이름 결정
*/
private fun resolveName(userInfo: DataGsmUserInfo): String {
val name = when (userInfo.objectType) {
"STUDENT" -> userInfo.student?.name
"TEACHER" -> userInfo.teacher?.name
else -> null
}
return name ?: userInfo.email
}
/**
* ID로 사용자 조회
*/
fun findById(id: Long): User {
return userRepository.findById(id)
.orElseThrow { RuntimeException("User not found: $id") }
}
/**
* 이메일로 사용자 조회
*/
fun findByEmail(email: String): User {
return userRepository.findByEmail(email)
?: throw RuntimeException("User not found: $email")
}
}JwtService
자체 JWT 토큰을 발급하고 검증하는 서비스입니다.
package com.example.app.service
import com.example.app.entity.User
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.security.Keys
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.util.*
import javax.crypto.SecretKey
@Service
class JwtService(
@Value("\${jwt.secret}") private val secretKey: String,
@Value("\${jwt.expiration:3600000}") private val expirationTime: Long
) {
private val logger = LoggerFactory.getLogger(JwtService::class.java)
private fun getSigningKey(): SecretKey {
return Keys.hmacShaKeyFor(secretKey.toByteArray())
}
/**
* JWT 토큰 생성
*/
fun generateToken(user: User): String {
val claims = mutableMapOf<String, Any>()
claims["userId"] = user.id!!
claims["email"] = user.email
claims["name"] = user.name
claims["grade"] = user.grade
claims["classNum"] = user.classNum
claims["number"] = user.number
val now = Date()
val expiryDate = Date(now.time + expirationTime)
return Jwts.builder()
.claims(claims)
.subject(user.email)
.issuedAt(now)
.expiration(expiryDate)
.signWith(getSigningKey(), Jwts.SIG.HS256)
.compact()
}
/**
* JWT에서 사용자 ID 추출
*/
fun extractUserId(token: String): Long {
val claims = extractAllClaims(token)
return claims["userId"].toString().toLong()
}
/**
* JWT에서 이메일 추출
*/
fun extractEmail(token: String): String {
return extractAllClaims(token).subject
}
/**
* JWT 유효성 검증
*/
fun validateToken(token: String): Boolean {
return try {
extractAllClaims(token)
!isTokenExpired(token)
} catch (e: Exception) {
logger.error("Invalid JWT token: {}", e.message)
false
}
}
/**
* JWT에서 모든 클레임 추출
*/
private fun extractAllClaims(token: String): Claims {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.payload
}
/**
* JWT 만료 여부 확인
*/
private fun isTokenExpired(token: String): Boolean {
return extractAllClaims(token).expiration.before(Date())
}
}DTO 클래스들
데이터 전송을 위한 DTO 클래스입니다.
package com.example.app.dto
import com.example.app.entity.User
import com.fasterxml.jackson.annotation.JsonProperty
// OAuth 콜백 요청
data class OAuthCallbackRequest(
val code: String
)
// DataGSM 토큰 응답
data class TokenResponse(
@JsonProperty("access_token")
val accessToken: String,
@JsonProperty("token_type")
val tokenType: String,
@JsonProperty("expires_in")
val expiresIn: Long,
@JsonProperty("refresh_token")
val refreshToken: String?,
@JsonProperty("scope")
val scope: String,
// scope에 openid를 요청한 코드 교환에서만 값이 있습니다.
@JsonProperty("id_token")
val idToken: String? = null
)
// DataGSM /userinfo 응답
data class DataGsmUserInfo(
val sub: String,
val id: Long,
val email: String,
val role: String,
val status: String,
val objectType: String?,
// isStudent는 Deprecated이며 objectType == "STUDENT"의 파생값입니다. 신규 연동은 objectType을 사용하세요.
val isStudent: Boolean,
val student: StudentInfo?,
val teacher: TeacherInfo?,
// club_read, project_read를 요청해야 채워지며 그렇지 않으면 빈 배열입니다.
val clubs: List<ClubSummary> = emptyList(),
val projects: List<ProjectSummary> = emptyList()
) {
data class StudentInfo(
val id: Long,
val name: String,
val sex: String,
val email: String,
val grade: Int?,
val classNum: Int?,
val number: Int?,
val studentNumber: Int?,
val major: String?,
val specialty: String?,
val role: String,
val dormitoryFloor: Int?,
val dormitoryRoom: Int?,
// club_read가 없으면 null입니다.
val majorClub: ClubSummary?,
val autonomousClub: ClubSummary?,
val githubId: String?,
val githubUrl: String?
)
data class TeacherInfo(
val id: Long,
val name: String,
val email: String,
val department: String,
val description: String?
)
data class ClubSummary(
val id: Long,
val name: String,
val type: String
)
data class ProjectSummary(
val id: Long,
val name: String,
val status: String,
val club: ClubSummary?
)
}
// 인증 응답 (JWT + 사용자 데이터)
data class AuthResponse(
val token: String,
val user: UserInfoResponse
)
// 사용자 데이터 응답
data class UserInfoResponse(
val id: Long,
val email: String,
val name: String,
val objectType: String?,
val grade: Int,
val classNum: Int,
val number: Int,
val profileImage: String?
) {
companion object {
fun from(user: User): UserInfoResponse {
return UserInfoResponse(
id = user.id!!,
email = user.email,
name = user.name,
objectType = user.objectType,
grade = user.grade,
classNum = user.classNum,
number = user.number,
profileImage = user.profileImage
)
}
}
}Entity & Repository
사용자 엔티티와 레포지토리입니다.
package com.example.app.entity
import jakarta.persistence.*
import java.time.LocalDateTime
@Entity
@Table(name = "users")
data class User(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@Column(nullable = false, unique = true)
var email: String,
@Column(nullable = false)
var name: String,
var objectType: String? = null,
var grade: Int,
var classNum: Int,
var number: Int,
var profileImage: String? = null,
@Column(nullable = false, updatable = false)
val createdAt: LocalDateTime = LocalDateTime.now(),
@Column(nullable = false)
var updatedAt: LocalDateTime = LocalDateTime.now()
)package com.example.app.repository
import com.example.app.entity.User
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface UserRepository : JpaRepository<User, Long> {
/**
* 이메일로 사용자 조회
*/
fun findByEmail(email: String): User?
/**
* 이메일 존재 여부 확인
*/
fun existsByEmail(email: String): Boolean
}환경 설정
React 환경 변수
REACT_APP_ 접두어가 붙은 값은 빌드 결과에 그대로 포함됩니다. client_secret은 여기에 넣지 않습니다.
# DataGSM OAuth 설정
REACT_APP_DATAGSM_CLIENT_ID=your-client-id-here
REACT_APP_REDIRECT_URI=http://localhost:3000/callback
# 백엔드 API URL
REACT_APP_BACKEND_URL=http://localhost:8080Spring Boot 환경 변수
client_secret은 서버 환경 변수로만 전달합니다. DATAGSM_REDIRECT_URI는 인가 요청에 쓴 REACT_APP_REDIRECT_URI, 콘솔에 등록한 리다이렉트 URI와 같은 값이어야 합니다. datagsm:account_read, datagsm:student_read도 콘솔에서 클라이언트에 등록해 두어야 합니다.
spring:
datasource:
url: jdbc:mysql://localhost:3306/myapp
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
# DataGSM OAuth 설정
datagsm:
oauth:
token-url: https://oauth.authorization.datagsm.kr/v1/oauth/token
userinfo-url: https://oauth.resource.datagsm.kr/userinfo
client-id: ${DATAGSM_CLIENT_ID}
client-secret: ${DATAGSM_CLIENT_SECRET}
redirect-uri: ${DATAGSM_REDIRECT_URI:http://localhost:3000/callback}
# JWT 설정
jwt:
secret: ${JWT_SECRET}
expiration: 3600000 # 1시간 (밀리초)
# CORS 설정
cors:
allowed-origins: http://localhost:3000
allowed-methods: GET,POST,PUT,DELETE,OPTIONS
allowed-headers: "*"
allow-credentials: trueexport DATAGSM_CLIENT_ID=your-client-id
export DATAGSM_CLIENT_SECRET=your-client-secret
export DATAGSM_REDIRECT_URI=http://localhost:3000/callback
# HS256 서명 키는 32바이트 이상이어야 합니다.
export JWT_SECRET=your-jwt-secret-minimum-32-characters-long의존성 설정
{
"name": "react-oauth-app",
"version": "1.0.0",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.20.0",
"react-scripts": "5.0.1"
},
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"typescript": "^4.9.5",
"tailwindcss": "^3.3.0"
}
}import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.2.0"
id("io.spring.dependency-management") version "1.1.4"
kotlin("jvm") version "1.9.21"
kotlin("plugin.spring") version "1.9.21"
kotlin("plugin.jpa") version "1.9.21"
}
group = "com.example"
version = "1.0.0"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
// Spring Boot
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
// Kotlin
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
// Database
runtimeOnly("com.mysql:mysql-connector-j")
// JWT
implementation("io.jsonwebtoken:jjwt-api:0.12.5")
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.12.5")
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.12.5")
// Validation
implementation("org.springframework.boot:spring-boot-starter-validation")
// Test
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}보안 고려사항
1. Client Secret 관리
Client Secret은 백엔드 환경 변수로만 관리합니다.
| 위험 요소 | 대응 방안 |
|---|---|
| 브라우저 노출 | 프론트엔드 코드와 번들에 넣지 않고 서버에서만 사용 |
| 프론트엔드 환경 변수 | REACT_APP_ 접두어 변수는 빌드 결과에 포함되므로 시크릿에 사용하지 않음 |
| 코드에 하드코딩 | 환경 변수나 시크릿 매니저로 관리 |
| 버전 관리 시스템 | .env 파일을 Git에 커밋하지 않음 |
2. DataGSM 토큰 관리
이 예제는 사용자 데이터를 조회한 뒤 DataGSM 토큰을 프론트엔드로 전달하지 않습니다. 자체 JWT가 만료되면 사용자는 다시 로그인합니다. SSO 세션이 남아 있으면 로그인 화면 없이 바로 콜백으로 돌아옵니다.
Refresh Token을 저장해 쓰는 경우에는 다음을 지킵니다.
| 항목 | 처리 방법 |
|---|---|
| 저장 위치 | 서버의 DB나 세션에 저장하고 브라우저로 전달하지 않음 |
| 회전 | 갱신 응답의 새 Refresh Token으로 항상 교체 |
| 동시 갱신 | 같은 토큰으로 동시에 갱신하면 재사용으로 판단되어 저장된 토큰까지 삭제되므로 한 번에 하나만 실행 |
invalid_grant | 다시 로그인하도록 안내 |
| 429 | 토큰을 지우지 않고 잠시 후 다시 시도 |
3. CORS 설정
백엔드에서 적절한 CORS 설정이 필요합니다.
package com.example.app.config
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
@Configuration
class CorsConfig {
@Value("\${cors.allowed-origins}")
private lateinit var allowedOriginsConfig: String
@Bean
fun corsFilter(): CorsFilter {
val config = CorsConfiguration().apply {
allowedOrigins = allowedOriginsConfig.split(",")
allowedMethods = listOf("GET", "POST", "PUT", "DELETE", "OPTIONS")
allowedHeaders = listOf("*")
allowCredentials = true
maxAge = 3600L
}
val source = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/api/**", config)
}
return CorsFilter(source)
}
}4. HTTPS 사용
프로덕션 환경에서는 반드시 HTTPS를 사용해야 합니다.
| 프로토콜 | 환경 | 사용 여부 | 이유 |
|---|---|---|---|
| HTTP | 로컬 개발 | 허용 | localhost는 안전한 컨텍스트 |
| HTTP | 프로덕션 | 금지 | Client Secret 및 토큰 탈취 위험 |
| HTTPS | 프로덕션 | 필수 | 데이터 암호화 및 보안 |
완전한 코드 예제
통합 플로우 예제
전체 OAuth 플로우를 하나의 서비스로 통합한 예제입니다.
import { oauthService, AppUser } from './oauthService';
interface AuthFlowResult {
success: boolean;
token?: string;
user?: AppUser;
error?: string;
}
/**
* 전체 OAuth 콜백 처리를 수행하는 통합 함수
*/
export async function completeOAuthFlow(params: URLSearchParams): Promise<AuthFlowResult> {
try {
// 1. State 검증
const savedState = sessionStorage.getItem('oauth_state');
sessionStorage.removeItem('oauth_state');
if (!savedState || params.get('state') !== savedState) {
throw new Error('State 파라미터가 일치하지 않습니다.');
}
// 2. 동의 거부와 오류 처리
const oauthError = params.get('error');
if (oauthError === 'access_denied') {
throw new Error('권한 요청을 거부했습니다. 로그인하려면 권한을 허용해 주세요.');
}
if (oauthError) {
throw new Error('로그인에 실패했습니다. 다시 시도해 주세요.');
}
const code = params.get('code');
if (!code) {
throw new Error('Authorization code가 없습니다.');
}
// 3. 서버에 code를 전달하여 JWT 받기
const authResponse = await oauthService.loginWithCode(code);
// 4. 토큰 저장
sessionStorage.setItem('auth_token', authResponse.token);
sessionStorage.setItem('user', JSON.stringify(authResponse.user));
return {
success: true,
token: authResponse.token,
user: authResponse.user
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.'
};
}
}인증된 API 호출 예제
JWT를 사용하여 보호된 API를 호출하는 예제입니다.
const API_BASE_URL = process.env.REACT_APP_BACKEND_URL || 'http://localhost:8080';
/**
* 인증이 필요한 API 호출
*/
async function authenticatedFetch(
endpoint: string,
options: RequestInit = {}
): Promise<Response> {
const token = sessionStorage.getItem('auth_token');
if (!token) {
throw new Error('인증 토큰이 없습니다.');
}
const response = await fetch(API_BASE_URL + endpoint, {
...options,
headers: {
...options.headers,
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
},
});
// 401 Unauthorized: 토큰 만료
if (response.status === 401) {
sessionStorage.removeItem('auth_token');
sessionStorage.removeItem('user');
window.location.href = '/login';
throw new Error('인증이 만료되었습니다.');
}
return response;
}
// 사용 예시
export async function getUserProfile() {
const response = await authenticatedFetch('/api/auth/me');
return response.json();
}다음 단계
기능 확장
구현을 완료한 후 다음 기능들을 추가로 고려해보세요.
| 기능 | 설명 | 우선순위 |
|---|---|---|
| Token Refresh | Refresh Token을 서버에 저장하고 회전된 새 값으로 교체하며 자동 갱신 | 높음 |
| 자동 로그아웃 | JWT 만료 시 자동 로그아웃 처리 | 높음 |
| Remember Me | 로그인 상태 유지 기능 | 중간 |
| 다중 기기 로그인 | 여러 기기에서 동시 로그인 지원 | 중간 |
모니터링 및 로깅
프로덕션 환경에서는 다음 항목들을 모니터링하세요.
// 로그 예시
logger.info("OAuth callback started")
logger.info("Successfully issued JWT for user: {}", email)
logger.error("Failed to {}: status={}, body={}", action, status, body)성능 최적화
- Redis를 사용한 JWT 블랙리스트 캐싱
- DB 쿼리 최적화 (인덱스 추가)
- Connection Pool 설정
- React 컴포넌트 메모이제이션