DeOAuth Developer Guide

— NATIVE PROTOCOL —

Build secure, decentralized authentication with blockchain-powered OAuth 2.0. Give users full control over their access permissions. 블록체인 기반 OAuth 2.0으로 안전하고 탈중앙화된 인증을 구축하세요. 사용자에게 접근 권한에 대한 완전한 제어권을 부여합니다.

🚀 Quick Start

DeOAuth enables user-controlled access permissions through blockchain technology. Users maintain direct control over their data instead of relying solely on centralized OAuth systems. DeOAuth는 블록체인 기술을 통해 사용자가 접근 권한을 직접 제어할 수 있게 합니다. 중앙화된 OAuth 시스템에만 의존하지 않고 사용자가 데이터를 직접 관리합니다.

1
User Login
Obtain JWT token via email/password 이메일/비밀번호로 JWT 토큰 획득
2
Temporary Auth
Get temporary authorization code 임시 인가 코드 획득
3
Access Token
Exchange for user access token & ID 사용자 액세스 토큰 및 ID 교환
4
Self Session
Manage your own session 자체 세션 관리

Authentication Flow 인증 흐름

🔐
User Login
Client obtains JWT token from DeOAuth API 클라이언트가 DeOAuth API에서 JWT 토큰 획득
🎫
Request Code
Get temporary authorization code 임시 인가 코드 획득
🔑
Exchange Token
Convert code to access token 코드를 액세스 토큰으로 변환
Access Granted
User authenticated successfully 사용자 인증 완료
sequenceDiagram participant User as 👤 User participant Client as 💻 Client App participant DeOAuth as 🔐 DeOAuth Server participant AppServer as 🖥️ App Server Note over User,AppServer: Step 1: User Login User->>Client: Enter email & password Client->>DeOAuth: POST /login_devuser DeOAuth-->>Client: JWT Token Client->>Client: Store JWT in localStorage Note over User,AppServer: Step 2: Request Authorization User->>Client: Access protected resource Client->>DeOAuth: GET /oauth/authorize
(client_id, redirect_uri) DeOAuth->>User: Show authorization page User->>DeOAuth: Approve access DeOAuth-->>Client: Redirect with auth code Note over User,AppServer: Step 3: Exchange Token Client->>AppServer: Forward auth code AppServer->>DeOAuth: POST /oauth/token
(code, client_secret) DeOAuth-->>AppServer: Access Token + User ID
+ Content Address AppServer->>AppServer: Create session AppServer-->>Client: Session cookie Note over User,AppServer: Step 4: Access Granted Client->>AppServer: Request with session AppServer-->>Client: Protected resource

Step 1 User Login사용자 로그인

The first step is to authenticate the user and obtain a JWT token from the DeOAuth platform. This token is required for all subsequent authorization requests. 첫 번째 단계는 사용자를 인증하고 DeOAuth 플랫폼에서 JWT 토큰을 획득하는 것입니다. 이 토큰은 이후 모든 인가 요청에 필요합니다.

POST /v1/dev-user/login_devuser

Request Parameters요청 파라미터

Parameter Type Required Description
email string Required User's email address 사용자의 이메일 주소
password string Required User's password 사용자의 비밀번호
const response = await fetch('http://127.0.0.1:3000/v1/dev-user/login_devuser', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'your-password'
  })
});

const data = await response.json();
const jwtToken = data.token;

localStorage.setItem('deoauth_jwt', jwtToken);
curl -X POST http://127.0.0.1:3000/v1/dev-user/login_devuser \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your-password"
  }'
import requests

response = requests.post(
    'http://127.0.0.1:3000/v1/dev-user/login_devuser',
    json={
        'email': 'user@example.com',
        'password': 'your-password'
    }
)

data = response.json()
jwt_token = data['token']

Response

{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "uuid": "user-uuid-12345"
}

⚠️ Important ⚠️ 중요

