Initial commit: OAuth 2.0 인증 시스템 with APISIX API Gateway

- FastAPI 백엔드 + MongoDB + Redis 구성
- React + Vite + TypeScript + shadcn/ui 프론트엔드
- Apache APISIX API Gateway 통합
- Docker Compose 기반 개발 환경
- 3단계 권한 체계 (System Admin, Group Admin, User)
- 동적 테마 지원
- 환경별 설정 (dev/vei/prod)

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Claude
2025-08-31 10:16:41 +09:00
commit f53d55e712
55 changed files with 6798 additions and 0 deletions

View File

@ -0,0 +1,349 @@
# OAuth API 명세서
## Base URL
- Development: `http://localhost:8000/api/v1`
- Verification: `https://vei-oauth-api.example.com/api/v1`
- Production: `https://api-oauth.example.com/api/v1`
## 인증 헤더
```
Authorization: Bearer {access_token}
```
## API 엔드포인트
### 인증 (Authentication)
#### POST /auth/login
사용자 로그인
**Request Body:**
```json
{
"email": "user@example.com",
"password": "password123"
}
```
**Response:**
```json
{
"access_token": "eyJ...",
"refresh_token": "eyJ...",
"token_type": "bearer",
"expires_in": 1800
}
```
#### POST /auth/logout
사용자 로그아웃
**Headers:**
- Authorization: Bearer {access_token}
**Response:**
```json
{
"message": "Successfully logged out"
}
```
#### POST /auth/refresh
토큰 갱신
**Request Body:**
```json
{
"refresh_token": "eyJ..."
}
```
**Response:**
```json
{
"access_token": "eyJ...",
"token_type": "bearer",
"expires_in": 1800
}
```
#### POST /auth/authorize
OAuth 인증 요청
**Query Parameters:**
- `response_type`: "code"
- `client_id`: Application Client ID
- `redirect_uri`: Redirect URI
- `scope`: 요청 권한 (space 구분)
- `state`: CSRF 방지용 상태값
**Response:**
- 302 Redirect to `{redirect_uri}?code={auth_code}&state={state}`
#### POST /auth/token
Access Token 발급
**Request Body:**
```json
{
"grant_type": "authorization_code",
"code": "auth_code",
"client_id": "client_id",
"client_secret": "client_secret",
"redirect_uri": "redirect_uri"
}
```
**Response:**
```json
{
"access_token": "eyJ...",
"refresh_token": "eyJ...",
"token_type": "bearer",
"expires_in": 1800,
"scope": "read write"
}
```
### 사용자 관리 (Users)
#### GET /users/me
현재 사용자 정보 조회
**Response:**
```json
{
"id": "user_id",
"email": "user@example.com",
"username": "username",
"full_name": "John Doe",
"role": "user",
"profile_picture": "https://...",
"created_at": "2024-01-01T00:00:00Z",
"last_login": "2024-01-01T00:00:00Z"
}
```
#### PUT /users/me
사용자 정보 수정
**Request Body:**
```json
{
"full_name": "Jane Doe",
"phone_number": "+1234567890",
"birth_date": "1990-01-01",
"gender": "female"
}
```
#### POST /users/me/password
패스워드 변경
**Request Body:**
```json
{
"current_password": "old_password",
"new_password": "new_password"
}
```
#### POST /users/me/profile-picture
프로필 사진 업로드
**Request:**
- Content-Type: multipart/form-data
- File: image file
#### GET /users/me/permissions
사용자 권한 조회
**Response:**
```json
{
"single_sign_on": true,
"share_name": true,
"share_gender": false,
"share_birth_date": false,
"share_email": true,
"share_phone": false
}
```
#### PUT /users/me/permissions
사용자 권한 수정
**Request Body:**
```json
{
"share_gender": true,
"share_birth_date": true
}
```
#### GET /users/me/applications
인증된 애플리케이션 목록
**Response:**
```json
{
"applications": [
{
"id": "app_id",
"name": "Application Name",
"logo_url": "https://...",
"authorized_at": "2024-01-01T00:00:00Z",
"last_used": "2024-01-01T00:00:00Z",
"permissions": ["read", "write"]
}
]
}
```
#### DELETE /users/me/applications/{app_id}
애플리케이션 인증 해제
### 애플리케이션 관리 (Applications)
#### GET /applications
애플리케이션 목록 조회 (Admin only)
#### POST /applications
애플리케이션 등록 (Admin only)
**Request Body:**
```json
{
"app_name": "My Application",
"description": "Application description",
"redirect_uris": ["https://app.example.com/callback"],
"allowed_origins": ["https://app.example.com"],
"theme": {
"primary_color": "#1976d2",
"secondary_color": "#dc004e",
"logo_url": "https://...",
"background_image_url": "https://..."
}
}
```
**Response:**
```json
{
"id": "app_id",
"client_id": "generated_client_id",
"client_secret": "generated_client_secret",
"app_name": "My Application",
"created_at": "2024-01-01T00:00:00Z"
}
```
#### GET /applications/{app_id}
애플리케이션 상세 조회
#### PUT /applications/{app_id}
애플리케이션 수정 (Admin only)
#### DELETE /applications/{app_id}
애플리케이션 삭제 (Admin only)
#### POST /applications/{app_id}/regenerate-secret
Client Secret 재생성 (Admin only)
### 관리자 (Admin)
#### GET /admin/users
전체 사용자 목록 (System Admin only)
**Query Parameters:**
- `page`: 페이지 번호 (default: 1)
- `limit`: 페이지당 항목 수 (default: 20)
- `role`: 역할 필터
- `search`: 검색어
#### GET /admin/users/{user_id}
사용자 상세 조회 (Admin only)
#### PUT /admin/users/{user_id}/role
사용자 역할 변경 (System Admin only)
**Request Body:**
```json
{
"role": "group_admin"
}
```
#### GET /admin/audit-logs
감사 로그 조회 (Admin only)
**Query Parameters:**
- `user_id`: 사용자 ID
- `app_id`: 애플리케이션 ID
- `action`: 액션 타입
- `start_date`: 시작일
- `end_date`: 종료일
#### GET /admin/statistics
통계 정보 조회 (Admin only)
**Response:**
```json
{
"total_users": 1000,
"active_users_today": 150,
"total_applications": 25,
"total_authentications_today": 5000,
"top_applications": [...]
}
```
## 에러 응답
### 에러 응답 형식
```json
{
"error": "error_code",
"message": "Error message",
"details": {}
}
```
### 에러 코드
- `400`: Bad Request
- `401`: Unauthorized
- `403`: Forbidden
- `404`: Not Found
- `409`: Conflict
- `422`: Unprocessable Entity
- `429`: Too Many Requests
- `500`: Internal Server Error
## Rate Limiting
- 일반 API: 100 requests/minute
- 인증 API: 10 requests/minute
- 관리자 API: 1000 requests/minute
## Webhooks
### 이벤트 타입
- `user.created`
- `user.updated`
- `user.deleted`
- `user.login`
- `user.logout`
- `application.authorized`
- `application.revoked`
### Webhook 페이로드
```json
{
"event": "user.login",
"timestamp": "2024-01-01T00:00:00Z",
"data": {
"user_id": "user_id",
"application_id": "app_id",
"ip_address": "192.168.1.1"
}
}
```

