Token บนมือถือ

token สองตัว ตู้เซฟหนึ่งใบ และการ refresh ที่ไม่ควรมีใครรู้สึก ดูมันวิ่งระหว่างมือถือ SecureStore กับ API แล้วลองทำให้พัง: สามหน้าจอพร้อมกัน token โดนขโมย และ logout

ระดับ: ลึกดู 17 ขั้น · ราว 1 นาทีครึ่งหมดอายุ ชนกัน ขโมย logoutจำ 3 คำถาม · 8 การ์ดเทียบ 4 แบบTypeScript · Jest

สิ่งที่จะได้

  • อธิบายได้ว่าทำไมใช้ access token อายุสั้นคู่กับ refresh token อายุยาว ไม่ใช้ตัวเดียวอายุยาว
  • refresh เงียบ ๆ ตอนได้ 401 ทีละครั้ง ส่วน request อื่นที่ได้ 401 ด้วยก็รอผลเดียวกัน
  • รู้ว่า rotation จับ refresh token ที่ถูกขโมยได้ยังไง แลกกับการ login ใหม่หนึ่งครั้ง
  • logout ให้ server ยกเลิก token ก่อน แล้วค่อยลบในเครื่อง สำเนาที่หลุดไปจะได้ใช้ไม่ได้

สรุป 1 นาที

กดข้อไหน ภาพข้างล่างจะเล่นขั้นนั้นให้ดู

4เทียบทุกแบบ
ได้ 401: refresh ทีละครั้งaccess 15 min · refresh 30 d
API · ยังไม่มี tokenไม่มี token
นาทีที่ 0
Keychain / Keystore · ว่าง
ร้านค้าmai@example.com••••••••Sign in
POST /login → …
ขั้น 1 / 17 · กดทีละขั้น
0refresh ที่สำเร็จ
0ได้ 200
ยังยัง login อยู่ไหม

ในภาพ: มือถือเครื่องใหญ่โชว์แอปร้านค้าแบบที่ผู้ใช้เห็น ข้าง ๆ คือตู้เซฟ Keychain ที่เก็บ token สองตัว (สีทองคือ access สีฟ้าคือ refresh เป็นสีเทาเมื่อหมดอายุหรือใช้แล้ว เป็นสีแดงเมื่อถูกยกเลิก) ตึก API เก็บชุดของ refresh token ไว้บนดาดฟ้า และนาฬิกานับนาทีตั้งแต่ login request คือดวงไฟที่วิ่งบนถนน 15 นาทีกับ 30 วันเป็นตัวอย่าง และทุกคำตอบมาจาก server จำลองตัวเล็ก ๆ

ขั้นที่ 4 · ปล่อยทุกแบบวิ่งพร้อมกัน

เทียบทุกแบบ: token บนมือถือ

แอปเดียวกันถือ token สี่แบบ แล้วเจอสี่เรื่องเรียงกัน: access หมดอายุ, สาม request ได้ 401 พร้อมกัน, มีคนอ่านไฟล์ของแอป และ token หลุดไปทาง log ✓ คือผู้ใช้ไม่หลุดและคนอื่นไม่ได้ของไปใช้นาน

เรื่องที่ 1 / 4: access token หมดอายุระหว่างใช้
AsyncStorage + ต่างคนต่าง refreshAsyncStorage.setItem("refresh", …)ผ่าน 0 จาก 0

ใช้เมื่อ ไม่ควรใช้ ใส่ไว้ให้เห็นว่าพังตรงไหน

ไม่ควรใช้เมื่อ ทุกแอป: token เป็นข้อความธรรมดา และ refresh พร้อมกันพาหลุด

แบบจำลอง: อายุ 15 นาทีกับ 30 วันเป็นตัวอย่าง ไม่ใช่ค่าที่ต้องใช้ ส่วน refresh ชนกันแล้วหลุด เกิดกับ server ที่หมุน refresh token และจับการใช้ซ้ำ ซึ่งเป็นแบบที่ควรทำ · กดช่องไหนก็ได้ ภาพใหญ่ด้านบนจะเปลี่ยนเป็นแบบนั้น พร้อมบอกว่าเหมาะกับงานแบบไหน

token สองตัว สองหน้าที่

Access tokenRefresh token
อายุหลักนาทีหลายวันถึงหลายสัปดาห์
ส่งไปที่ทุก API call (Authorization: Bearer)endpoint ขอ token อย่างเดียว
เก็บที่SecureStore (หรือ memory)SecureStore
ถ้าหลุดใช้ได้จนหมดอายุrotation จับการใช้ซ้ำได้

refresh ได้ทีละครั้ง

ถ้าหลาย call ได้ 401 พร้อมกัน ตัวแรกเริ่ม refresh ที่เหลือรอ promise เดียวกัน ส่ง refresh token ตัวเดิมไปสามรอบ สำหรับ server ที่หมุน token มันดูเหมือนโดนขโมยทุกประการ และ server ควรยกเลิกทั้งหมดจริง ๆ

token กับ cookie

browser เก็บ session ไว้ใน cookie ที่มันคุ้มกันเอง (HttpOnly, SameSite) แอป native ไม่มีแบบนั้น เลยส่ง token ไปใน header แล้วคุ้มกันเองใน Keychain หรือ Keystore

ในโค้ดจริง

