ရိုးရိုးလေး ရှင်းပြမယ်
Bearer token ကို ရိုးရိုးလေး ပြောရရင်
Bearer ဆိုတာ 'ကိုင်ထားသူ' လို့ အဓိပ္ပာယ်ရပါတယ်။ Bearer token ဆိုတာ ကိုင်ထားတဲ့သူ ဘယ်သူပဲ ဖြစ်ဖြစ် ဝင်ခွင့်ရတဲ့ ဝင်ခွင့်လက်မှတ်တစ်ခုပါ။ ဇာတ်ရုံမှာ လက်မှတ်ကို ကိုင်ထားတဲ့သူကို ဝင်ခွင့်ပေးသလိုပါပဲ၊ ဘယ်သူ့နာမည်နဲ့ ဝယ်လဲ မမေးပါဘူး။ Login အောင်မြင်တဲ့အခါ server က token တစ်ခု ထုတ်ပေးပြီး client က နောက် request တိုင်းမှာ Authorization header ထဲ ထည့်ပို့ပါတယ်။
JWT (JSON Web Token) ဆိုတာ အဲဒီ token ကို ဖော်မတ်လုပ်တဲ့ အသုံးများဆုံး နည်းတစ်ခုပါ။ ဝင်ခွင့်လက်မှတ်ပေါ်မှာ 'ဒါ u_1 ပါ၊ ၁၅ မိနစ်အတွင်း သက်တမ်းကုန်မယ်' လို့ ရေးထားပြီး server ရဲ့ တံဆိပ်တုံးနဲ့ ခတ်ထားတာမျိုးပါ။ Server က တံဆိပ်ကို ပြန်စစ်လို့ ရတာမို့ request တိုင်းအတွက် database ကို မမေးဘဲ ခေါ်သူ ဘယ်သူလဲ သိနိုင်ပါတယ်။ ဒါပေမဲ့ တံဆိပ်ခတ်ထားတာ ဖြစ်ပြီး စာကို ဖုံးထားတာ မဟုတ်ပါဘူး၊ ဘယ်သူမဆို ဖတ်လို့ရပါတယ်။
Problem → Why → Solution
ပြဿနာ: payload ကို ဖတ်ပြီး ယုံမိတာ
Request တစ်ခုမှာ Authorization: Bearer eyJ... ပါလာတယ်။ Token ရဲ့ အလယ်အပိုင်းကို decode လုပ်ရင် roles: ['user'] ပေါ်လာလို့ အဲဒီအတိုင်း လက်ခံလိုက်ပါတယ်။ အသုံးပြုသူတစ်ယောက်က online JWT decoder နဲ့ payload ကို ဖွင့်ကြည့်ပြီး roles ကို ['admin'] ပြောင်းကာ ပြန် encode လုပ်ပြီး ပို့လိုက်ပါတယ်။ Signature ကို ဘယ်သူမှ မစစ်တာမို့ ကိုယ့် server က admin အခွင့်အာဏာကို ပေးလိုက်ပါတယ်။
// BROKEN: reads the claims but never verifies the signature
function currentUser(authorizationHeader) {
const token = authorizationHeader.replace("Bearer ", "");
const payload = token.split(".")[1];
return JSON.parse(Buffer.from(payload, "base64url").toString());
}
const user = currentUser(req.headers.authorization);
if (user.roles.includes("admin")) {
showAdminPanel(); // anyone can edit the payload and send "roles": ["admin"]
}Signed ဆိုတာ encrypted မဟုတ်ဘူး
JWT ကို sign လုပ်ထားတာက server ကို ပြင်ထားမှုကို ရှာတွေ့စေဖို့ပါ၊ ဖတ်ခွင့်ကို ကာကွယ်ဖို့ မဟုတ်ပါဘူး။ ဒါပေမဲ့ server က secret (ဒါမှမဟုတ် issuer ရဲ့ public key) နဲ့ signature ကို ပြန်တွက်စစ်မှသာ အဲဒီ ကာကွယ်မှု အလုပ်ဖြစ်ပါတယ်။ ဖတ်လို့ရတာ မှန်သမျှ ပြင်လို့လည်း ရပါတယ်၊ ပြင်ထားတာကို လက်မခံအောင် တားတဲ့အရာက signature ပဲ ရှိပါတယ်။
Core concept: bearer token ကို sign လုပ်၊ စစ်၊ သက်တမ်းကုန်စေ
Bearer token ကို Authorization: Bearer <token> ပုံစံနဲ့ ပို့ပါတယ် (RFC 6750)။ ဒီ scheme မှာ ခေါ်သူက token ကိုင်ထားကြောင်းကလွဲပြီး ဘာမှ ထပ်သက်သေပြစရာ မလိုတာမို့ ခိုးယူသူလည်း အတူတူ သုံးနိုင်ပါတယ်။ ဒါကြောင့် HTTPS မဖြစ်မနေ သုံးရပြီး token သက်တမ်းကို တိုထားရပါတယ်။ API key လို application တစ်ခုကို ဖော်ပြတာထက် token တွေက login ဝင်ထားတဲ့ user တစ်ယောက်ရဲ့ session ကို ကိုယ်စားပြုလေ့ရှိပါတယ်။
JWT မှာ dot နဲ့ ခြားထားတဲ့ အပိုင်းသုံးပိုင်း ရှိပါတယ်: header၊ payload နဲ့ signature။ Header ထဲမှာ algorithm (alg) နဲ့ token အမျိုးအစား (typ) ပါပါတယ်။ Payload ထဲမှာ claim တွေ ပါပါတယ်: sub (ဘယ်သူ)၊ iat (ထုတ်တဲ့အချိန်)၊ exp (သက်တမ်းကုန်တဲ့အချိန်) စတာတွေပါ။ HS256 မှာ signature က HMAC-SHA256(header + '.' + payload, secret) ပါ။ အပိုင်းတိုင်းကို base64url နဲ့ encode လုပ်ထားပါတယ်၊ ဒါက URL မှာ လုံခြုံတဲ့ base64 မျိုး (+ နဲ့ / အစား - နဲ့ _) ဖြစ်ပြီး encryption မဟုတ်ဘဲ ဖော်မတ်လုပ်တာသက်သက်ပါ။
Server ဘက်မှာ အစီအစဉ်တကျ စစ်ပါ: အပိုင်းသုံးပိုင်း ရှိလား၊ header ထဲက alg က ကိုယ်မျှော်လင့်တဲ့ algorithm လား (token က ပြောတာကို ဘယ်တော့မှ မယုံပါနဲ့)၊ signature ကို ပြန်တွက်ပြီး constant-time နဲ့ နှိုင်းယှဉ်၊ ပြီးမှ exp (လိုရင် iss နဲ့ aud) ကို စစ်ပါ။ အားလုံးအောင်မှ claim တွေကို ယုံရပါတယ်။ HS256 က secret တစ်ခုတည်းနဲ့ sign လည်းလုပ်၊ verify လည်းလုပ်ပေမဲ့ RS256 ကတော့ private key နဲ့ sign ပြီး public key နဲ့ verify လုပ်တာမို့ service အများကြီးက token ထုတ်ခွင့်မရှိဘဲ စစ်ခွင့်ရနိုင်ပါတယ်။
Failure ဆိုရင် 401 ပြန်ပြီး RFC 6750 ပုံစံ WWW-Authenticate: Bearer error="invalid_token" ထည့်ပါ။ Token လုံးဝ မပါရင်တော့ error မပါတဲ့ Bearer realm="api" ပဲ ပြန်ပါတယ်။ JWT ကို stateless ဖြစ်လို့ exp မရောက်ခင် ပြန်ရုပ်သိမ်းဖို့ ခက်ပါတယ်၊ ဒါကြောင့် access token ကို မိနစ်ဆယ်ချီပဲ အသက်ရှိစေပြီး refresh token နဲ့ အသစ်ယူခိုင်းတာက စံနည်းပါ။
| Claim | အဓိပ္ပာယ် |
|---|---|
| sub | Token ကို ဘယ် user (ဒါမှမဟုတ် client) အတွက် ထုတ်ထားလဲ |
| iat / exp | ထုတ်တဲ့အချိန်နဲ့ သက်တမ်းကုန်တဲ့အချိန်၊ 1970 ကစပြီး စက္ကန့်နဲ့ ရေတွက် |
| iss / aud | ဘယ် server က ထုတ်လဲ၊ ဘယ် API အတွက် ရည်ရွယ်လဲ |
- Login: server က header + payload ကို sign
- Client က token ကို သိမ်း (သက်တမ်းတို)
- Call တိုင်း Authorization: Bearer <token>
- Server က signature ပြန်တွက်၊ exp စစ်
- မှန်ရင် claim ကို ယုံ၊ မဟုတ်ရင် 401
Signature က token ကို ပြင်ထားမှု မရှိဘူးလို့ သက်သေပြတာ၊ payload ကို ဖုံးအုပ်တာ မဟုတ်ပါဘူး။
အထွေထွေ ပုံစံ
Authorization: Bearer <header>.<payload>.<signature>
header = base64url({"alg":"HS256","typ":"JWT"})
payload = base64url({"sub":"...","exp":<unix seconds>})
signature = base64url(HMAC-SHA256(header + "." + payload, secret))Token ကို header တစ်ကြောင်းထဲမှာ ပို့ပါတယ်။ Signature က ရှေ့အပိုင်းနှစ်ခုကို secret နဲ့ ပေါင်းတွက်ထားတာမို့ တစ်လုံးပြောင်းရင်တောင် မကိုက်တော့ပါဘူး။
Worked example: JWT ကို ကိုယ်တိုင် ဆောက်ပြီး စစ်ကြည့်ခြင်း
Script က HS256 token တစ်ခုကို Node ရဲ့ crypto module နဲ့ ဆောက်ပါတယ်။ အရင်ဆုံး header နဲ့ payload ကို secret မလိုဘဲ decode လုပ်ပြပါတယ်၊ ဒါက ဘယ်သူမဆို ဖတ်နိုင်တယ်ဆိုတာ သက်သေပါ။ ပြီးတော့ local server ကို Bearer header နဲ့ ခေါ်ပါတယ်: token မှန်၊ payload ကို admin လို့ ပြင်ထားတဲ့ token၊ header မပါတာ၊ သက်တမ်းကုန်ပြီးတဲ့ token။
Secret နဲ့ token တွေက demo အတွက် ဖန်တီးထားတာပါ၊ လက်တွေ့ system မှာ သုံးလို့ မရပါဘူး။ Production code မှာတော့ ကိုယ်တိုင် မရေးဘဲ jose လို maintain လုပ်ထားတဲ့ library ကို သုံးပါ၊ ဒီ script က အပိုင်းတွေကို မြင်စေဖို့ပဲ ရည်ရွယ်ပါတယ်။ Clock ကိုလည်း ပုံသေ ထားထားလို့ output က အမြဲ တူပါတယ်။
import http from "node:http";
import crypto from "node:crypto";
const SECRET = "demo-signing-secret-not-for-production";
const encode = (value) => Buffer.from(value).toString("base64url");
const sign = (data) =>
crypto.createHmac("sha256", SECRET).update(data).digest("base64url");
function createToken(claims) {
const header = encode(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const payload = encode(JSON.stringify(claims));
return `${header}.${payload}.${sign(`${header}.${payload}`)}`;
}
let now = 1_700_000_000; // a fixed "now" in Unix seconds, so the output repeats
function verifyToken(token) {
const parts = token.split(".");
if (parts.length !== 3) return { ok: false, reason: "malformed" };
const [header, payload, signature] = parts;
if (JSON.parse(Buffer.from(header, "base64url")).alg !== "HS256") {
return { ok: false, reason: "unexpected_algorithm" }; // never trust the token's alg
}
const expected = Buffer.from(sign(`${header}.${payload}`));
const given = Buffer.from(signature);
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {
return { ok: false, reason: "invalid_signature" };
}
const claims = JSON.parse(Buffer.from(payload, "base64url"));
if (claims.exp <= now) return { ok: false, reason: "expired" };
return { ok: true, claims };
}
const server = http.createServer((req, res) => {
const reply = (status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
const [scheme, token] = (req.headers.authorization ?? "").split(" ");
if (scheme?.toLowerCase() !== "bearer" || !token) {
const challenge = { "WWW-Authenticate": 'Bearer realm="api"' };
return reply(401, { error: "missing_token" }, challenge);
}
const result = verifyToken(token);
if (!result.ok) {
const challenge = 'Bearer realm="api", error="invalid_token"';
return reply(401, { error: result.reason }, { "WWW-Authenticate": challenge });
}
const { sub, email, roles } = result.claims;
reply(200, { id: sub, email, roles });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
async function getMe(label, authorization) {
const headers = authorization ? { Authorization: authorization } : {};
const res = await fetch(`${base}/v1/me`, { headers });
console.log(`${label.padEnd(16)} ${res.status} ${await res.text()}`);
}
const claims = { sub: "u_1", email: "alice@example.com", roles: ["user"] };
const token = createToken({ ...claims, iat: now, exp: now + 900 });
const [header, payload, signature] = token.split(".");
console.log("header :", Buffer.from(header, "base64url").toString());
console.log("payload:", Buffer.from(payload, "base64url").toString());
await getMe("valid token", `Bearer ${token}`);
const forgedClaims = { ...claims, roles: ["admin"], iat: now, exp: now + 900 };
const forged = [header, encode(JSON.stringify(forgedClaims)), signature].join(".");
await getMe("edited payload", `Bearer ${forged}`);
await getMe("no header", undefined);
now += 1000; // 1000 seconds later, the 900-second token is past its exp
await getMe("after expiry", `Bearer ${token}`);
server.close();Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Encode the parts
const encode = (value) => Buffer.from(value).toString("base64url");JSON text ကို bytes ပြောင်းပြီး base64url string အဖြစ် ရေးပါတယ်။ Padding (=) မပါသလို URL မှာ ပြဿနာပေးတဲ့ + နဲ့ / လည်း မပါပါဘူး။
- Sign
return `${header}.${payload}.${sign(`${header}.${payload}`)}`;Token က header.payload.signature ပါ။ Signature ကို ရှေ့အပိုင်းနှစ်ခုကို dot နဲ့ ဆက်ထားတဲ့ စာကြောင်းပေါ်မှာ တွက်ပါတယ်၊ ဒါကြောင့် ဘယ်အပိုင်းကို ပြင်ပြင် signature မကိုက်တော့ပါဘူး။
- Pin the algorithm
if (JSON.parse(Buffer.from(header, "base64url")).alg !== "HS256") {Token ရဲ့ header က ကိုယ်ကိုယ်ကို ဘယ် algorithm လို့ ပြောပြော server ကတော့ HS256 ကိုပဲ လက်ခံပါတယ်။ Library အစောပိုင်းတချို့ကို alg none (signature မပါ) နဲ့ လှည့်စားလို့ရခဲ့တာကြောင့် ဒီစစ်ဆေးမှု လိုတာပါ။
- Verify the signature
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) {Server က signature ကို ပြန်တွက်ပြီး ရောက်လာတဲ့ signature နဲ့ constant-time နှိုင်းယှဉ်ပါတယ်။ timingSafeEqual က length မတူရင် error တက်လို့ အရင် length စစ်ပါတယ်။
- Check exp
if (claims.exp <= now) return { ok: false, reason: "expired" };Signature မှန်ပေမဲ့ exp ကျော်ပြီးရင် token က မသုံးရတော့ပါဘူး။ exp နဲ့ now နှစ်ခုစလုံး စက္ကန့်နဲ့ ရေတွက်တာမို့ တိုက်ရိုက် နှိုင်းယှဉ်လို့ရပါတယ်။
- Tamper on purpose
const forged = [header, encode(JSON.stringify(forgedClaims)), signature].join(".");Payload ကို roles: ['admin'] နဲ့ အစားထိုးပြီး မူရင်း signature ကို ပြန်သုံးပါတယ်။ Payload ပြောင်းသွားတာမို့ signature မကိုက်တော့ဘဲ server က invalid_signature နဲ့ ပယ်ချပါတယ်။
header : {"alg":"HS256","typ":"JWT"}
payload: {"sub":"u_1","email":"alice@example.com","roles":["user"],"iat":1700000000,"exp":1700000900}
valid token 200 {"id":"u_1","email":"alice@example.com","roles":["user"]}
edited payload 401 {"error":"invalid_signature"}
no header 401 {"error":"missing_token"}
after expiry 401 {"error":"expired"}- Authorization header ကို ဖတ်
- Header, payload, signature အဖြစ် ခွဲ
- Algorithm နဲ့ signature ကို စစ်
- exp (နဲ့ iss, aud) ကို စစ်
- Claim တွေကို ယုံပြီး handler run
Header မပါ
401 + Bearer realm
Signature မမှန် ဒါမှမဟုတ် သက်တမ်းကုန်
401 + error=invalid_token
အားလုံး မှန်
200 OK
exp က စက္ကန့်၊ base64url က base64 နဲ့ မတူ
JWT မှာ အချိန်တွေက 1970 ကစပြီး စက္ကန့်နဲ့ ရေတွက်ပါတယ်၊ JavaScript ရဲ့ Date.now() ကတော့ မီလီစက္ကန့်နဲ့ ရေတွက်ပါတယ်။ ဒီနှစ်ခုကို ရောရင် token အားလုံး သက်တမ်းကုန်နေသလို ဒါမှမဟုတ် ဘယ်တော့မှ မကုန်သလို ဖြစ်သွားနိုင်ပါတယ်။ အောက်က script က မှန်တဲ့ ပြောင်းနည်းနဲ့ မှားတဲ့ပုံစံကို ယှဉ်ပြပြီး base64 နဲ့ base64url ရဲ့ ကွာခြားချက်ကိုလည်း ပြပါတယ်။
const exp = 1700000900; // a JWT exp claim counts SECONDS since 1970
console.log(new Date(exp * 1000).toISOString()); // correct: convert to milliseconds
console.log(new Date(exp).toISOString()); // bug: treated as milliseconds
// base64 uses + and /, base64url uses - and _ so a token fits in a URL or header
const bytes = Buffer.from([251, 255, 254]);
console.log(bytes.toString("base64"));
console.log(bytes.toString("base64url"));ပထမ line က exp 1700000900 ကို 2023 ခုနှစ် နိုဝင်ဘာလက အချိန်အဖြစ် မှန်မှန်ကန်ကန် ပြပါတယ်။ ဒုတိယ line က တူညီတဲ့ နံပါတ်ကို မီလီစက္ကန့်လို့ ယူလိုက်လို့ 1970 ဇန်နဝါရီလ ဖြစ်သွားပါတယ်။ နောက်နှစ်ကြောင်းက byte အတူတူကို base64 မှာ +//+ ဖြစ်ပြီး base64url မှာ -__- ဖြစ်တာကို ပြပါတယ်။
HS256 လား RS256 လား
| Algorithm | Token ထုတ်နိုင်သူ | Token စစ်နိုင်သူ |
|---|---|---|
| HS256 (shared secret) | Secret ကို သိသူ အားလုံး | Secret ကို သိသူ အားလုံး |
| RS256 (key pair) | Private key ကို ကိုင်ထားသူ တစ်ဦးတည်း | Public key ရှိသူ ဘယ်သူမဆို |
Service တစ်ခုတည်းက token ထုတ်ပြီး ကိုယ်တိုင်ပဲ စစ်တယ်ဆိုရင် HS256 က ရိုးရှင်းပါတယ်။ Auth server တစ်ခုက ထုတ်ပြီး microservice အများကြီးက စစ်ရမယ်ဆိုရင် RS256 ကို ရွေးပါ၊ ဒါမှ service တွေကို secret မပေးဘဲ public key ပဲ ပေးလို့ရပါတယ်။ ဘယ်လိုပဲဖြစ်ဖြစ် verify လုပ်တဲ့ code ကပဲ ဘယ် algorithm ကို လက်ခံမလဲ ဆုံးဖြတ်ရပါမယ်။
Client က token ကို ဘယ်မှာ သိမ်းမလဲ
| သိမ်းဆည်းပုံ | Page JavaScript က ဖတ်နိုင်လား | အဓိက အန္တရာယ် |
|---|---|---|
| JavaScript variable (memory) | ဖတ်နိုင် (ဒီ page ရဲ့ code ပဲ) | Page ကို refresh လုပ်ရင် ပျောက် |
| HttpOnly cookie | မဖတ်နိုင် | CSRF ဖြစ်နိုင်လို့ SameSite နဲ့ CSRF ကာကွယ်မှု လို |
| localStorage | ဖတ်နိုင် | XSS bug တစ်ခုခုက token ကို ခိုးယူနိုင် |
အားလုံးအတွက် အကောင်းဆုံး ဆိုတာ မရှိပါဘူး၊ နည်းလမ်းတိုင်းမှာ trade-off ရှိပါတယ်။ ဘယ်နည်းကို ရွေးရွေး token သက်တမ်းကို တိုထားပါ၊ XSS ကို ကာကွယ်ပါ၊ ပြီးတော့ မယုံကြည်ရတဲ့ source က script တွေကို page ထဲ မထည့်ပါနဲ့။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ bearer token
Login endpoint တစ်ခုက email နဲ့ password ကို စစ်ပြီး access token (မကြာခဏ JWT) နဲ့ refresh token ပြန်ပေးပါတယ်။ Single-page app၊ mobile app နဲ့ အခြား service တွေက access token ကို Authorization header ထဲ ထည့်ပြီး API ကို ခေါ်ပါတယ်။ API gateway ဒါမှမဟုတ် middleware က token ကို စစ်ပြီး sub နဲ့ roles ကို request ထဲ ထည့်ပေးလိုက်တာမို့ handler တွေက ခေါ်သူ ဘယ်သူလဲ သိပါတယ်။
- Identity provider တွေ (Auth0, Keycloak, Amazon Cognito, Firebase Auth စတာတွေ) က JWT ထုတ်ပေးတာမို့ ကိုယ့် API ကတော့ ၎င်းတို့ရဲ့ public key နဲ့ token ကို စစ်ရုံပဲ လုပ်ရပါတယ်။
- Production မှာ maintain လုပ်ထားတဲ့ library (ဥပမာ jose) ကို သုံးပြီး iss, aud နဲ့ exp ကို အမြဲစစ်ပါ။ Clock မညီမှုအတွက် စက္ကန့်အနည်းငယ် leeway ပေးတာ ရှိပါတယ်။
- Access token သက်တမ်း မိနစ်အနည်းငယ်၊ refresh token ကို သီးသန့် ပိုလုံခြုံတဲ့ နေရာမှာ သိမ်းပါ၊ logout လုပ်ရင် refresh token ကို server ဘက်မှာ ပိတ်ပါ။
အမှားများ
Bearer token / JWT နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
Signature မစစ်ဘဲ payload ကို decode လုပ်ရုံ
atob ဒါမှမဟုတ် Buffer.from ကို payload ပေါ်မှာ သုံးရုံနဲ့ ဘာမှ မသက်သေပြပါဘူး။ Decode လုပ်တာနဲ့ verify လုပ်တာက မတူပါဘူး၊ claim ကို မယုံခင် signature နဲ့ exp ကို အမြဲ စစ်ပါ။
Payload ထဲ လျှို့ဝှက်ချက် ထည့်ခြင်း
Password, API key, ကိုယ်ရေးကိုယ်တာ အချက်အလက်တွေကို payload ထဲ မထည့်ပါနဲ့။ Token ကို ကိုင်ထားသူ၊ proxy နဲ့ log ကြည့်သူတိုင်း ဖတ်နိုင်ပါတယ်။ User id လို ဖော်ထုတ်လို့ရတဲ့ အချက်တွေပဲ ထည့်ပါ။
Seconds နဲ့ milliseconds ကို ရောခြင်း
exp က စက္ကန့်ပါ။ exp > Date.now() လို့ ရေးရင် Date.now() က ၁၀၀၀ ဆ ပိုကြီးလို့ token အားလုံး သက်တမ်းကုန်ပြီလို့ ပယ်ချမှာပါ။ Date.now() / 1000 ဒါမှမဟုတ် exp * 1000 လို့ ပြောင်းပါ။
သက်တမ်းရှည်လွန်းတဲ့ token
သက်တမ်းလ အနည်းငယ်ရှိတဲ့ JWT တစ်ခု ပေါက်ကြားရင် ရက်တွေ၊ အပတ်တွေ ကြာကြာ အသုံးချခံရနိုင်ပြီး stateless ဖြစ်လို့ ရုပ်သိမ်းဖို့လည်း ခက်ပါတယ်။ Access token ကို မိနစ်ဆယ်ချီပဲ ထားပြီး refresh လုပ်ခိုင်းပါ။
Best Practices
Best practices
- Verify ပြီးမှ claim ကို ယုံပါ၊ server မှာ algorithm ကို ကိုယ်တိုင် သတ်မှတ်ပါ။
- HTTPS ပေါ်မှာပဲ ပို့ပါ၊ access token ကို မိနစ်အနည်းငယ်ပဲ အသက်ရှိစေပါ။
- Payload ထဲမှာ အများမြင်လို့ရတဲ့ အချက်တွေပဲ ထည့်ပါ။
- Error response မှာ WWW-Authenticate နဲ့ error="invalid_token" ကို ပြန်ပြီး ဘာကြောင့် ကျသလဲ log မှာ မှတ်ပါ၊ token တစ်ခုလုံးကိုတော့ မမှတ်ပါနဲ့။
Mini challenge
Mini challenge: issuer နဲ့ audience စစ်တဲ့ token checker
HS256 token ကို ထုတ်တဲ့ issueToken နဲ့ စစ်တဲ့ checkToken ကို ရေးပါ။ checkToken က signature အပြင် issuer (iss) က auth.example.com ဟုတ်မဟုတ်၊ audience (aud) က ကိုယ့် API နာမည်နဲ့ ကိုက်မကိုက်၊ exp မကျော်သေးလား စစ်ရမယ်၊ ပြီးရင် အခြေအနေ ခြောက်ခုမှာ စမ်းပြီး ရလဒ်ကို print ထုတ်ပါ။
- Token ကို base64url နဲ့ ဖွဲ့စည်းပြီး crypto.createHmac နဲ့ sign လုပ်ရမယ်
- Signature ကို timingSafeEqual နဲ့ နှိုင်းယှဉ်ပြီး length မတူရင် error မတက်စေရဘူး
- ပျက်ကွက်ရင် malformed, bad_signature, wrong_issuer, wrong_audience, expired ထဲက reason တစ်ခု ပြန်ရမယ်
- အခြေအနေ ခြောက်ခုကို စမ်းပြီး တစ်ကြောင်းစီ print ထုတ်ပါ
import crypto from "node:crypto";
// TODO: a secret, the expected issuer, and two helpers: b64(object) and mac(text)
// TODO: issueToken(claims) -> "header.payload.signature" (HS256, iss added for you)
// TODO: checkToken(token, { audience, now })
// -> { ok: true, claims } or { ok: false, reason }
// reasons, in order: malformed, bad_signature, wrong_issuer, wrong_audience, expired
// TODO: build one good token, then check it in six situations and print one line each:
// valid, other audience, after expiry, foreign issuer, cut signature, two-part stringရလဒ်: valid က ok၊ other audience က wrong_audience၊ after expiry က expired၊ foreign issuer က wrong_issuer၊ cut signature က bad_signature၊ two-part string က malformed ဖြစ်ရမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Signature အရင်စစ်ပါ၊ မမှန်တဲ့ token ရဲ့ claim ကို ဘယ်တော့မှ မဖတ်ပါနဲ့။ Foreign issuer ကို စမ်းဖို့ issueToken ကနေ iss ကို override လုပ်လို့ရအောင် claims ကို နောက်မှ spread လုပ်ပါ။
အဖြေ ကြည့်ရန်
import crypto from "node:crypto";
const KEY = "challenge-secret-not-for-production";
const ISSUER = "auth.example.com";
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const mac = (text) => crypto.createHmac("sha256", KEY).update(text).digest("base64url");
function issueToken(claims) {
const head = b64({ alg: "HS256", typ: "JWT" });
const body = b64({ iss: ISSUER, ...claims });
return `${head}.${body}.${mac(`${head}.${body}`)}`;
}
function checkToken(token, { audience, now }) {
const parts = token.split(".");
if (parts.length !== 3) return { ok: false, reason: "malformed" };
const [head, body, sig] = parts;
const good = Buffer.from(mac(`${head}.${body}`));
const got = Buffer.from(sig);
if (good.length !== got.length || !crypto.timingSafeEqual(good, got)) {
return { ok: false, reason: "bad_signature" };
}
const claims = JSON.parse(Buffer.from(body, "base64url"));
if (claims.iss !== ISSUER) return { ok: false, reason: "wrong_issuer" };
if (claims.aud !== audience) return { ok: false, reason: "wrong_audience" };
if (claims.exp <= now) return { ok: false, reason: "expired" };
return { ok: true, claims };
}
const now = 1_800_000_000;
const claims = { sub: "u_7", aud: "orders-api", exp: now + 600 };
const good = issueToken(claims);
const foreign = issueToken({ ...claims, iss: "evil.example" });
const cases = [
["valid", checkToken(good, { audience: "orders-api", now })],
["other audience", checkToken(good, { audience: "billing-api", now })],
["after expiry", checkToken(good, { audience: "orders-api", now: now + 601 })],
["foreign issuer", checkToken(foreign, { audience: "orders-api", now })],
["cut signature", checkToken(good.slice(0, -4), { audience: "orders-api", now })],
["two-part string", checkToken("abc.def", { audience: "orders-api", now })],
];
for (const [label, result] of cases) {
console.log(label.padEnd(16), result.ok ? "ok" : result.reason);
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Bearer token ကို Authorization: Bearer <token> နဲ့ ပို့ပါတယ်၊ ကိုင်ထားသူတိုင်း သုံးနိုင်လို့ HTTPS နဲ့ သက်တမ်းတိုက ဆုံးဖြတ်ချက်ပါ။
- JWT က header.payload.signature ဖြစ်ပြီး base64url ပါ၊ sign လုပ်ထားတာဖြစ်ပြီး encrypt မလုပ်ထားလို့ payload ကို ဘယ်သူမဆို ဖတ်နိုင်ပါတယ်။
- Claim ကို မယုံခင် algorithm ကို pin လုပ်၊ signature ကို constant-time နဲ့ စစ်၊ exp (နဲ့ iss, aud) ကို စစ်ပါ။
- exp က စက္ကန့်၊ Date.now() က မီလီစက္ကန့်၊ ပျက်ကွက်ရင် 401 နဲ့ WWW-Authenticate ပြန်ပါ။