Store the JWT token securely in your client application using localStorage, sessionStorage, or cookies. This token is required for the authorization process. JWT 토큰을 클라이언트 애플리케이션에서 localStorage, sessionStorage 또는 쿠키를 사용하여 안전하게 저장하세요. 이 토큰은 인가 프로세스에 필요합니다.

Step 2 Obtain Temporary Authorization Code임시 인가 코드 획득

Before authorizing a user, developers must first receive verification of valid access. This is done by calling the temporary authorization API and receiving a code sent to your configured redirect URI. 사용자를 인가하기 전에 개발자는 유효한 접근에 대한 검증을 받아야 합니다. 임시 인가 API를 호출하여 설정된 리디렉션 URI로 전송된 코드를 수신합니다.

GET /oauth/authorize

Query Parameters쿼리 파라미터

Parameter Type Required Description
client_id string Required Your application's client ID 애플리케이션의 클라이언트 ID
redirect_uri string Required Your registered redirect URI 등록된 리디렉션 URI
response_type string Required Must be "code" "code"여야 합니다
state string Optional CSRF protection token CSRF 보호 토큰
const clientId = 'your-client-id';
const redirectUri = encodeURIComponent('https://your-app.com/callback');
const state = generateRandomString();

const authUrl = `http://127.0.0.1:3000/oauth/authorize?` +
  `client_id=${clientId}&` +
  `redirect_uri=${redirectUri}&` +
  `response_type=code&` +
  `state=${state}`;

window.location.href = authUrl;
curl "http://127.0.0.1:3000/oauth/authorize?\
client_id=your-client-id&\
redirect_uri=https://your-app.com/callback&\
response_type=code&\
state=random-string"
flowchart TB Start([👤 User Accesses
Protected Resource]) BuildURL[💻 Client builds authorization URL
with client_id, redirect_uri, state] Redirect[🌐 Browser redirects to
DeOAuth Server] ShowAuth[🔐 DeOAuth shows
authorization page] UserApprove{👤 User approves
access?} GenCode[✅ Generate temporary
authorization code] RedirectBack[🔄 Redirect to redirect_uri
with code & state] Callback[💻 Client receives code
at callback endpoint] Denied[❌ Access Denied] Start --> BuildURL BuildURL --> Redirect Redirect --> ShowAuth ShowAuth --> UserApprove UserApprove -->|Yes| GenCode UserApprove -->|No| Denied GenCode --> RedirectBack RedirectBack --> Callback style Start fill:#1c1c1c,stroke:#a3e635,color:#efefef style Callback fill:#1c1c1c,stroke:#a3e635,color:#efefef style Denied fill:#1c1c1c,stroke:#ef4444,color:#efefef style UserApprove fill:#1c1c1c,stroke:#f97316,color:#efefef

ℹ️ Callback Response ℹ️ 콜백 응답

After user authorization, DeOAuth redirects back to your redirect_uri with the authorization code: 사용자 인가 후 DeOAuth가 인가 코드와 함께 redirect_uri로 리디렉션합니다: https://your-app.com/callback?code=AUTH_CODE&state=random-string

Step 3 Exchange Code for Access Token액세스 토큰으로 코드 교환

Use the temporary authorization code to obtain the user's access token and unique ID. This information identifies the user and allows you to manage their session. 임시 인가 코드를 사용하여 사용자의 액세스 토큰과 고유 ID를 획득합니다. 이 정보로 사용자를 식별하고 세션을 관리할 수 있습니다.

POST /oauth/token

Request Parameters요청 파라미터

Parameter Type Required Description
client_id string Required Your application's client ID 애플리케이션의 클라이언트 ID
client_secret string Required Your application's client secret 애플리케이션의 클라이언트 시크릿
code string Required Authorization code from Step 2 Step 2의 인가 코드
grant_type string Required Must be "authorization_code" "authorization_code"여야 합니다
redirect_uri string Required Same redirect URI from Step 2 Step 2와 동일한 리디렉션 URI
const response = await fetch('http://127.0.0.1:3000/oauth/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    client_id: 'your-client-id',
    client_secret: 'your-client-secret',
    code: authorizationCode,
    grant_type: 'authorization_code',
    redirect_uri: 'https://your-app.com/callback'
  })
});

