---
title: "Require a Token"
description: "ให้ HTTP server ของ cafe-mcp รับเฉพาะ request ที่มี token ของตัวเอง ทดสอบด้วย curl แล้วต่อ Claude Code โดยไม่เขียน token ลงไฟล์ config"
canonical_url: "https://iamthana.com/courses/mcp-security/auth"
---

> Index of every page on this site: [llms.txt](https://iamthana.com/llms.txt)

`http_server.py` ตอนนี้ใครต่อถึง port 8765 ก็เรียก tool ได้หมดครับ บทนี้ให้มันรับเฉพาะ request ที่มี token

ทุกคำสั่งรันในโฟลเดอร์ `cafe-mcp` จากบท [Set Up the Security Lab](https://iamthana.com/courses/mcp-security/lab)

## What Is Authorization in MCP

authorization ใน MCP เป็นของเสริม และใช้กับ transport แบบ HTTP เท่านั้น server แบบ stdio ที่ Claude Code เปิดเป็น subprocess (อย่าง `cafe` ในคอร์สแรก) ไม่ต้องมี token เพราะมันรันด้วยสิทธิ์ของคนที่เปิดมันอยู่แล้ว บทนี้เลยใส่ auth ที่ทางเข้า HTTP อย่างเดียว

MCP ใช้ OAuth ซึ่งแบ่งหน้าที่เป็นสองฝั่ง ฝั่งที่ให้ผู้ใช้ login แล้วออก token เรียกว่า authorization server ส่วน MCP server ของเราเป็น **resource server** มีหน้าที่แค่ตรวจ token ที่ client แนบมา ไม่ได้ออก token เอง

สิ่งที่ spec กำหนดให้ server ทำ กับสิ่งที่ `cafe-mcp` ทำในบทนี้

<table>
<thead>
  <tr>
    <th>
      Spec Requires
    </th>
    
    <th>
      <code>
        cafe-mcp
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      MUST มีเอกสาร Protected Resource Metadata (RFC 9728) บอกว่า token ต้องไปขอจากที่ไหน
    </td>
    
    <td>
      SDK เปิดให้ที่ <code>
        /.well-known/oauth-protected-resource/mcp
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      ตอบ <code>
        401
      </code>
      
       พร้อม <code>
        resource_metadata
      </code>
      
       ใน header <code>
        WWW-Authenticate
      </code>
    </td>
    
    <td>
      ได้จาก SDK
    </td>
  </tr>
  
  <tr>
    <td>
      MUST ตรวจว่า token ออกให้ server นี้ (audience)
    </td>
    
    <td>
      <code>
        validate_token_resource=True
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      token ที่ผิดหรือหมดอายุ MUST ได้ <code>
        401
      </code>
    </td>
    
    <td>
      ได้จาก SDK
    </td>
  </tr>
  
  <tr>
    <td>
      MUST NOT ส่ง token ของ client ต่อไปเรียก API อื่น (token passthrough)
    </td>
    
    <td>
      <code>
        cafe-mcp
      </code>
      
       ไม่เรียก API ภายนอก ดูต่อในบท <a href="/courses/mcp-security/http-attacks">
        HTTP Attacks
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      token ที่สิทธิ์ไม่พอ SHOULD ได้ <code>
        403
      </code>
      
       กับ <code>
        error="insufficient_scope"
      </code>
    </td>
    
    <td>
      ได้ <code>
        403
      </code>
      
       แต่ไม่มี <code>
        scope=
      </code>
      
       (ดู Pitfalls ของบท <a href="/courses/mcp-security/scopes">
        Limit Tools by Scope
      </a>
      
      )
    </td>
  </tr>
</tbody>
</table>

ระบบจริงตรวจ token ด้วยลายเซ็น JWT หรือถาม authorization server กลับไป (introspection) แล้วเช็กว่าใครออก ยังไม่หมดอายุ และออกให้ server นี้ บทนี้ไม่มี authorization server เลยใช้ `DemoTokenVerifier` เทียบ token กับค่าใน environment variable 4 ตัวแทน ตัวนี้ใช้ทดลองในเครื่องเท่านั้นนะครับ (เหตุผลอยู่ใน Pitfalls)

token ทดลองมี 4 ตัว ต่างกันที่ scope กับ server ที่ token ออกให้

<table>
<thead>
  <tr>
    <th>
      Environment Variable
    </th>
    
    <th>
      Client
    </th>
    
    <th>
      Scopes
    </th>
    
    <th>
      Issued For
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        CAFE_STAFF_TOKEN
      </code>
    </td>
    
    <td>
      <code>
        staff-demo
      </code>
    </td>
    
    <td>
      <code>
        orders:read
      </code>
      
       <code>
        orders:write
      </code>
    </td>
    
    <td>
      <code>
        http://127.0.0.1:8765/mcp
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CAFE_VIEWER_TOKEN
      </code>
    </td>
    
    <td>
      <code>
        viewer-demo
      </code>
    </td>
    
    <td>
      <code>
        orders:read
      </code>
    </td>
    
    <td>
      <code>
        http://127.0.0.1:8765/mcp
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CAFE_GUEST_TOKEN
      </code>
    </td>
    
    <td>
      <code>
        guest-demo
      </code>
    </td>
    
    <td>
      ไม่มี
    </td>
    
    <td>
      <code>
        http://127.0.0.1:8765/mcp
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        CAFE_FOREIGN_TOKEN
      </code>
    </td>
    
    <td>
      <code>
        foreign-demo
      </code>
    </td>
    
    <td>
      <code>
        orders:read
      </code>
      
       <code>
        orders:write
      </code>
    </td>
    
    <td>
      <code>
        http://127.0.0.1:9999/other
      </code>
    </td>
  </tr>
</tbody>
</table>

`CAFE_FOREIGN_TOKEN` จำลอง token ที่ออกให้บริการอื่น scope ครบทุกตัวแต่ Issued For ไม่ใช่ server นี้ เลยต้องโดนปฏิเสธ

ทุก request ที่ `/mcp` ต้องมี `orders:read` รวมทั้ง `list_menu` ที่ดูแค่เมนู เพราะ resource ของออร์เดอร์มีชื่อลูกค้า และใช้กฎเดียวทั้ง endpoint ง่ายกว่าแยกทีละตัว ส่วน `orders:write` สำหรับ tool ที่แก้ข้อมูลอยู่ในบท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes)

## Write the Code

- สร้าง token ทดลอง
- เขียน `auth.py`
- ต่อ auth เข้ากับ `mcp` ใน `cafe_server.py`

### 1. Demo Tokens

สุ่ม token สี่ตัวลงไฟล์ `tokens.env` แล้วใส่ไฟล์นี้ใน `.gitignore` ก่อนทำอย่างอื่น token ห้ามเข้า git เพราะใครเปิด repo ได้ก็เอาไปใช้ได้

```bashtangle=run
for name in STAFF VIEWER GUEST FOREIGN; do echo "export CAFE_${name}_TOKEN=$(openssl rand -hex 24)"; done > tokens.env
echo tokens.env >> .gitignore
source tokens.env
```

`source tokens.env` ต้องทำในทุก terminal ที่ใช้ token ทั้งหน้าต่างที่รัน server และหน้าต่างที่ส่ง curl เพราะ environment variable ไม่ตามไปหน้าต่างอื่นให้เอง

### 2. auth.py

```python [auth.py]
import hmac
import os

from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError

RESOURCE_URL = "http://127.0.0.1:8765/mcp"

# environment variable -> (client id, scopes, resource the token was issued for)
DEMO_TOKENS = {
    "CAFE_STAFF_TOKEN": ("staff-demo", ["orders:read", "orders:write"], RESOURCE_URL),
    "CAFE_VIEWER_TOKEN": ("viewer-demo", ["orders:read"], RESOURCE_URL),
    "CAFE_GUEST_TOKEN": ("guest-demo", [], RESOURCE_URL),
    "CAFE_FOREIGN_TOKEN": ("foreign-demo", ["orders:read", "orders:write"], "http://127.0.0.1:9999/other"),
}

AUTH_SETTINGS = AuthSettings(
    issuer_url="https://auth.example.com",
    resource_server_url=RESOURCE_URL,
    required_scopes=["orders:read"],
    validate_token_resource=True,
)


class DemoTokenVerifier:
    """Stands in for JWT or introspection checks against a real authorization server."""

    async def verify_token(self, token: str) -> AccessToken | None:
        for variable, (client_id, scopes, resource) in DEMO_TOKENS.items():
            expected = os.environ.get(variable, "")
            if expected and hmac.compare_digest(token.encode(), expected.encode()):
                return AccessToken(token=token, client_id=client_id, scopes=scopes, resource=resource)
        return None


def require_scope(scope: str) -> None:
    # No access token means stdio or an in-process client; over HTTP the endpoint rejects requests without one.
    access_token = get_access_token()
    if access_token is not None and scope not in access_token.scopes:
        raise ToolError(f"This token cannot change orders: missing scope {scope}.")
```

`require_scope` ท้ายไฟล์ยังไม่ได้ใช้ในบทนี้ จะใช้ในบท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes)