173
oauth/docs/apisix-guide.md Normal file
View File

@ -0,0 +1,173 @@
# APISIX API Gateway 가이드
## 개요
Apache APISIX는 고성능 API Gateway로 OAuth 시스템의 모든 API 트래픽을 관리합니다.
## 주요 기능
### 1. API 라우팅
```mermaid
graph LR
Client[클라이언트] --> APISIX[APISIX Gateway]
APISIX --> |/api/v1/auth/*| Auth[인증 서비스]
APISIX --> |/api/v1/users/*| Users[사용자 서비스]
APISIX --> |/api/v1/applications/*| Apps[애플리케이션 서비스]
APISIX --> |/api/v1/admin/*| Admin[관리자 서비스]
APISIX --> |/*| Frontend[프론트엔드]
```
### 2. Rate Limiting 정책
- **인증 API**: 10 req/s (burst: 20)
- **사용자 API**: 100 req/s (burst: 50)
- **애플리케이션 API**: 50 req/s (burst: 25)
- **관리자 API**: 200 req/s (burst: 100)
- **Health Check**: 1000 req/s (burst: 500)
### 3. 보안 플러그인
#### JWT 인증
```yaml
jwt-auth:
key: "user-key"
secret: "my-secret-key"
algorithm: "HS256"
```
#### IP 제한 (관리자 API)
```yaml
ip-restriction:
whitelist:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
```
#### CORS 설정
```yaml
cors:
allow_origins: "*"
allow_methods: "GET,POST,PUT,DELETE,OPTIONS"
allow_headers: "*"
expose_headers: "*"
```
### 4. 캐싱 전략
프론트엔드 정적 리소스에 대한 캐싱:
- 캐시 크기: 메모리 50MB, 디스크 1GB
- 캐시 TTL: 300초
- 캐시 대상: GET, HEAD 요청
- 캐시 상태 코드: 200, 301, 404
## APISIX 대시보드
### 접속 정보
- URL: http://localhost:9000
- 계정: admin / admin123
### 주요 기능
1. **라우트 관리**: API 라우팅 규칙 설정
2. **업스트림 관리**: 백엔드 서비스 설정
3. **플러그인 설정**: 보안, 캐싱, 모니터링 플러그인
4. **모니터링**: 실시간 트래픽 모니터링
## API 호출 예시
### 1. Health Check
```bash
curl http://localhost:9080/health
```
### 2. 인증 API
```bash
# 로그인
curl -X POST http://localhost:9080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"user@example.com","password":"password123"}'
```
### 3. 사용자 API (JWT 토큰 필요)
```bash
curl -X GET http://localhost:9080/api/v1/users/me \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
```
### 4. 관리자 API (IP 제한 + JWT)
```bash
curl -X GET http://localhost:9080/api/v1/admin/users \
-H "Authorization: Bearer ADMIN_JWT_TOKEN"
```
## 프로메테우스 메트릭
APISIX는 Prometheus 메트릭을 제공합니다:
- Endpoint: http://localhost:9091/metrics
- 주요 메트릭:
- `apisix_http_status`: HTTP 상태 코드별 요청 수
- `apisix_http_latency`: 요청 지연 시간
- `apisix_bandwidth`: 대역폭 사용량
## 트러블슈팅
### 1. etcd 연결 실패
```bash
# etcd 상태 확인
docker-compose exec etcd etcdctl endpoint health
# etcd 로그 확인
docker-compose logs etcd
```
### 2. 라우트가 작동하지 않음
```bash
# APISIX Admin API로 라우트 확인
curl http://localhost:9092/apisix/admin/routes
```
### 3. Rate Limiting 디버깅
```bash
# Rate limit 헤더 확인
curl -i http://localhost:9080/api/v1/auth/login
# X-RateLimit-Limit, X-RateLimit-Remaining 헤더 확인
```
## 성능 최적화
### 1. 연결 풀 설정
```yaml
upstream:
keepalive: 320
keepalive_requests: 10000
keepalive_timeout: 60s
```
### 2. 캐시 최적화
```yaml
proxy-cache:
cache_zone:
memory_size: 100m # 메모리 캐시 증가
disk_size: 5G # 디스크 캐시 증가
```
### 3. 로드 밸런싱 알고리즘
- `roundrobin`: 기본 라운드 로빈
- `chash`: 일관된 해싱
- `ewma`: 지수 가중 이동 평균
## 보안 Best Practices
1. **Admin API 보호**
- 프로덕션에서는 Admin API를 내부 네트워크에서만 접근 가능하도록 설정
- Admin Key를 환경 변수로 관리
2. **SSL/TLS 설정**
- 프로덕션에서는 반드시 HTTPS 사용
- Let's Encrypt 또는 상용 인증서 적용
3. **WAF 플러그인 활용**
- SQL Injection 방지
- XSS 공격 방지
- CSRF 토큰 검증
4. **로그 모니터링**
- 비정상적인 트래픽 패턴 감지
- 실패한 인증 시도 추적
- Rate limit 초과 모니터링