const data = await response.json();
const { access_token, user_id, content_address } = data;
curl -X POST http://127.0.0.1:3000/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "your-client-id",
    "client_secret": "your-client-secret",
    "code": "authorization-code",
    "grant_type": "authorization_code",
    "redirect_uri": "https://your-app.com/callback"
  }'
import requests

response = requests.post(
    'http://127.0.0.1:3000/oauth/token',
    json={
        'client_id': 'your-client-id',
        'client_secret': 'your-client-secret',
        'code': authorization_code,
        'grant_type': 'authorization_code',
        'redirect_uri': 'https://your-app.com/callback'
    }
)

data = response.json()
access_token = data['access_token']
user_id = data['user_id']

Response

{
  "success": true,
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "user_id": "user-unique-id-12345",
  "content_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
}
flowchart TB Start([💻 Client receives
authorization code]) ValidateState{🔍 Validate state
parameter?} SendToken[📤 Send POST request to
/oauth/token with code,
client_id, client_secret] ServerValidate[🔐 DeOAuth validates
code & credentials] CheckValid{✅ Valid?} GenerateToken[🔑 Generate Access Token
+ User ID
+ Content Address] StoreUser[💾 Find or create user
in database by User ID] CreateSession[🎫 Create application
session] Success([✅ User authenticated
& logged in]) Error[❌ Invalid state
CSRF attack prevented] TokenError[❌ Invalid code or
credentials error] Start --> ValidateState ValidateState -->|Valid| SendToken ValidateState -->|Invalid| Error SendToken --> ServerValidate ServerValidate --> CheckValid CheckValid -->|Yes| GenerateToken CheckValid -->|No| TokenError GenerateToken --> StoreUser StoreUser --> CreateSession CreateSession --> Success style Start fill:#1c1c1c,stroke:#888888,color:#efefef style Success fill:#1c1c1c,stroke:#a3e635,color:#efefef style Error fill:#1c1c1c,stroke:#ef4444,color:#efefef style TokenError fill:#1c1c1c,stroke:#ef4444,color:#efefef style GenerateToken fill:#1c1c1c,stroke:#f97316,color:#efefef

ℹ️ Blockchain Integration ℹ️ 블록체인 통합

If your content requires blockchain authorization (DAPP with ERC-20 contract), the response includes a 콘텐츠에 블록체인 인가(ERC-20 컨트랙트가 있는 DAPP)가 필요한 경우, 응답에 content_address field. This is the user's blockchain EOA wallet address for token transfers on the XOTN Network. 필드가 포함됩니다. 이것은 XOTN 네트워크에서 토큰 이전을 위한 사용자의 블록체인 EOA 지갑 주소입니다.

Authorization Successful! 인가 완료!

User is now authenticated and can access protected resources. 사용자가 인증되어 보호된 리소스에 접근할 수 있습니다.

Step 4 Manage Self Session자체 세션 관리

After completing the DeOAuth authorization and verifying user information, your application manages its own session between the client (browser) and your server. DeOAuth 인가를 완료하고 사용자 정보를 검증한 후, 애플리케이션은 클라이언트(브라우저)와 서버 간의 자체 세션을 관리합니다.

Session Management세션 관리

  • Session Creation: After successful authentication, create a session in your application using the user_id성공적인 인증 후 user_id를 사용하여 애플리케이션에 세션을 생성하세요
  • Session Storage: Store the access token and user information securely on your server서버에서 액세스 토큰과 사용자 정보를 안전하게 저장하세요
  • Re-authorization: DeOAuth re-authorization is only required when:DeOAuth 재인가는 다음 경우에만 필요합니다:
    • Your self-session has expired자체 세션이 만료된 경우
    • User explicitly logs out of your application사용자가 애플리케이션에서 명시적으로 로그아웃한 경우
    • Access token has expired (check expires_in value)액세스 토큰이 만료된 경우(expires_in 값 확인)