- `AuthSettings` บอก SDK ว่า server นี้เป็น resource server ที่ `RESOURCE_URL` ส่วน `issuer_url` คือ authorization server ที่ client ต้องไปขอ token spec บังคับให้ metadata มีอย่างน้อยหนึ่งตัว บทนี้ไม่มี authorization server เลยใส่ `https://auth.example.com` เป็นที่อยู่สมมติไว้
- `required_scopes=["orders:read"]` ทำสองอย่าง SDK ปฏิเสธ request ของ token ที่ไม่มี scope นี้ด้วย `403` และเขียน scope นี้เป็น `scopes_supported` ใน metadata
- `validate_token_resource=True` ให้ SDK เทียบ `AccessToken.resource` กับ `resource_server_url` token ที่ออกให้ resource อื่นได้ `401` ถ้าไม่ตั้งค่านี้ SDK 2.3.0 ยอมรับ token ของ resource อื่นและเตือนว่าเวอร์ชัน 3.0 จะเปลี่ยนค่าเริ่มต้นเป็น `True`
- `verify_token` คืน `AccessToken` ถ้า token ตรงกับตัวแปรตัวใดตัวหนึ่ง และคืน `None` ถ้าไม่ตรง ซึ่ง SDK แปลงเป็น `401`
- `hmac.compare_digest` เทียบ token ด้วยเวลาคงที่ คนโจมตีเลยเดาจากเวลาตอบไม่ได้ว่าตรงไปกี่ตัวอักษรแล้ว ต้องแปลงเป็น bytes ก่อน เพราะ `str` ที่มีอักขระนอก ASCII ทำให้มัน raise `TypeError`
- `if expected` กันตัวแปรที่ไม่ได้ตั้งค่า ตัวแปรว่างจะไม่ตรงกับ token ว่างที่ client ส่งมา

