본문으로 건너뛰기

API 인증

D.Hub API는 JWT(JSON Web Token) 기반 인증을 사용합니다. 모든 API 요청에는 유효한 토큰이 필요하며, 토큰은 Authorization 헤더에 Bearer 형식으로 포함합니다.

인증 흐름

로그인으로 토큰 발급하기

로그인은 이메일과 비밀번호로 수행합니다.

cURL

curl -c cookies.txt -X POST https://{host}/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "you@example.com",
"password": "your-password"
}'

Python

import requests

session = requests.Session()
response = session.post(
"https://{host}/api/v1/auth/login",
json={
"email": "you@example.com",
"password": "your-password",
},
)

data = response.json()
access_token = data["access_token"]

JavaScript

const response = await fetch("https://{host}/api/v1/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
email: "you@example.com",
password: "your-password",
}),
});

const { access_token } = await response.json();

응답

{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "bearer"
}

로그인 응답은 refresh_token을 JSON 본문에 포함하지 않습니다. 서버가 HttpOnly 쿠키로 설정하므로 cURL은 쿠키 파일을, Python은 같은 Session 객체를 이어서 사용합니다. 브라우저 JavaScript에서는 쿠키 값을 직접 읽지 않고 credentials: "include"로 전송합니다.

API 호출

발급받은 access_tokenAuthorization 헤더에 포함하여 API를 호출합니다.

curl -X GET https://{host}/api/v1/datasets \
-H "Authorization: Bearer {access_token}"
headers = {"Authorization": f"Bearer {access_token}"}

response = requests.get(
"https://{host}/api/v1/datasets",
headers=headers,
)
토큰 보안
  • 토큰은 소스 코드에 직접 입력하지 않고 환경 변수나 비밀 값 저장소에서 불러옵니다.
  • 클라이언트 코드와 로그에 토큰이 노출되지 않도록 확인합니다.

토큰 갱신

access_token이 만료되면 로그인할 때 받은 refresh_token 쿠키로 새 토큰을 발급받습니다. 요청 본문에는 refresh_token을 넣지 않습니다.

curl -b cookies.txt -X POST https://{host}/api/v1/auth/refresh
response = session.post("https://{host}/api/v1/auth/refresh")

data = response.json()
access_token = data["access_token"]
const response = await fetch("https://{host}/api/v1/auth/refresh", {
method: "POST",
credentials: "include",
});

const { access_token } = await response.json();

서비스 토큰

자동화 스크립트, CI/CD, 외부 시스템 연동에는 서비스 토큰을 사용합니다. 관리자가 서비스 계정을 만든 뒤 POST /api/v1/admin/tokens로 해당 계정의 토큰을 발급합니다. 일반 사용자 계정에는 서비스 토큰을 발급할 수 없습니다.

# 관리자가 서비스 계정의 토큰 발급
curl -X POST https://{host}/api/v1/admin/tokens \
-H "Authorization: Bearer {access_token}" \
-H "Content-Type: application/json" \
-d '{
"user_id": "{service_account_id}",
"name": "data-pipeline-bot",
"description": "자동화 파이프라인 연동용",
"expires_in_days": 180
}'

응답의 token 값은 발급할 때 한 번만 표시됩니다. 안전한 비밀 저장소에 보관하고, 일반 access_token과 동일하게 Authorization: Bearer 헤더로 사용합니다.

curl -X GET https://{host}/api/v1/datasets \
-H "Authorization: Bearer {service_token}"

서비스 계정으로 적재 데이터를 조회하고 외부 데이터베이스에 반영하는 절차는 외부 데이터 조회에서 확인합니다.

발급·조회·폐기 엔드포인트의 요청과 응답은 자동 생성 API 참조admin 토큰 항목에서 확인합니다.

Knowledge Chat API 인증

RAG 기반 Knowledge Chat은 OpenAI Chat Completions와 호환되는 엔드포인트({knowledge_base}/v1/chat/completions)를 제공합니다. 이 엔드포인트는 핵심 API(/api/v1)와 별도의 서비스 주소에서 동작하며, 동일한 JWT 토큰을 api_key로 전달합니다.

from openai import OpenAI

client = OpenAI(
base_url="https://{knowledge_base}/v1", # Knowledge(RAG) 서비스 주소
api_key="{access_token}",
)

response = client.chat.completions.create(
model="{knowledge_id}",
messages=[
{"role": "user", "content": "서울시 교통 현황을 알려줘"}
],
)

일반적인 인증 오류

상태 코드원인해결 방법
401 Unauthorized토큰이 없거나 만료됨로그인하여 새 토큰 발급 또는 토큰 갱신
401 Unauthorized토큰 형식이 잘못됨Bearer 접두사 포함 여부 확인
403 Forbidden해당 자산에 대한 권한 없음관리자에게 접근 권한 요청

다음 단계