Thuta Learning
API Tutorial
IntermediateWeb Developmentအလယ်အလတ်

OAuth 2.0 အကျဉ်းချုပ်

API Tutorialသင်ခန်းစာ 945 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Authorization code flow ရဲ့ redirect နှစ်ခုနဲ့ request တစ်ခုချင်းစီကို အစဉ်လိုက် ရှင်းပြနိုင်ဖို့
  • client_id, redirect_uri, scope, state, code_challenge နဲ့ code_verifier တို့ရဲ့ အလုပ်ကို ပြောပြနိုင်ဖို့
  • PKCE ကြောင့် ခိုးယူထားတဲ့ code က ဘာကြောင့် အသုံးမဝင်တော့လဲ၊ browser ဒါမှမဟုတ် mobile app မှာ client secret ဘာကြောင့် မထားရလဲ ရှင်းပြနိုင်ဖို့
  • User မပါတဲ့ service-to-service အတွက် client credentials flow ကို သုံးပြီး token ကို cache လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

OAuth 2.0 ကို ရိုးရိုးလေး ပြောရရင်

OAuth 2.0 ဆိုတာ app တစ်ခုက တခြား service မှာ ရှိတဲ့ သင့် data ကို သင့် password မသိဘဲ အကန့်အသတ်နဲ့ သုံးခွင့်ရဖို့ နည်းလမ်းပါ။ ဟိုတယ်ရဲ့ key card နဲ့ ဥပမာပေးရင် ရပါတယ်။ သင်က front desk (provider) မှာ ကိုယ်တိုင် သက်သေပြပါတယ်၊ ပြီးတော့ desk က app ကို တံခါးအချို့ပဲ ဖွင့်လို့ရတဲ့ သက်တမ်းရှိတဲ့ key card တစ်ခု ပေးလိုက်ပါတယ်။ App က သင့်ရဲ့ ကိုယ်ပိုင် credential (password) ကို တစ်ခါမှ မမြင်ရပါဘူး။

အဓိက အချက်က login လုပ်တာနဲ့ ခွင့်ပြုတာကို provider ရဲ့ ကိုယ်ပိုင် စာမျက်နှာမှာပဲ လုပ်တာပါ။ App က user ကို အဲဒီ စာမျက်နှာကို ပို့ပေးပြီး ပြန်လာတဲ့အခါ code တစ်ခု ရပါတယ်၊ အဲဒီ code ကို token နဲ့ လဲလှယ်ပြီး API ကို ခေါ်ပါတယ်။ ပြောရရင် OAuth က 'ဘယ်သူလဲ' ဆိုတာထက် 'ဘာလုပ်ခွင့်ရှိလဲ' ကို ဖြေတာပါ။

Problem → Why → Solution

ပြဿနာ: app က အခြား service ရဲ့ password ကို တောင်းတာ

'ကျွန်တော့်ပုံတွေကို print ထုတ်ပေးမယ့်' app တစ်ခုက သင့်ကို photo service ရဲ့ email နဲ့ password တောင်းတယ် ဆိုပါစို့။ App က အဲဒီ password နဲ့ photo API ကို ခေါ်လို့ ရပေမဲ့ အခုတော့ သင့် account တစ်ခုလုံးကို လက်ဝယ်ထားပါပြီ။ ပုံတွေ ဖတ်ခွင့်ပဲ ပေးချင်ရင်တောင် ကန့်သတ်လို့ မရသလို၊ app ကို ပြန်ပိတ်ချင်ရင် password ကိုပဲ ပြောင်းရပါတယ်။ App ရဲ့ database ပေါက်ကြားရင် password ကော တခြား service တွေမှာ ထပ်သုံးထားတာကပါ ပေါက်ကြားပါတယ်။

password-anti-pattern.js
// BROKEN design: the app asks the user for their password to ANOTHER service
const { email, password } = await promptUser("Enter your PhotoShare login");

const res = await fetch("https://api.example.com/photos", {
  headers: { Authorization: "Basic " + btoa(`${email}:${password}`) },
});
// The app now holds a credential that can do everything, forever.

Password အစား scope ပါတဲ့ token

Password က လုပ်ခွင့်အားလုံးကို ပေးပြီး သက်တမ်းမကုန်ပါဘူး၊ ကန့်သတ်လို့လည်း မရပါဘူး။ OAuth က app ကို token လို့ခေါ်တဲ့ အစားထိုး credential ကို ပေးပါတယ်။ အဲဒီ token က 'ပုံဖတ်ခွင့်ပဲ' လို scope နဲ့ ကန့်သတ်ထားပြီး အချိန်တိုလေးပဲ အသက်ရှိကာ user ကသော်လည်းကောင်း provider ကသော်လည်းကောင်း ရုပ်သိမ်းနိုင်ပါတယ်။ ထုတ်ပေးတာကလည်း user ကို တကယ်သိတဲ့ service ကိုယ်တိုင်ပါ။

