Thuta Learning
ရှာဖွေရန်
AdvancedWeb Developmentintermediate

Authentication နှင့် Authorization

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

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

  • Authentication နှင့် authorization ကို ခွဲခြားရန်
  • Server Action နှင့် data layer မှာ permission စစ်ရန်
  • UI hide လုပ်ခြင်းတစ်ခုတည်းကို security မယူဆရန်

Delete button ကိုမပြတာက လုံခြုံရေးမဟုတ်ပါဘူး။ User က request ကို ကိုယ်တိုင်ပို့နိုင်သေးလို့ server ဘက်မှာ “ဒီလူကဘယ်သူလဲ” နဲ့ “ဒီ note ကိုဖျက်ခွင့်ရှိလား” နှစ်ခုလုံး ပြန်စစ်ရပါတယ်။

နားလည်ထားရမယ့် အချက်

Authentication က session မှ user identity အတည်ပြုခြင်း၊ authorization က resource ပိုင်ရှင် သို့မဟုတ် role ကိုစစ်ခြင်းပါ။ Layout မှာ redirect လုပ်တာက user experience အတွက်အသုံးဝင်ပေမယ့် data access function နဲ့ Server Action အတွင်းစစ်တာက တကယ့်ကာကွယ်မှုဖြစ်ပါတယ်။ Session cookie ကို httpOnly၊ secure နဲ့ sameSite policy သင့်တော်စွာထားပြီး password hashing နဲ့ CSRF ကာကွယ်မှုလို အလုပ်တွေကို စမ်းသပ်ပြီးသား auth library သုံးတာ ပိုကောင်းပါတယ်။

အတူတူ စမ်းရေးကြည့်မယ်

typescript
"use server";

export async function deleteNote(noteId: string) {
  const session = await getSession();
  if (!session?.user) throw new Error("Unauthorized");

  const note = await db.note.findUnique({ where: { id: noteId } });
  if (!note) throw new Error("Not found");
  if (note.ownerId !== session.user.id) throw new Error("Forbidden");

  await db.note.delete({ where: { id: noteId } });
}

Code က ဘယ်လိုအလုပ်လုပ်သလဲ

deleteNote က session မရှိရင် unauthorized error ပစ်ပြီး note.ownerId နဲ့ current user id ကိုနှိုင်းပါတယ်။ Button ကိုဖျောက်ထားလည်း direct request ရောက်လာချိန် ဒီစစ်ဆေးမှုကကာကွယ်ပေးပါတယ်။

You should see
Login ဝင်ထားပြီး note ပိုင်ရှင်ဖြစ်သူသာ delete လုပ်နိုင်မည်။

၅ မိနစ် စမ်းကြည့်

Editor role ရှိသူ သို့မဟုတ် note ပိုင်ရှင်သာ update လုပ်နိုင်မည့် permission check ရေးပါ။

Next.js — AuthenticationNext.js

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Button ဖျောက်ထားတာကို authorization လို့ယူဆခြင်း
  • Layout တစ်နေရာမှာ session စစ်ပြီး data function တိုင်းလုံခြုံပြီဟု ယူဆခြင်း

လေ့ကျင့်ခန်း

Editor role ရှိသူ သို့မဟုတ် note ပိုင်ရှင်သာ update လုပ်နိုင်မည့် permission check ရေးပါ။

You'll know it worked when: Login ဝင်ထားပြီး note ပိုင်ရှင်ဖြစ်သူသာ delete လုပ်နိုင်မည်။

Authentication နှင့် Authorization | Thuta Learning