209
oauth/docs/architecture.md Normal file
View File

@ -0,0 +1,209 @@
# OAuth 시스템 아키텍처
## 시스템 구성도
```mermaid
graph TB
subgraph "Client Layer"
Browser[사용자 브라우저]
end
subgraph "API Gateway Layer"
APISIX[Apache APISIX<br/>- API Gateway<br/>- Rate Limiting<br/>- Authentication<br/>- Load Balancing]
etcd[etcd<br/>- Service Discovery<br/>- Configuration Store]
end
subgraph "Application Layer"
Backend[FastAPI Backend<br/>- Auth Logic<br/>- JWT Handling<br/>- Business Logic]
Frontend[React Frontend<br/>- Dynamic UI<br/>- Theme Engine<br/>- SPA Routing]
end
subgraph "Data Layer"
MongoDB[MongoDB<br/>- Users<br/>- Apps<br/>- History]
Redis[Redis<br/>- Cache<br/>- Queue<br/>- Session]
Celery[Celery<br/>- Tasks<br/>- Jobs]
Backup[Backup Service<br/>- Cron Jobs<br/>- Archives]
end
Browser -->|HTTP/HTTPS| APISIX
APISIX -->|/api/v1/*| Backend
APISIX -->|/*| Frontend
APISIX <--> etcd
Backend --> MongoDB
Backend --> Redis
Backend --> Celery
Backend --> Backup
```
## 데이터 플로우
### 1. 인증 플로우
```mermaid
sequenceDiagram
participant User as 사용자
participant App as 애플리케이션
participant OAuth as OAuth 서버
participant DB as Database
User->>App: 1. 접속
App->>OAuth: 2. 리다이렉트 (client_id, redirect_uri)
OAuth->>User: 3. 동적 로그인 페이지 렌더링
User->>OAuth: 4. 인증 정보 입력
OAuth->>DB: 5. 인증 검증
OAuth->>User: 6. Authorization Code 발급
User->>App: 7. Code 전달
App->>OAuth: 8. Access Token 요청
OAuth->>App: 9. Access Token 발급
App->>OAuth: 10. 사용자 정보 요청
OAuth->>App: 11. 권한별 사용자 정보 제공
```
### 2. 토큰 관리
- Access Token: 30분 유효
- Refresh Token: 7일 유효
- Token Rotation 정책 적용
## 마이크로서비스 구조
```mermaid
graph LR
subgraph "Core Services"
Auth[Authentication Service]
Authz[Authorization Service]
UserMgmt[User Management Service]
AppService[Application Service]
Audit[Audit Service]
end
subgraph "Support Services"
Cache[Cache Service]
Queue[Queue Service]
Backup[Backup Service]
end
Auth --> Cache
Auth --> Queue
Authz --> Cache
UserMgmt --> Audit
AppService --> Audit
```
### Core Services
1. **Authentication Service**
- 사용자 인증
- 토큰 발급/검증
- 세션 관리
2. **Authorization Service**
- 권한 확인
- 역할 기반 접근 제어 (RBAC)
- 리소스 접근 관리
3. **User Management Service**
- 사용자 CRUD
- 프로필 관리
- 패스워드 관리
4. **Application Service**
- 애플리케이션 등록/관리
- Client Credentials 관리
- 테마 설정 관리
5. **Audit Service**
- 접속 로그
- 인증 히스토리
- 보안 이벤트 추적
## 확장성 고려사항
### Horizontal Scaling
```mermaid
graph TB
LB[Load Balancer]
subgraph "Application Instances"
App1[App Instance 1]
App2[App Instance 2]
App3[App Instance 3]
end
subgraph "Shared State"
Redis[Redis Session Store]
MongoDB[MongoDB Cluster]
end
LB --> App1
LB --> App2
LB --> App3
App1 --> Redis
App1 --> MongoDB
App2 --> Redis
App2 --> MongoDB
App3 --> Redis
App3 --> MongoDB
```
### Database Sharding
- User ID 기반 샤딩
- Application ID 기반 샤딩
- 시간 기반 파티셔닝 (히스토리)
### Caching Strategy
- User Profile 캐싱
- Application Settings 캐싱
- Token 캐싱
## 보안 아키텍처
```mermaid
graph TB
subgraph "External"
Internet[Internet]
end
subgraph "DMZ"
WAF[WAF]
CDN[CDN]
end
subgraph "Public Subnet"
ALB[Application Load Balancer]
NAT[NAT Gateway]
end
subgraph "Private Subnet"
App[Application Servers]
Cache[Cache Layer]
end
subgraph "Data Subnet"
DB[(Database)]
Backup[(Backup Storage)]
end
Internet --> WAF
WAF --> CDN
CDN --> ALB
ALB --> App
App --> Cache
App --> NAT
App --> DB
DB --> Backup
```
### Network Security
- VPC 격리
- Security Groups
- Private Subnets
### Application Security
- Rate Limiting
- DDoS Protection
- WAF Rules
### Data Security
- Encryption at Rest
- Encryption in Transit
- Key Management Service (KMS)