Core concept: authorization code flow နဲ့ PKCE

OAuth မှာ အခန်းကဏ္ဍ လေးခု ရှိပါတယ်: resource owner (user)၊ client (သူ့ data ကို လိုချင်တဲ့ app)၊ authorization server (login နဲ့ consent လုပ်ပြီး token ထုတ်တဲ့ provider ဘက်) နဲ့ resource server (token လက်ခံတဲ့ API)။ အသုံးအများဆုံး နည်းက authorization code flow ပါ၊ code ကို browser redirect ကနေ ယူပြီး token ကိုတော့ app နဲ့ provider ကြား တိုက်ရိုက် request နဲ့ ယူတာပါ။

text
Authorization code flow with PKCE
---------------------------------
  App (with browser)        Authorization server            Resource API
       |                            |                             |
  1    |-- GET /authorize --------->|                             |
       |   client_id, redirect_uri, scope, state, code_challenge  |
  2    |<-- login + consent ------->|  (the password is typed     |
       |                            |   here, never in the app)   |
  3    |<-- 302 redirect_uri?code=...&state=...                   |
  4    |-- POST /token ------------>|                             |
       |   code + code_verifier     |                             |
  5    |<-- access_token -----------|                             |
  6    |-- GET /api/me, Authorization: Bearer <token> ----------->|

Redirect ကို ဒီလို ဖတ်ပါ။ ပထမ redirect (အဆင့် 1) မှာ app က user ရဲ့ browser ကို provider ရဲ့ /authorize URL ဆီ ပို့ပါတယ်။ User က အဲဒီမှာ login ဝင်ပြီး 'ခွင့်ပြုမယ်' နှိပ်ပါတယ်။ ဒုတိယ redirect (အဆင့် 3) မှာ provider က browser ကို app ရဲ့ redirect_uri ဆီ code နဲ့ state ပါပြီး ပြန်ပို့ပါတယ်။ ပြီးမှ app က code ကို provider ရဲ့ /token ဆီ ကိုယ်တိုင် ပို့ပြီး access token ရပါတယ်။ Code က browser နဲ့ ကြားထဲက ဘာမဆို မြင်နိုင်တဲ့ နေရာကို ဖြတ်သွားတာမို့ တစ်ကြိမ်သုံး၊ အသက်တိုတဲ့ အရာပဲ ဖြစ်ရပါမယ်။

Parameterဘာအတွက်လဲ
client_idProvider မှာ register လုပ်ထားတဲ့ app ရဲ့ အများသိ identifier
redirect_uriCode ကို ပြန်ပို့မယ့် URL၊ register လုပ်ထားတာနဲ့ အတိအကျ ကိုက်ရမယ်
scopeApp တောင်းတဲ့ လုပ်ခွင့်များ၊ ဥပမာ read:profile
stateApp ကိုယ်တိုင် ထုတ်တဲ့ random တန်ဖိုး၊ ပြန်ရောက်လာတာ ကိုယ့် login ရဲ့ အဖြေဟုတ်မဟုတ် စစ်ပြီး CSRF ကို ကာကွယ်
code_challengecode_verifier ရဲ့ SHA-256 hash (method S256)၊ အဆင့် 1 မှာ ပို့
codeRedirect နဲ့ ပြန်လာတဲ့ တစ်ကြိမ်သုံး authorization code
code_verifierကနဦး random secret၊ အဆင့် 4 မှာပဲ ဖော်ပြပြီး provider က hash ပြန်တွက်စစ်

Client secret ကိုတော့ server ပေါ်မှာ run တဲ့ app (confidential client) က token endpoint မှာ ကိုယ့်ကိုယ်ကို သက်သေပြဖို့ သုံးပါတယ်။ Browser JavaScript ဒါမှမဟုတ် mobile app (public client) ထဲမှာတော့ secret ထားလို့ မရပါဘူး၊ ဘယ်သူမဆို ထုတ်ယူနိုင်လို့ပါ။ အဲဒီအစား PKCE ကို သုံးပါတယ်: app က verifier တစ်ခု ထုတ်ပြီး hash ကိုပဲ အရင်ပို့တာမို့ code ကို ခိုးယူသူက verifier မရှိဘဲ token မလဲနိုင်ပါဘူး။