### 3. Wire Auth into cafe_server.py

แก้สองจุดใน `cafe_server.py` คือ import กับการสร้าง `mcp`

```diff [cafe_server.py]
+from auth import AUTH_SETTINGS, DemoTokenVerifier, require_scope
 from database import connect

-mcp = MCPServer("cafe")
+mcp = MCPServer("cafe", auth=AUTH_SETTINGS, token_verifier=DemoTokenVerifier())
```

เทสต์ 14 ตัวจากบท [Test with pytest](https://iamthana.com/courses/mcp-server/testing) ยังผ่านโดยไม่ต้องแก้ เพราะ `Client(mcp)` ไม่มี token ให้ตรวจ

`http_server.py` ไม่ต้องแก้ เพราะค่า auth ติดอยู่กับ `mcp` ตั้งแต่ตอนสร้าง `mcp.run(transport="streamable-http")` เลยตรวจ token และเปิด metadata ให้เอง ส่วน `python cafe_server.py` แบบ stdio ไม่ผ่านชั้นนี้

## Test with curl

- รัน server และเตรียมคำสั่ง
- request ที่ไม่ผ่าน authentication
- token ที่ผ่านแต่สิทธิ์ไม่พอ
- metadata
- token ที่ใช้ได้

### Start the Server

หยุด `http_server.py` ที่รันค้างจากบทก่อน (Ctrl+C) แล้วรันใหม่ในหน้าต่างเดิม server จะโหลด `cafe_server.py` ที่เพิ่งแก้

```bash
source tokens.env
uv run python http_server.py
```

เปิดอีกหน้าต่างสำหรับ curl แล้วตั้งตัวแปรกับฟังก์ชันช่วย `META` ตัวนี้ประกาศ `elicitation` เหมือนในบท [Confirm Actions with Elicitation](https://iamthana.com/courses/mcp-server/orders)

```bash
source tokens.env
URL=http://127.0.0.1:8765/mcp
META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{"elicitation":{}}}'

call_tool() {
  curl -s -i $URL \
    -H "Authorization: Bearer $1" \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json, text/event-stream' \
    -H 'MCP-Protocol-Version: 2026-07-28' \
    -H 'Mcp-Method: tools/call' \
    -H "Mcp-Name: $2" \
    -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$2\",\"arguments\":$3,$4$META}}" \
    | tr -d '\r' | grep -iE '^(HTTP/|www-authenticate:|\{)'
}
```

`call_tool TOKEN ชื่อtool arguments` ส่ง `tools/call` พร้อม header `Authorization` parameter ตัวที่ 4 ไว้แทรก field เพิ่มใน `params` ใช้ในบท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes) `-i` พิมพ์ header ของ response ด้วย แล้ว `grep` เหลือเฉพาะบรรทัดสถานะ `www-authenticate` และ body

### No Token

request แรกไม่แนบ `Authorization`

```bash
curl -s -i $URL \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -H 'Mcp-Method: tools/call' \
  -H 'Mcp-Name: list_menu' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"list_menu\",\"arguments\":{},$META}}" \
  | tr -d '\r' | grep -iE '^(HTTP/|www-authenticate:|\{)'
```

```text [$ curl -s -i $URL]
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer error="invalid_token", error_description="Authentication required", resource_metadata="http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp"
{"error": "invalid_token", "error_description": "Authentication required"}
```

ได้ `401` พร้อม `resource_metadata` ที่ชี้ไปเอกสาร metadata client ที่ทำตาม spec จะอ่าน URL นี้แล้วไปขอ token ต่อเอง ส่วน body ไม่บอกอะไรเกี่ยวกับ tool เลย เพราะ request โดนปฏิเสธก่อนถึงโค้ดของ MCP

### Wrong Token

```bash
call_tool wrong-token list_menu '{}'
```

token ที่ server ไม่รู้จักได้ `401` ตัวเดียวกับไม่ส่ง token เลย

### Token for Another Resource

```bash
call_tool "$CAFE_FOREIGN_TOKEN" list_menu '{}'
```

ได้ `401` ตัวเดียวกับข้างบนทุกตัวอักษร ทั้งที่ token นี้มี scope ครบ เพราะมันออกให้ `http://127.0.0.1:9999/other` ไม่ใช่ server นี้ client จะไม่รู้ว่าผิดเพราะอะไร เหตุผลอยู่ใน log ของ server

```text [terminal ที่รัน http_server.py]
WARNING  Bearer token resource 'http://127.0.0.1:9999/other' is not resource_server_url http://127.0.0.1:8765/mcp
```

### Token Without Scope

```bash
call_tool "$CAFE_GUEST_TOKEN" list_menu '{}'
```

```text [$ call_tool "$CAFE_GUEST_TOKEN" list_menu '{}'][$ call_tool "$CAFE_GUEST_TOKEN" list_menu '']
HTTP/1.1 403 Forbidden
www-authenticate: Bearer error="insufficient_scope", error_description="Required scope: orders:read", resource_metadata="http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp"
{"error": "insufficient_scope", "error_description": "Required scope: orders:read"}
```

token ถูกต้องแต่ไม่มี `orders:read` ได้ `403` กับ `error="insufficient_scope"` จำง่าย ๆ ว่า `401` คือ server ไม่รู้ว่าเราเป็นใคร ส่วน `403` คือรู้แล้วแต่สิทธิ์ไม่พอ

### Protected Resource Metadata

```bash
curl -s http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp | python3 -m json.tool
```

```json [$ curl -s http://127.0.0.1:8765/.well-known/oauth-protected-resource/mcp]
{
    "resource": "http://127.0.0.1:8765/mcp",
    "authorization_servers": [
        "https://auth.example.com"
    ],
    "scopes_supported": [
        "orders:read"
    ],
    "bearer_methods_supported": [
        "header"
    ]
}
```

หน้านี้อ่านได้โดยไม่ต้องมี token เพราะ client ต้องอ่านก่อนถึงจะรู้ว่าไปขอ token ที่ไหน path คือ `/.well-known/oauth-protected-resource` ต่อด้วย path ของ endpoint (`/mcp`) ตาม RFC 9728

`scopes_supported` มีแค่ `orders:read` เพราะ SDK เอามาจาก `required_scopes` ส่วน `orders:write` ไม่อยู่ในนี้ (ผลของเรื่องนี้อยู่ใน Pitfalls ของบท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes))