auth-client.ts
// A token client for the app: Bearer on every call, a silent refresh on 401, and ONE refresh at a time.
// Plain TypeScript: where the tokens are kept (SecureStore) and how bytes travel (fetch) are passed in.
export interface Tokens { access: string; refresh: string }
export interface TokenStore {
  get(): Promise<Tokens | null>;
  set(tokens: Tokens): Promise<void>;
  clear(): Promise<void>;
}
export interface Reply { status: number; json(): Promise<unknown> }
export type Send = (path: string, init: { method?: string; headers?: Record<string, string>; body?: string }) => Promise<Reply>;

export function createAuthClient(send: Send, store: TokenStore, onSignedOut: () => void) {
  let refreshing: Promise<Tokens | null> | null = null;

  // Every 401 that arrives while a refresh is running waits for that same refresh.
  function refresh(): Promise<Tokens | null> {
    refreshing ??= (async () => {
      const old = await store.get();
      if (!old) return null;
      const res = await send("/token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refresh_token: old.refresh }) });
      if (res.status !== 200) {
        await store.clear();
        onSignedOut();
        return null;
      }
      const next = (await res.json()) as Tokens;
      await store.set(next); // the server rotated it: the old refresh token is dead now
      return next;
    })().finally(() => {
      refreshing = null;
    });
    return refreshing;
  }

  async function api(path: string): Promise<Reply> {
    const tokens = await store.get();
    if (!tokens) throw new Error("signed out");
    const call = (access: string) => send(path, { headers: { authorization: `Bearer ${access}` } });
    const res = await call(tokens.access);
    if (res.status !== 401) return res;
    const fresh = await refresh();
    if (!fresh) throw new Error("signed out");
    return call(fresh.access);
  }

  async function signOut(): Promise<void> {
    const tokens = await store.get();
    // Revoke on the server first, so a copy that leaked earlier dies too; then forget them here.
    if (tokens) await send("/logout", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ refresh_token: tokens.refresh }) });
    await store.clear();
    onSignedOut();
  }

  return { api, refresh, signOut };
}
รัน: tsc พร้อมโค้ดแอป แล้ว Jest test ของมันเรียกใช้จริง (รันใน Node ไม่ใช่บนมือถือ)

แนบ Bearer ทุก call, refresh เงียบ ๆ ตอนได้ 401 และใช้ refresh เดียวร่วมกันระหว่างที่มันทำงาน เป็น TypeScript ล้วน SecureStore กับ fetch ส่งเข้ามาจากข้างนอก

คำถามที่เจอบ่อย

เก็บ token บนมือถือที่ไหน

ใน SecureStore (expo-secure-store) หรือ react-native-keychain ซึ่งใช้ Keychain บน iOS และ Keystore บน Android ห้ามเก็บใน AsyncStorage เพราะเป็นข้อความธรรมดาในไฟล์ของแอป

ทำไมต้องมีสอง token ใช้ตัวเดียวอายุยาว ๆ ไม่ได้เหรอ

access token ไปกับทุก request เลยหลุดได้หลายทาง อายุสั้นทำให้ตัวที่หลุดใช้ได้แค่ไม่กี่นาที refresh token ไปที่เดียวและหมุนทุกครั้งที่ใช้ token เดียวอายุเดือนหนึ่ง หลุดแล้วคนร้ายใช้ได้ทั้งเดือน

ทำไมผู้ใช้หลุดออกจากระบบเองบางที

สาเหตุที่เจอบ่อยคือหลาย request ได้ 401 พร้อมกันแล้วต่างคนต่าง refresh ด้วย token ตัวเดียวกัน server ที่หมุน refresh token เห็นตัวที่ใช้ไปแล้วกลับมา เลยยกเลิกทั้งชุด แก้ด้วยการให้ refresh ได้ทีละครั้ง

refresh token rotation ช่วยอะไร

refresh token แต่ละตัวใช้ได้ครั้งเดียว ถ้ามีคนขโมยไปใช้ ฝั่งใดฝั่งหนึ่งจะส่งตัวที่ใช้แล้วมา server รู้ทันทีและยกเลิกทั้งชุด token ของคนร้ายตายไปด้วย แลกกับที่ผู้ใช้ต้อง login ใหม่

logout แค่ลบ token ในเครื่องพอไหม

ไม่พอ ถ้ามีสำเนาหลุดไปก่อนหน้า มันยังใช้ได้ บอก server ให้ยกเลิก refresh token ด้วย แล้วค่อยลบในเครื่อง access token เดิมยังใช้ได้จนหมดอายุ ถ้า server ไม่ได้เช็กรายการที่ยกเลิก

ทำไมแอปมือถือใช้ token ไม่ใช้ cookie

แอป native ไม่มี cookie jar กับกฎแบบ browser (SameSite, HttpOnly) token ใน header ใช้ง่ายกว่า แต่หน้าที่เก็บให้ปลอดภัยก็ตกเป็นของแอปเอง ฝั่งเว็บอ่านต่อได้ในบท Cookie กับ session

บทต่อไป

Cookie กับ sessionระดับ: กลาง

บนมือถือแอปเฝ้า token เอง ต่อไปคือฝั่งเว็บ login ที่เก็บใน cookie และ flag ที่กันไม่ให้ใครขโมยไป