ဟိုတယ် front desk နဲ့ key card
  1. App က user ကို provider ဆီ ပို့
  2. User က အဲဒီမှာ login ဝင်ပြီး ခွင့်ပြု
  3. Provider က code နဲ့ redirect ပြန်
  4. App က code + verifier ကို token နဲ့ လဲ
  5. App က Bearer <token> နဲ့ API ခေါ်

Password က provider ဆီမှာပဲ ရှိပြီး app ကတော့ scope ကန့်သတ်ထားတဲ့ သက်တမ်းတိုတဲ့ token ကိုပဲ ကိုင်ရပါတယ်။

အထွေထွေ ပုံစံ

text
1. GET  <authorize-url>?response_type=code&client_id=...&redirect_uri=...
        &scope=...&state=...&code_challenge=...&code_challenge_method=S256
2. 302  <redirect_uri>?code=...&state=...
3. POST <token-url>
        grant_type=authorization_code&code=...&redirect_uri=...
        &client_id=...&code_verifier=...
4. 200  { "access_token": "...", "token_type": "Bearer", "expires_in": 900 }

URL နှစ်ခုကို provider ကပေးပါတယ်: authorize နဲ့ token။ Parameter အားလုံးက query string (အဆင့် 1, 2) ဒါမှမဟုတ် form body (အဆင့် 3) ထဲမှာ ပါပါတယ်။

Worked example: mock provider နဲ့ flow တစ်ခုလုံး run ကြည့်ခြင်း

အောက်က script က provider တစ်ခုကို process တစ်ခုတည်းထဲမှာ ပုံစံတူ ဖန်တီးထားပါတယ်: /authorize၊ /token နဲ့ /api/me ပါပါတယ်။ Client ဘက်က diagram ရဲ့ အဆင့်တွေအတိုင်း လုပ်ပါတယ်: verifier နဲ့ state ထုတ်၊ /authorize ကို ခေါ်၊ redirect ကို ဖတ်ပြီး state စစ်၊ code ကို token နဲ့ လဲ၊ ပြီးမှ API ကို ခေါ်ပါတယ်။ ကြားထဲမှာ မှားတဲ့ redirect_uri၊ မှားတဲ့ verifier နဲ့ code ပြန်သုံးတာတွေကိုလည်း စမ်းပြီး provider က ဘယ်လို ပယ်ချလဲ ပြပါတယ်။

Browser က redirect ကို အလိုလို လိုက်သွားတာမို့ script မှာ redirect: 'manual' သုံးပြီး 302 မှာ ရပ်ကာ Location header ကို ဖတ်ပါတယ်။ Code တွေက counter နဲ့ ထုတ်ထားလို့ output က တူပါတယ် (လက်တွေ့မှာ random ဖြစ်ရမယ်)၊ verifier နဲ့ state ကတော့ random ဖြစ်ပြီး print မထုတ်ပါဘူး။ https://app.example.com/callback ကို တကယ် မခေါ်ပါဘူး။

oauth-pkce-flow.mjs
import http from "node:http";
import crypto from "node:crypto";

const s256 = (text) => crypto.createHash("sha256").update(text).digest("base64url");
const REDIRECT_URI = "https://app.example.com/callback"; // registered with the provider

// A mock provider: authorization endpoint, token endpoint and API in one process.
const pendingCodes = new Map(); // code -> what the provider remembers about the request
let codeCounter = 0;

const provider = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://provider.local");
  const json = (status, body) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(body));
  };

  if (url.pathname === "/authorize") {
    const q = url.searchParams;
    // Never redirect to an unregistered redirect_uri: the code would go to a stranger.
    if (q.get("client_id") !== "demo-app" || q.get("redirect_uri") !== REDIRECT_URI) {
      return json(400, { error: "invalid_request" });
    }
    // A real provider shows its login and consent screen here; we pretend "Allow".
    const code = `code_${++codeCounter}`;
    pendingCodes.set(code, { challenge: q.get("code_challenge"), scope: q.get("scope") });
    const back = new URL(REDIRECT_URI);
    back.searchParams.set("code", code);
    back.searchParams.set("state", q.get("state"));
    res.writeHead(302, { Location: back.href });
    return res.end();
  }

  if (url.pathname === "/token" && req.method === "POST") {
    let raw = "";
    for await (const chunk of req) raw += chunk;
    const form = new URLSearchParams(raw);
    const pending = pendingCodes.get(form.get("code"));
    if (!pending || s256(form.get("code_verifier") ?? "") !== pending.challenge) {
      return json(400, { error: "invalid_grant" });
    }
    pendingCodes.delete(form.get("code")); // a code works exactly once
    const grant = { access_token: "at_demo_1", token_type: "Bearer", expires_in: 900 };
    return json(200, { ...grant, scope: pending.scope });
  }

  if (url.pathname === "/api/me" && req.headers.authorization === "Bearer at_demo_1") {
    return json(200, { name: "Alice" });
  }
  json(401, { error: "invalid_token" });
});