### Valid Token

token `viewer` มี `orders:read` อย่างเดียว

```bash
call_tool "$CAFE_VIEWER_TOKEN" list_menu '{"max_price_thb":50}'
```

```text [$ call_tool "$CAFE_VIEWER_TOKEN" list_menu '{"max_price_thb":50}'][$ call_tool "$CAFE_VIEWER_TOKEN" list_menu '']
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"{\n  \"name\": \"thai tea\",\n  \"price_thb\": 45,\n  \"available\": false\n}","type":"text"},{"text":"{\n  \"name\": \"americano\",\n  \"price_thb\": 50,\n  \"available\": true\n}","type":"text"}],"isError":false,"resultType":"complete","structuredContent":{"result":[{"name":"thai tea","price_thb":45,"available":false},{"name":"americano","price_thb":50,"available":true}]},"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

## Try It in Claude Code

- เอา `cafe` แบบ stdio ออกชั่วคราว
- ลงทะเบียน `cafe-auth` โดยไม่ให้ token อยู่ในไฟล์
- ตรวจสถานะการเชื่อมต่อด้วย token ของ staff
- ดูผลของการลงทะเบียนโดยไม่มี header

Claude Code ต่อ server ที่ต้องใช้ token ได้สองทาง คือ login แบบ OAuth ผ่าน `/mcp` (ต้องมี authorization server ซึ่งบทนี้ไม่มี) กับส่ง header `Authorization` ไปกับทุก request บทนี้ใช้ทางที่สองครับ

<steps level="3">

### Remove the stdio Server

`cafe` แบบ stdio จากคอร์สแรกไม่มี auth ถ้าปล่อยไว้ Claude Code อาจเลือกเรียก tool จากตัวนั้นแทน แล้วการตรวจ token ทั้งหมดก็ไม่มีความหมาย ถอดออกก่อนครับ

```bash
claude mcp remove --scope project cafe
```

ตรวจว่า terminal ที่รัน `http_server.py` ยังทำงานอยู่ (ถ้าปิดไปแล้วให้รัน `source tokens.env` แล้ว `uv run python http_server.py` ใหม่)

### Register with a Variable

ระวังตรงนี้นะครับ ถ้าใช้ `claude mcp add ... --header "Authorization: Bearer $CAFE_STAFF_TOKEN"` shell จะแทนค่าตัวแปรก่อน token ตัวจริงเลยถูกเขียนลง `.mcp.json` ซึ่งเป็นไฟล์ที่ docs ของ Claude Code แนะนำให้ commit เข้า git

ทางที่ถูกคือเขียน `${CAFE_STAFF_TOKEN}` ลงไฟล์ไปเลย Claude Code แทนค่าให้ตอนรัน ใช้ `claude mcp add-json` แล้วครอบ JSON ด้วย single quote ไม่ให้ shell แทนค่า

```bash
claude mcp add-json cafe-auth '{"type":"http","url":"http://127.0.0.1:8765/mcp","headers":{"Authorization":"Bearer ${CAFE_STAFF_TOKEN}"}}' --scope project
```

```text [$ claude mcp add-json cafe-auth ... --scope project]
Added http MCP server cafe-auth to project config
```

รายการที่เขียนลง `.mcp.json` ยังเป็นชื่อตัวแปร

```json [.mcp.json]tangle=skip
"cafe-auth": {
  "type": "http",
  "url": "http://127.0.0.1:8765/mcp",
  "headers": {
    "Authorization": "Bearer ${CAFE_STAFF_TOKEN}"
  }
}
```

ตรวจด้วย `claude mcp get`

```bash
claude mcp get cafe-auth
```

```text [$ claude mcp get cafe-auth]
cafe-auth:
  Scope: Project config (shared via .mcp.json)
  Status: ⏸ Pending approval (run `claude` to approve)
  Type: http
  URL: http://127.0.0.1:8765/mcp
  Headers:
    Authorization: Bearer ${CAFE_STAFF_TOKEN}

