OAuth
Open Authorization
An open standard authorization protocol that grants third-party applications limited access without the user's password. The core technology behind social logins such as "Sign in with Google" and "Sign in with GitHub."
Open Authorization
An open standard authorization protocol that grants third-party applications limited access without the user's password. The core technology behind social logins such as "Sign in with Google" and "Sign in with GitHub."
OAuth (Open Authorization) is an open authorization standard jointly developed by Twitter and Ma.gnolia in 2007. Its core concept is "Delegated Authorization": a user can grant access to specific resources without giving their password to a third-party app. For example, for a calendar app to read Google Calendar, it accesses it with an OAuth token rather than the user's Google password. This eliminates the security risk of sharing passwords.
OAuth 2.0 consists of four main roles: the Resource Owner (user), the Client (third-party app), the Authorization Server (the server that authenticates and issues tokens), and the Resource Server (API server). In the most widely used Authorization Code Grant flow, the user logs in at the Authorization Server, and the app receives an Authorization Code and exchanges it for an Access Token. This token is used to call the Resource Server's API.
The key security elements of OAuth are scopes and tokens. A scope limits the range of access (for example, read:user, write:repos). An Access Token has a short lifetime (usually 1 hour) and is renewed with a Refresh Token. A short expiration time is used to minimize damage even if an Access Token is stolen. PKCE (Proof Key for Code Exchange) is an additional security layer that prevents Authorization Code interception attacks.
OAuth is an authorization protocol, not an authentication protocol. It decides "May this app access my data?" but OAuth alone cannot tell "Who is this user?" When you need to verify user identity, use OIDC (OpenID Connect), which is built on top of OAuth. OAuth 2.1, the security-hardened version of OAuth 2.0, includes the removal of the Implicit Grant and mandatory PKCE.
// OAuth 2.0 Authorization Code Flow - Node.js Express
const express = require('express');
const axios = require('axios');
const crypto = require('crypto');
const app = express();
// OAuth 설정
const OAUTH_CONFIG = {
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
authorizationUrl: 'https://github.com/login/oauth/authorize',
tokenUrl: 'https://github.com/login/oauth/access_token',
redirectUri: 'http://localhost:3000/callback',
scope: 'read:user user:email'
};
// 1단계: 인증 페이지로 리다이렉트
app.get('/login', (req, res) => {
// PKCE: code_verifier 생성
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest('base64url');
// 세션에 저장 (실제로는 secure session 사용)
req.session = { codeVerifier };
// state: CSRF 방지
const state = crypto.randomBytes(16).toString('hex');
const authUrl = new URL(OAUTH_CONFIG.authorizationUrl);
authUrl.searchParams.set('client_id', OAUTH_CONFIG.clientId);
authUrl.searchParams.set('redirect_uri', OAUTH_CONFIG.redirectUri);
authUrl.searchParams.set('scope', OAUTH_CONFIG.scope);
authUrl.searchParams.set('state', state);
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('response_type', 'code');
res.redirect(authUrl.toString());
});
// 2단계: 콜백 - Authorization Code를 Access Token으로 교환
app.get('/callback', async (req, res) => {
const { code, state } = req.query;
// state 검증 (CSRF 방지)
// if (state !== req.session.state) return res.status(403).send('Invalid state');
try {
// Authorization Code → Access Token 교환
const tokenResponse = await axios.post(OAUTH_CONFIG.tokenUrl, {
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret,
code: code,
redirect_uri: OAUTH_CONFIG.redirectUri,
// code_verifier: req.session.codeVerifier // PKCE
}, {
headers: { Accept: 'application/json' }
});
const { access_token, refresh_token, expires_in } = tokenResponse.data;
// 3단계: Access Token으로 API 호출
const userResponse = await axios.get('https://api.github.com/user', {
headers: { Authorization: `Bearer ${access_token}` }
});
res.json({
user: userResponse.data,
tokenInfo: { expires_in }
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 토큰 갱신
async function refreshAccessToken(refreshToken) {
const response = await axios.post(OAUTH_CONFIG.tokenUrl, {
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: OAUTH_CONFIG.clientId,
client_secret: OAUTH_CONFIG.clientSecret
});
return response.data;
}
app.listen(3000);
# OAuth 2.0 Authorization Code Flow - FastAPI
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
import httpx
import secrets
import hashlib
import base64
from pydantic import BaseModel
app = FastAPI()
# OAuth 설정
OAUTH_CONFIG = {
"client_id": "your_client_id",
"client_secret": "your_client_secret",
"authorization_url": "https://accounts.google.com/o/oauth2/v2/auth",
"token_url": "https://oauth2.googleapis.com/token",
"redirect_uri": "http://localhost:8000/callback",
"scope": "openid email profile"
}
# 세션 저장소 (실제로는 Redis 사용)
sessions = {}
def generate_pkce():
"""PKCE code_verifier와 code_challenge 생성"""
code_verifier = secrets.token_urlsafe(32)
code_challenge = base64.urlsafe_b64encode(
hashlib.sha256(code_verifier.encode()).digest()
).decode().rstrip("=")
return code_verifier, code_challenge
@app.get("/login")
async def login():
"""1단계: Authorization Server로 리다이렉트"""
state = secrets.token_hex(16)
code_verifier, code_challenge = generate_pkce()
# 세션에 저장
sessions[state] = {"code_verifier": code_verifier}
params = {
"client_id": OAUTH_CONFIG["client_id"],
"redirect_uri": OAUTH_CONFIG["redirect_uri"],
"response_type": "code",
"scope": OAUTH_CONFIG["scope"],
"state": state,
"code_challenge": code_challenge,
"code_challenge_method": "S256",
"access_type": "offline", # Refresh Token 요청
"prompt": "consent"
}
auth_url = f"{OAUTH_CONFIG['authorization_url']}?{'&'.join(f'{k}={v}' for k, v in params.items())}"
return RedirectResponse(url=auth_url)
@app.get("/callback")
async def callback(code: str, state: str):
"""2단계: Authorization Code를 Access Token으로 교환"""
# State 검증
if state not in sessions:
raise HTTPException(status_code=403, detail="Invalid state")
session_data = sessions.pop(state)
async with httpx.AsyncClient() as client:
# Token 교환
token_response = await client.post(
OAUTH_CONFIG["token_url"],
data={
"client_id": OAUTH_CONFIG["client_id"],
"client_secret": OAUTH_CONFIG["client_secret"],
"code": code,
"redirect_uri": OAUTH_CONFIG["redirect_uri"],
"grant_type": "authorization_code",
"code_verifier": session_data["code_verifier"]
}
)
if token_response.status_code != 200:
raise HTTPException(status_code=400, detail="Token exchange failed")
tokens = token_response.json()
access_token = tokens["access_token"]
# 3단계: Access Token으로 사용자 정보 조회
user_response = await client.get(
"https://www.googleapis.com/oauth2/v2/userinfo",
headers={"Authorization": f"Bearer {access_token}"}
)
return {
"user": user_response.json(),
"tokens": {
"access_token": access_token[:20] + "...", # 일부만 표시
"expires_in": tokens.get("expires_in"),
"has_refresh_token": "refresh_token" in tokens
}
}
# 토큰 갱신 유틸리티
async def refresh_access_token(refresh_token: str):
"""Refresh Token으로 Access Token 갱신"""
async with httpx.AsyncClient() as client:
response = await client.post(
OAUTH_CONFIG["token_url"],
data={
"client_id": OAUTH_CONFIG["client_id"],
"client_secret": OAUTH_CONFIG["client_secret"],
"refresh_token": refresh_token,
"grant_type": "refresh_token"
}
)
return response.json()
OAuth 2.0 Authorization Code Flow (PKCE 포함)
==============================================
사용자(Browser) Client(App) Authorization Resource
| | Server Server
| | | |
| 1. 로그인 클릭 | | |
|-------------------->| | |
| | | |
| | 2. PKCE 생성 | |
| | code_verifier | |
| | code_challenge | |
| | | |
| 3. 리다이렉트 (client_id, scope, | |
|<----------- code_challenge, state) | |
| | | |
| 4. Authorization Server 로그인 페이지 | |
|------------------------------------------>| |
| | | |
| 5. 사용자 로그인 + 권한 동의 | |
|------------------------------------------>| |
| | | |
| 6. 리다이렉트 (code, state) | |
|<------------------------------------------| |
| | | |
| 7. code 전달 | | |
|-------------------->| | |
| | | |
| | 8. Token 교환 요청 | |
| | (code, code_verifier, client_secret) |
| |--------------------->| |
| | | |
| | 9. Access Token + | |
| | Refresh Token | |
| |<---------------------| |
| | | |
| | 10. API 요청 | |
| | (Bearer Token) | |
| |---------------------------------------->|
| | | |
| | 11. Protected Data | |
| |<----------------------------------------|
| | | |
| 12. 결과 표시 | | |
|<--------------------| | |
Token 종류와 수명
================
- Access Token: 리소스 접근용, 짧은 수명 (1시간)
- Refresh Token: Access Token 갱신용, 긴 수명 (30일+)
- Authorization Code: 1회용, 매우 짧은 수명 (10분)
Scope 예시
==========
Google: openid, email, profile, drive.readonly
GitHub: read:user, user:email, repo, write:repo_hook
Slack: channels:read, chat:write, users:read
"Let's implement Google login with the OAuth 2.0 Authorization Code Flow. PKCE must be applied, and the Refresh Token should be managed only on the server side. On the frontend, store even the Access Token only in memory."
"We should design OAuth scopes on the principle of least privilege. We shouldn't give write permission to an app that only needs read:profile. Let's introduce scope-based access control in our API too, so that third-party apps request only the permissions they need."
"We reduced the Access Token lifetime to 1 hour and applied Refresh Token Rotation. It's a defensive design that minimizes the blast radius if a token is stolen. Server-side token invalidation on logout is also implemented."
The Implicit Grant (response_type=token) is dangerous because the token is exposed in the URL fragment. SPAs should also use the Authorization Code Flow + PKCE. It has been officially removed in OAuth 2.1.
The Client Secret must be used only on the server. If a Client Secret is in browser JavaScript, anyone can see it. Public Clients secure themselves with PKCE alone.
Implementing OAuth without State makes you vulnerable to CSRF attacks. An attacker can bind the victim's session to the attacker's own Authorization Code. Always generate and verify a cryptographically random state.
Apply mandatory PKCE, short Access Token lifetimes, Refresh Token Rotation, minimal scopes, mandatory HTTPS, and redirect_uri whitelist validation. Following the OAuth 2.1 guidelines can prevent most vulnerabilities.