await new Promise((resolve) => provider.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${provider.address().port}`;

// Step 1: the client invents a one-time secret (the verifier) and sends only its hash.
const codeVerifier = crypto.randomBytes(32).toString("base64url");
const state = crypto.randomBytes(16).toString("base64url");
const authorizeParams = {
  response_type: "code",
  client_id: "demo-app",
  redirect_uri: REDIRECT_URI,
  scope: "read:profile",
  state,
  code_challenge: s256(codeVerifier),
  code_challenge_method: "S256",
};
const authorizeUrl = (overrides = {}) =>
  `${base}/authorize?${new URLSearchParams({ ...authorizeParams, ...overrides })}`;

const bad = await fetch(authorizeUrl({ redirect_uri: "https://evil.example/cb" }));
console.log("bad redirect_uri :", bad.status, (await bad.json()).error);

// Step 2: a browser would follow this URL; we stop at the 302 to read its Location.
const hop = await fetch(authorizeUrl(), { redirect: "manual" });
const callback = new URL(hop.headers.get("location"));
console.log("redirected to    :", callback.origin + callback.pathname);
console.log("state matches    :", callback.searchParams.get("state") === state);
const code = callback.searchParams.get("code");

// Step 3: swap the code (plus the original verifier) for an access token.
async function exchange(verifier) {
  const res = await fetch(`${base}/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      redirect_uri: REDIRECT_URI,
      client_id: "demo-app",
      code_verifier: verifier,
    }),
  });
  return { status: res.status, body: await res.json() };
}

const thief = await exchange("a-guess-by-someone-who-stole-the-code");
console.log("wrong verifier   :", thief.status, thief.body.error);
const granted = await exchange(codeVerifier);
const { token_type, expires_in, scope } = granted.body;
console.log("token response   :", granted.status, token_type, expires_in, scope);
const replay = await exchange(codeVerifier);
console.log("code replay      :", replay.status, replay.body.error);