To remove this server, run: claude mcp remove cafe-auth -s project
```

`Pending approval` เป็นปกติของ server ที่เพิ่งเพิ่มใน project scope ต้องรัน `claude` เพื่ออนุมัติก่อน

### Check the Connection

เปิด `claude` จากหน้าต่างที่ `source tokens.env` แล้ว เพราะ Claude Code อ่านตัวแปรตอนเปิดโปรแกรม

```bash
source tokens.env
claude
```

Claude Code ถามว่า `New MCP server found in this project: cafe-auth` เหมือนหน้าอนุมัติของ `cafe` ในบท [Build Your First Tool](https://iamthana.com/courses/mcp-server/first-tool) อนุมัติแล้วพิมพ์ `/mcp` เลือก `cafe-auth`

![หน้า /mcp ของ Claude Code เลือก cafe-auth แสดง Status connected, Auth authenticated, Protocol 2026-07-28, URL http://127.0.0.1:8765/mcp, Capabilities tools, resources, prompts และ Tools 3 tools](https://iamthana.com/images/courses/mcp-security/claude-auth-connected.webp)

ขึ้น `Auth: ✔ authenticated` กับ 3 tools แปลว่า token ของ staff ผ่าน หน้านี้ไม่แสดงค่า token ให้เห็นด้วย

### Without a Token

ออกจาก Claude Code (`/exit`) แล้วลองลงทะเบียนโดยไม่มี header

```bash
claude mcp remove --scope project cafe-auth
claude mcp add --transport http --scope project cafe-auth http://127.0.0.1:8765/mcp
```

เปิด `claude` แล้วพิมพ์ `/mcp` จะเห็น `✘ cafe-auth` เลือกดูรายละเอียดได้หน้านี้

![หน้า /mcp ของ Claude Code เลือก cafe-auth แสดง Status failed, Issue getaddrinfo ENOTFOUND auth.example.com, Auth not authenticated และตัวเลือก 1 Authenticate, 2 Reconnect, 3 Disable](https://iamthana.com/images/courses/mcp-security/claude-auth-no-token.webp)

Claude Code ได้ `401` แล้วตาม `resource_metadata` ไปหา authorization server ที่ `auth.example.com` เอง แต่ host นี้เป็นที่อยู่สมมติใน `AuthSettings` เลยขึ้น `ENOTFOUND` และมีปุ่ม Authenticate ให้กด ถ้าเรามี authorization server จริง ตรงนี้คือหน้า login แบบ OAuth

ออกจาก Claude Code อีกครั้ง ถอด `cafe-auth` ตัวที่ไม่มี header ออก แล้วลงทะเบียนใหม่ด้วย token ของ staff โดยใช้คำสั่ง `claude mcp add-json` ในขั้น Register with a Variable บท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes) ใช้ `cafe-auth` ตัวนั้นต่อ

</steps>

## Pitfalls

- ถ้าเปิด `claude` จากหน้าต่างที่ไม่ได้ `source tokens.env` Claude Code จะส่ง `Bearer ${CAFE_STAFF_TOKEN}` ไปเป็นข้อความตรง ๆ server ตอบ `401` ดูชื่อตัวแปรที่หายไปได้จาก `claude mcp list`
- เปลี่ยน token ใน `tokens.env` แล้วต้องรัน server กับ `claude` ใหม่ทั้งคู่ เพราะทั้งสองอ่านตัวแปรตอนเริ่ม
- `DemoTokenVerifier` ใช้บน production ไม่ได้ token ไม่มีวันหมดอายุ เพิกถอนไม่ได้ ตัวจริงต้องตรวจลายเซ็นหรือ introspection, issuer, วันหมดอายุ และ audience แล้วใส่ `expires_at` กับ `resource` ลงใน `AccessToken`
- token บน http ธรรมดาใครดัก request ระหว่างทางก็อ่านได้ (mitmproxy ในคอร์สแรกโชว์ให้เห็นแล้ว) auth แทน TLS ไม่ได้ ถ้าเอา server ออกนอกเครื่อง ต้องวาง HTTPS ไว้ข้างหน้า
- อย่าส่ง token ใน URL query string spec ห้ามไว้ และถึง SDK จะตอบ `401` แต่ URL เต็มก็ลง access log ของ uvicorn ไปแล้ว ใช้ header `Authorization` เท่านั้น

## Summary

ตอนนี้ทางเข้า HTTP ของ `cafe-mcp` ต้องมี token แล้วครับ ไม่มี token, token ผิด หรือ token ของ server อื่นได้ `401` ส่วน token ที่ไม่มี `orders:read` ได้ `403` และ Claude Code ต่อเข้ามาด้วย `${VAR}` โดยไม่มี token อยู่ในไฟล์ที่ commit

บทถัดไป [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes) ให้ tool ที่แก้ข้อมูลเช็ก `orders:write` ก่อนทำงาน

## References

- [Authorization (spec 2026-07-28)](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
- [RFC 9728: OAuth 2.0 Protected Resource Metadata](https://datatracker.ietf.org/doc/html/rfc9728)
- [Claude Code: Connect to MCP servers](https://code.claude.com/docs/en/mcp)
- [OWASP MCP Top 10](https://owasp.org/projects/mcp-top-10)

## Sitemap

See the full [sitemap](https://iamthana.com/sitemap.md) for all pages.