app.post('/callback', async (req, res) => {
  const { code } = req.query;
  
  const tokenResponse = await exchangeCodeForToken(code);
  const { access_token, user_id } = tokenResponse;
  
  req.session.userId = user_id;
  req.session.accessToken = access_token;
  
  const user = await findOrCreateUser(user_id);
  
  res.redirect('/dashboard');
});

app.get('/dashboard', ensureAuthenticated, (req, res) => {
  const userId = req.session.userId;
  res.render('dashboard', { userId });
});
@app.route('/callback')
def callback():
    code = request.args.get('code')
    
    token_response = exchange_code_for_token(code)
    access_token = token_response['access_token']
    user_id = token_response['user_id']
    
    session['user_id'] = user_id
    session['access_token'] = access_token
    
    user = find_or_create_user(user_id)
    
    return redirect('/dashboard')

@app.route('/dashboard')
@login_required
def dashboard():
    user_id = session.get('user_id')
    return render_template('dashboard.html', user_id=user_id)

⚠️ Security Best Practices ⚠️ 보안 모범 사례

Always validate the CSRF 공격을 방지하기 위해 state parameter to prevent CSRF attacks. Store access tokens securely on the server-side, never expose them in client-side JavaScript or URLs. 파라미터를 항상 검증하세요. 서버 측에서 액세스 토큰을 안전하게 저장하고, 클라이언트 측 JavaScript나 URL에 노출하지 마세요.

🎮 ERC-20 Token Transfers (Optional)ERC-20 토큰 이전 (선택 사항)

For blockchain-integrated applications (DAPPs), DeOAuth provides ERC-20 token transfer capabilities on the XOTN Network. This enables in-app economies, rewards, and transferable assets. 블록체인 통합 애플리케이션(DAPP)을 위해 DeOAuth는 XOTN 네트워크에서 ERC-20 토큰 이전 기능을 제공합니다. 이를 통해 인앱 경제, 보상 및 이전 가능한 자산을 지원합니다.

Use Cases활용 사례

  • Gaming: Transfer tokens between players based on game outcomes (winner/loser)게임 결과(승자/패자)에 따라 플레이어 간 토큰 이전
  • Rewards: Distribute tokens as rewards for user actions사용자 행동에 대한 보상으로 토큰 배포
  • Marketplace: Enable token-based transactions for digital assets디지털 자산에 대한 토큰 기반 거래 지원
  • Access Control: Grant content access based on token ownership토큰 소유권에 따른 콘텐츠 접근 부여

ℹ️ Token Details ℹ️ 토큰 세부 정보

XOTN Network uses XOTN as its native token. The XOTN 네트워크는 XOTN을 네이티브 토큰으로 사용합니다. 인증 응답의 content_address field in the authentication response is the user's EOA (Externally Owned Account) wallet address for receiving tokens. 필드는 토큰을 받기 위한 사용자의 EOA(외부 소유 계정) 지갑 주소입니다.

async function transferTokens(fromAddress, toAddress, amount) {
  const response = await fetch('http://127.0.0.1:3000/v1/token/transfer', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
      from_address: fromAddress,
      to_address: toAddress,
      amount: amount,
      contract_address: '0xbCB8699bc8A580Bf418F052e651Be6E96E17b94C'
    })
  });
  
  const result = await response.json();
  return result.transaction_hash;
}
curl -X POST http://127.0.0.1:3000/v1/token/transfer \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -d '{
    "from_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
    "to_address": "0x8ba1f109551bD432803012645Ac136ddd64DBA72",
    "amount": "100",
    "contract_address": "0xbCB8699bc8A580Bf418F052e651Be6E96E17b94C"
  }'