const auth = { Authorization: `Bearer ${granted.body.access_token}` };
const me = await fetch(`${base}/api/me`, { headers: auth });
console.log("API with token   :", me.status, await me.text());
provider.close();

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Registered redirect_uriif (q.get("client_id") !== "demo-app" || q.get("redirect_uri") !== REDIRECT_URI) {

    Provider က redirect_uri ကို register လုပ်ထားတာနဲ့ အတိအကျ နှိုင်းယှဉ်ပါတယ်။ မကိုက်ရင် 400 ပြန်ပြီး code ကို မပို့ပါဘူး၊ မဟုတ်ရင် attacker ရဲ့ URL ဆီ code ရောက်သွားမှာပါ။

  2. PKCE paircode_challenge: s256(codeVerifier),

    Client က random verifier ကို ကိုယ့်ဆီမှာပဲ ထားပြီး hash (challenge) ကိုပဲ အဆင့် 1 မှာ ပို့ပါတယ်။ Hash ကနေ verifier ကို ပြန်ရှာလို့ မရတာမို့ redirect ကို မြင်သူတွေ verifier မရပါဘူး။

  3. Stop at the redirectconst hop = await fetch(authorizeUrl(), { redirect: "manual" });

    redirect: 'manual' ကြောင့် fetch က 302 ကို မလိုက်ဘဲ Location header ကို ပြန်ပေးပါတယ်။ Browser ပါရင် user က provider ရဲ့ login စာမျက်နှာကို မြင်ရမယ့်နေရာ ဒီမှာပါပဲ။

  4. Check stateconsole.log("state matches :", callback.searchParams.get("state") === state);

    ပြန်ရောက်လာတဲ့ state က ကိုယ်ပို့ခဲ့တဲ့ state နဲ့ တူရမယ်။ မတူရင် ဒီ response က ကိုယ်စတင်ခဲ့တဲ့ login ရဲ့ အဖြေ မဟုတ်လို့ code ကို လက်မခံရပါဘူး။

  5. Provider verifies PKCEif (!pending || s256(form.get("code_verifier") ?? "") !== pending.challenge) {

    Token endpoint က ရောက်လာတဲ့ verifier ကို hash လုပ်ပြီး အဆင့် 1 က သိမ်းထားတဲ့ challenge နဲ့ နှိုင်းယှဉ်ပါတယ်။ ခိုးယူသူက code ရပေမဲ့ verifier မသိတာမို့ invalid_grant ရပါတယ်။

  6. Single-use codependingCodes.delete(form.get("code")); // a code works exactly once

    Exchange အောင်မြင်ရင် code ကို ချက်ချင်း ဖျက်ပါတယ်။ အဲဒါကြောင့် ဒုတိယအကြိမ် ပြန်သုံးတာ invalid_grant နဲ့ ကျရှုံးတာကို output ထဲမှာ တွေ့ရပါမယ်။

You should see
bad redirect_uri : 400 invalid_request
redirected to    : https://app.example.com/callback
state matches    : true
wrong verifier   : 400 invalid_grant
token response   : 200 Bearer 900 read:profile
code replay      : 400 invalid_grant
API with token   : 200 {"name":"Alice"}

Wire ပေါ်မှာ ဘာတွေ ပို့လဲ

Browser ကို ပို့တဲ့ authorize URL က တစ်ကြောင်းတည်းပါ၊ ဒီမှာ ဖတ်ရလွယ်အောင် ခွဲပြထားတာပါ။ Parameter တန်ဖိုးတွေကို percent-encode လုပ်ရပါတယ် (redirect_uri ထဲက : နဲ့ / က %3A နဲ့ %2F ဖြစ်တာ တွေ့ပါလိမ့်မယ်)။ Challenge တန်ဖိုးက RFC 7636 ပါ နမူနာ တန်ဖိုးပါ။

text
https://auth.example.com/authorize
  ?response_type=code
  &client_id=demo-app
  &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
  &scope=read%3Aprofile
  &state=af0ifjsldkj
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256

User ခွင့်ပြုပြီးရင် provider က ဒီလို redirect ပြန်ပို့ပါတယ်။ ပြီးတော့ app ရဲ့ backend (ဒါမှမဟုတ် SPA) က token request ကို ကိုယ်တိုင် ပို့ပါတယ်။ ဒီ request က browser ရဲ့ address bar မှာ မပေါ်ပါဘူး၊ ဒါကြောင့် token ကို URL ထဲ မထည့်ဘဲ response body ထဲ ပြန်ပေးတာပါ။

text
HTTP/1.1 302 Found
Location: https://app.example.com/callback?code=7xK2qLw9&state=af0ifjsldkj
text
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=7xK2qLw9&client_id=demo-app
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

နောက်ဆုံး request body က တစ်ကြောင်းတည်းပါ၊ ဒီမှာတော့ ဖတ်ရလွယ်အောင် ဖြတ်ပြထားပါတယ်။ Provider က 200 နဲ့ access_token, token_type: Bearer, expires_in ပါတဲ့ JSON ပြန်ပေးပါတယ်။

PKCE: code ကို ကာကွယ်ပုံ

PKCE မရှိရင် redirect ကို ကြားဖြတ်မိတဲ့ ဘယ်သူမဆို — phone ပေါ်မှာ တူညီတဲ့ custom URL scheme ကို register လုပ်ထားတဲ့ malicious app၊ browser extension၊ log — က code ကို token နဲ့ လဲလို့ရပါတယ်။ PKCE က code ကို flow စတင်ခဲ့တဲ့ app instance နဲ့ ချိတ်ပေးပါတယ်: challenge ကို အဆင့် 1 မှာ ပို့ပြီး verifier ကိုတော့ အဆင့် 4 မှာပဲ ဖော်ပြတာပါ။

pkce-challenge.mjs
import crypto from "node:crypto";

// The example pair published in RFC 7636 (PKCE), Appendix B.
const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
console.log(challenge);
console.log(challenge === "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");

// A fresh verifier is 32 random bytes written as 43 base64url characters.
console.log(crypto.randomBytes(32).toString("base64url").length);

ပထမ line က RFC 7636 ရဲ့ နမူနာ verifier ကို SHA-256 hash လုပ်ပြီး base64url ပြောင်းတဲ့ challenge ပါ၊ ဒုတိယ line က RFC ပါ တန်ဖိုးနဲ့ တူကြောင်း စစ်တာပါ။ နောက်ဆုံး line က verifier အသစ်တစ်ခုက byte 32 လုံး random ကို character 43 လုံးအဖြစ် ရေးထားတာကို ပြပါတယ်။

Client credentials flow: user မပါတဲ့ အခါ

ညဘက် job တစ်ခု ဒါမှမဟုတ် backend တစ်ခုက တခြား backend ကို ခေါ်တဲ့အခါ user မပါပါဘူး၊ ဒါကြောင့် redirect လည်း code လည်း မလိုပါဘူး။ Client က ကိုယ့်ကိုယ်ကို client_id နဲ့ client_secret ကို သုံးပြီး /token မှာ တိုက်ရိုက် သက်သေပြပါတယ်၊ ပုံမှန်အားဖြင့် HTTP Basic header နဲ့ပါ။ ရလာတဲ့ token က ဒီ service ကိုယ်တိုင်ရဲ့ scope ပါ၊ refresh token ကတော့ ပုံမှန်အားဖြင့် မပါပါဘူး၊ token ကုန်ရင် ထပ်တောင်းရုံပါပဲ။ ဒီ flow ကို server ပေါ်မှာပဲ သုံးရပါမယ်၊ secret ရှိလို့ပါ။

client-credentials.mjs
import http from "node:http";

// Client credentials: no user, no redirect. The server proves itself with id + secret.
const tokenEndpoint = http.createServer(async (req, res) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  const form = new URLSearchParams(raw);
  const basic = (req.headers.authorization ?? "").replace(/^Basic /, "");
  const [id, secret] = Buffer.from(basic, "base64").toString().split(":");

  const reply = (status, body, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(body));
  };
  if (form.get("grant_type") !== "client_credentials") {
    return reply(400, { error: "unsupported_grant_type" });
  }
  if (id !== "billing-service" || secret !== "demo-secret-not-real") {
    const challenge = { "WWW-Authenticate": 'Basic realm="oauth"' };
    return reply(401, { error: "invalid_client" }, challenge);
  }
  reply(200, { access_token: "at_service_1", token_type: "Bearer", expires_in: 3600 });
});

