Token 사용 - 구현 시나리오
Access Token을 발급받기 위한 비즈니스 로직 및 API 실행 순서
이 시나리오는 클라이언트 애플리케이션이 사용자 인증을 통해 Access Token을 발급받고, 이를 사용하여 보호된 리소스에 접근하는 OAuth 2.0 Authorization Code Flow의 전체 과정을 설명합니다.
총 4단계의 비즈니스 로직과 3개의 API 엔드포인트가 순차적으로 실행됩니다.
비즈니스 로직 단계
사용자가 "로그인" 버튼을 클릭하면 클라이언트는 Authorization Endpoint로 리다이렉트합니다.
인증 서버는 Authorization Code를 생성하고 클라이언트의 redirect_uri로 리다이렉트합니다.
Token Endpoint는 Authorization Code를 검증하고 Access Token을 발급합니다.
User Information Endpoint에 Access Token을 포함하여 요청하면 사용자 정보를 반환받습니다.
API 실행 순서 및 흐름
GET /oauth/authorize사용자 인증 및 권한 승인
필수 파라미터:
- • client_id
- • redirect_uri
- • response_type
- • scope
- • state
응답:
Authorization Code
POST /oauth/tokenAuthorization Code를 Access Token으로 교환
필수 파라미터:
- • grant_type
- • code
- • client_id
- • client_secret
- • redirect_uri
응답:
Access Token, Refresh Token, Expires In
GET /oauth/userinfo인증된 사용자 정보 조회
필수 파라미터:
- • Authorization: Bearer {access_token}
응답:
User Information (sub, name, email, etc.)
사용자 인증
Token 발급
사용자 정보 조회
구현 코드 샘플
전체 구현 예제
// Step 1: Authorization Endpoint로 리다이렉트
const authorizeUser = () => {
const clientId = 'your_client_id';
const redirectUri = 'https://yourapp.com/callback';
const scope = 'read write delete';
const state = generateRandomState();
const authUrl = new URL('https://api.example.com/v1/oauth/authorize');
authUrl.searchParams.append('client_id', clientId);
authUrl.searchParams.append('redirect_uri', redirectUri);
authUrl.searchParams.append('response_type', 'code');
authUrl.searchParams.append('scope', scope);
authUrl.searchParams.append('state', state);
// 사용자를 인증 페이지로 리다이렉트
window.location.href = authUrl.toString();
};
// Step 2: Callback에서 Authorization Code 처리
const handleCallback = async () => {
const params = new URLSearchParams(window.location.search);
const authCode = params.get('code');
const state = params.get('state');
if (!authCode) {
console.error('Authorization code not found');
return;
}
// Step 3: Token Endpoint에서 Access Token 요청
const tokenResponse = await fetch('https://api.example.com/v1/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
code: authCode,
client_id: 'your_client_id',
client_secret: 'your_client_secret',
redirect_uri: 'https://yourapp.com/callback',
}),
});
const tokenData = await tokenResponse.json();
const accessToken = tokenData.access_token;
// Access Token 저장
localStorage.setItem('accessToken', accessToken);
// Step 4: User Information 조회
const userResponse = await fetch('https://api.example.com/v1/oauth/userinfo', {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
const userData = await userResponse.json();
console.log('User Info:', userData);
};State 파라미터 검증
Authorization Code 획득 시 state 파라미터를 저장하고, 콜백에서 동일한지 검증하여 CSRF 공격을 방지하세요.
Client Secret 보호
Client Secret은 절대 클라이언트 측 코드에 노출되면 안 됩니다. 백엔드 서버에서만 안전하게 관리하세요.
HTTPS 사용
모든 OAuth 2.0 통신은 HTTPS를 통해 암호화되어야 합니다.
Token 만료 처리
Access Token의 만료 시간(expires_in)을 확인하고, 만료 전에 Refresh Token을 사용하여 새로운 Token을 발급받으세요.