await new Promise((resolve) => tokenEndpoint.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${tokenEndpoint.address().port}/token`;

async function requestToken(id, secret) {
  const credentials = Buffer.from(`${id}:${secret}`).toString("base64");
  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Basic ${credentials}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({ grant_type: "client_credentials", scope: "invoices" }),
  });
  console.log(res.status, await res.text());
}

await requestToken("billing-service", "demo-secret-not-real");
await requestToken("billing-service", "wrong-secret");
tokenEndpoint.close();

ပထမ call က 200 နဲ့ token ပြန်ရပြီး ဒုတိယ call က secret မှားလို့ 401 နဲ့ invalid_client ပြန်ပါတယ်။ Client authentication ကျရင် provider က Basic challenge ပါတဲ့ 401 ပြန်ရမယ်လို့ OAuth spec က ပြောထားပါတယ်။

Scope, access token နဲ့ refresh token

Scope တွေက provider သတ်မှတ်တဲ့ စကားလုံးတွေပါ (read:profile လို့)၊ space နဲ့ ခြားပြီး တောင်းပါတယ်။ User က consent screen မှာ app တောင်းတာကို မြင်ရပြီး ခွင့်ပြုသလား မပြုဘူးလား ဆုံးဖြတ်ပါတယ်။ ကိုယ်လိုတာထက် မပိုတောင်းပါနဲ့၊ scope များလေ user က ငြင်းလေ၊ token ပေါက်ကြားရင် ထိခိုက်မှုကြီးလေပါပဲ။

Tokenသက်တမ်းဘယ်ကို ပို့လဲ
Access tokenမိနစ်ကနေ နာရီအနည်းငယ်Resource API (Authorization: Bearer)
Refresh tokenရက်ကနေ လအထိProvider ရဲ့ token endpoint ကိုပဲ

Access token သက်တမ်းကုန်ရင် app က refresh token ကို grant_type=refresh_token နဲ့ token endpoint ကို ပို့ပြီး access token အသစ် ယူပါတယ်၊ user ကို login ထပ်မခိုင်းရပါဘူး။ Refresh token က ပိုတန်ဖိုးရှိတာမို့ ပိုလုံခြုံတဲ့ နေရာမှာ သိမ်းပြီး API ကို ဘယ်တော့မှ မပို့ပါနဲ့။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ OAuth

'Google နဲ့ ဝင်မယ်' ဒါမှမဟုတ် 'GitHub နဲ့ ဝင်မယ်' ခလုတ်တွေက OAuth ပေါ်မှာ OpenID Connect ဆိုတဲ့ identity layer ကို တင်ထားတာပါ။ Calendar app တစ်ခုက သင့် Google Calendar ကို ဖတ်တာ၊ chat bot တစ်ခုက workspace ထဲ message ပို့တာ၊ CI service တစ်ခုက repository ကို ကြည့်တာတွေ အားလုံး OAuth နဲ့ ခွင့်ပြုခံရတာပါ။ Developer အနေနဲ့ provider ရဲ့ developer console မှာ app ကို register လုပ်ပြီး client_id ရယူကာ redirect URI တွေကို အတိအကျ ထည့်ရပါတယ်။

  • Provider တစ်ခုချင်းစီရဲ့ endpoint URL၊ အသုံးပြုလို့ရတဲ့ scope နဲ့ redirect စည်းမျဉ်းတွေက documentation ထဲမှာပါ၊ ဒီ lesson က ပုံသဏ္ဍာန်ကို သင်ပေးတာပါ။
  • Mobile app တွေက စနစ်ရဲ့ browser ကို ဖွင့်ပြီး PKCE နဲ့ flow ကို လုပ်ပါတယ်၊ app ထဲက embedded login form ကို မသုံးပါဘူး။
  • Server-to-server integration တွေ (billing, reporting job စတာ) က client credentials နဲ့ token ယူပြီး သက်တမ်းမကုန်မချင်း cache လုပ်ထားပါတယ်။
  • OAuth library ကို သုံးပါ။ လက်တွေ့မှာ token refresh, error handling နဲ့ provider ကွာခြားချက်တွေက ကိုယ်တိုင်ရေးရင် အမှားများလွန်းပါတယ်။

အမှားများ

OAuth နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

Browser ဒါမှမဟုတ် mobile app ထဲ client secret ထည့်ခြင်း

App package ထဲက secret ကို ဘယ်သူမဆို ထုတ်ယူနိုင်ပါတယ်၊ obfuscate လုပ်တာနဲ့ base64 encode လုပ်တာက လမ်းကို နည်းနည်းပဲ ရှည်စေပါတယ်။ Public client တွေက secret မပါဘဲ PKCE နဲ့ authorization code flow ကို သုံးပါ။

state ကို မစစ်ခြင်း

State မစစ်ရင် attacker က ကိုယ့် account ရဲ့ code ပါတဲ့ callback link တစ်ခု ပို့ပြီး victim ရဲ့ session ကို attacker ရဲ့ account နဲ့ ချိတ်နိုင်ပါတယ် (login CSRF)။ Flow စတင်တိုင်း random state ထုတ်ပြီး session ထဲမှာ သိမ်းကာ callback မှာ ယှဉ်စစ်ပါ။

OAuth ကို login လို့ ထင်ခြင်း

Access token က API ကို ခေါ်ခွင့်ပေးတာ၊ ဘယ် user လဲ ပြောတာ မဟုတ်ပါဘူး။ 'ဝင်ရောက်ခြင်း' လိုချင်ရင် OpenID Connect ရဲ့ id_token ကို သုံးပြီး signature, iss, aud နဲ့ nonce ကို စစ်ရပါမယ်။

ဟောင်းနွမ်းတဲ့ flow တွေ သုံးခြင်း

Implicit flow က token ကို URL fragment နဲ့ ပို့ပြီး password grant က app ကို user password ပြန်ပေးတာမို့ လက်ရှိ OAuth security guidance က မသုံးဖို့ အကြံပေးပါတယ်။ အသစ်စတင်တဲ့ project တိုင်းမှာ authorization code + PKCE ကို ရွေးပါ။

Best Practices

Best practices

  • Public client တိုင်းမှာ PKCE သုံးပါ၊ server-side app တွေမှာလည်း အပိုကာကွယ်ရေးအဖြစ် သုံးလို့ ရပါတယ်။
  • redirect_uri ကို အတိအကျ register လုပ်ပါ၊ wildcard မသုံးပါနဲ့။
  • Scope ကို လိုတာပဲ တောင်းပြီး access token ကို သက်တမ်းတို ထားပါ။
  • Token နဲ့ code တွေကို log ထဲမှာ မမှတ်ပါနဲ့၊ OAuth library ကို သုံးပါ။

Mini challenge

Mini challenge: client-credentials token cache

Service-to-service client တစ်ခုက API ကို ခေါ်တိုင်း token အသစ် မတောင်းသင့်ပါဘူး။ Mock token endpoint တစ်ခုရေးပါ (ခေါ်တိုင်း at_1, at_2 ... ထုတ်ပြီး expires_in 60 ပေးမယ်)၊ ပြီးရင် getToken() ကို ရေးပါ — token သက်တမ်း ၅ စက္ကန့်ထက်ပိုကျန်သေးရင် cache က ပြန်ပေးပြီး မဟုတ်ရင် client_credentials နဲ့ အသစ်တောင်းရမယ်။ ဖန်တီးထားတဲ့ နာရီနဲ့ စမ်းပါ။

  • Mock endpoint က issued count ကို မှတ်ပြီး at_<n> token ပြန်ရမယ်
  • getToken က form body ထဲ grant_type=client_credentials ပို့ရမယ်
  • Token က ကျန်သက်တမ်း ၅ စက္ကန့်ထက် ပိုရှိသရွေ့ cache ကိုပဲ သုံးရမယ်
  • နာရီကို 54 စက္ကန့်၊ ပြီးတော့ 1 စက္ကန့် ထပ်တိုးပြီး token နဲ့ issued count ကို print ထုတ်ပါ
token-cache.mjs
import http from "node:http";

// TODO: a mock token endpoint on port 0 that counts the tokens it has issued
//   and answers { access_token: "at_<n>", token_type: "Bearer", expires_in: 60 }

// TODO: a fake clock in seconds (let clock = 1000) so the output repeats

// TODO: getToken() -> the cached token while it stays valid for more than 5 more
//   seconds, otherwise POST grant_type=client_credentials and cache the new token

// TODO: call getToken() twice, advance the clock 54 s and call again, advance
//   1 s more and call again; print each token and the issued count

ရလဒ်: ပထမ call နှစ်ခုက at_1 at_1 (issued: 1)၊ 54 စက္ကန့်အကြာမှာ at_1 (issued: 1)၊ 55 စက္ကန့်မှာ at_2 (issued: 2) ဖြစ်ရမယ်။

အရိပ်အမြွက် ကြည့်ရန်

Cache ထဲမှာ token တန်ဖိုးနဲ့ expiresAt (ယခုနာရီ + expires_in) ကို သိမ်းပါ။ expiresAt - 5 > clock ဖြစ်ရင်သာ cache ကို ပြန်သုံးပါ။ ပထမ call ကျတဲ့အခါ cache က null ဖြစ်နေတာကို မမေ့ပါနဲ့။

အဖြေ ကြည့်ရန်
token-cache.mjs
import http from "node:http";

let issued = 0;
const tokenServer = http.createServer(async (req, res) => {
  for await (const chunk of req) void chunk; // drain the request body
  issued += 1;
  res.writeHead(200, { "Content-Type": "application/json" });
  const grant = { access_token: `at_${issued}`, token_type: "Bearer", expires_in: 60 };
  res.end(JSON.stringify(grant));
});
await new Promise((resolve) => tokenServer.listen(0, "127.0.0.1", resolve));
const tokenUrl = `http://127.0.0.1:${tokenServer.address().port}/token`;

let clock = 1000; // fake "now" in seconds, so the output repeats
let cached = null;

async function getToken() {
  if (cached && cached.expiresAt - 5 > clock) return cached.value; // 5 s safety margin
  const res = await fetch(tokenUrl, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({ grant_type: "client_credentials" }),
  });
  const data = await res.json();
  cached = { value: data.access_token, expiresAt: clock + data.expires_in };
  return cached.value;
}

const first = await getToken();
const second = await getToken();
console.log("first two calls :", first, second, `(issued: ${issued})`);

clock += 54;
console.log("54 s later      :", await getToken(), `(issued: ${issued})`);

clock += 1;
console.log("55 s later      :", await getToken(), `(issued: ${issued})`);
tokenServer.close();

Quick Quiz 1 / 3

Authorization code က browser redirect ထဲမှာ ပါပေမဲ့ access token က ဘာကြောင့် မပါတာလဲ?

Quick Quiz 2 / 3

Authorization request ထဲက state parameter ရဲ့ အလုပ်က ဘာလဲ?

Quick Quiz 3 / 3

Mobile app က token endpoint ကို ခေါ်ဖို့ client secret လိုတယ် လို့ ဆိုပါစို့။ ဘာလုပ်သင့်လဲ?

မှတ်ထားရမယ့် အချက်များ

  • OAuth 2.0 က password အစား scope ကန့်သတ်ထားတဲ့ သက်တမ်းတိုတဲ့ token ကို app ကို ပေးပြီး login ကို provider ရဲ့ စာမျက်နှာမှာပဲ လုပ်စေပါတယ်။
  • Authorization code flow: /authorize redirect၊ code နဲ့ state ပါတဲ့ redirect ပြန်၊ /token မှာ code + code_verifier လဲ၊ Bearer token နဲ့ API ခေါ်။
  • PKCE နဲ့ state က code ခိုးခံရတာ နဲ့ CSRF ကို ကာကွယ်ပြီး browser/mobile app မှာ client secret ဘယ်တော့မှ မထားရပါဘူး။
  • Client credentials flow က user မပါတဲ့ server-to-server အတွက်ဖြစ်ပြီး token ကို သက်တမ်းမကုန်မချင်း cache လုပ်ပါ။

RFC 6749 — OAuth 2.0 Authorization Framework — IETF

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

OAuth 2.0 အကျဉ်းချုပ် | Thuta Learning