Thuta Learning
ရှာဖွေရန်
GraphQL
AdvancedWeb Developmentbeginner

GraphQL မှာ Auth — Authentication နှင့် Authorization

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

  • GraphQL မှာ Auth — Authentication နှင့် Authorization concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ GraphQL query/code ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် မှန်ကန်စွာအသုံးချနိုင်ရန်

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

GraphQL schema ကိုယ်တိုင်မှာ built-in auth mechanism မပါဘဲ authentication (ဒီလူဘယ်သူလဲ) ကို context creation အဆင့်မှာ token decode ပြီး လုပ်ပြီး authorization (ဒီလူ ဒီအရာလုပ်ခွင့်ရှိလား) ကို resolver တစ်ခုချင်းစီအတွက် explicit check အနေနဲ့ ရေးရပါတယ်။ Unauthenticated/unauthorized error များကို `GraphQLError` ထဲ `extensions.code: 'UNAUTHENTICATED'` သို့ `'FORBIDDEN'` ဖြင့် throw လုပ်ပြီး client က distinguish လုပ်နိုင်စေရပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

`deleteTutorial` mutation ရဲ့ resolver ထဲမှာ `context.userId` မရှိရင် `UNAUTHENTICATED` error ချက်ချင်း throw လုပ်ပြီး၊ user ရှိပေမယ့် `editor` role မပါရင် `FORBIDDEN` error ပြန်ပေးမယ်—checks နှစ်ခုစလုံးကို database delete ခေါ်ခင်း မခေါ်မီ လုပ်ရပါတယ်။

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

typescript
const resolvers = {
  Mutation: {
    deleteTutorial: (
      _parent: unknown,
      args: { id: string },
      context: Context,
    ) => {
      if (!context.userId) {
        throw new GraphQLError('You must be logged in', {
          extensions: { code: 'UNAUTHENTICATED' },
        });
      }
      if (!context.roles.includes('editor')) {
        throw new GraphQLError('Editors only', {
          extensions: { code: 'FORBIDDEN' },
        });
      }
      return tutorialRepository.delete(args.id);
    },
  },
};
You should see
Resolver ထဲမှာ authentication/authorization check နှစ်ခုကို မှန်ကန်စွာ ခွဲရေးနိုင်မည်။

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

`publishTutorial` mutation ကို `author` (own tutorials only) သို့ `editor` (any tutorial) role ခွင့်ပြုသော authorization rule နှင့်တကွ ရေးပါ။

သတိလေးတစ်ချက်

Authorization check ကို frontend UI level (button hide) မှာသာ လုပ်ပြီး resolver ထဲ server-side check မထားပါနှင့်—GraphQL client ကို anyone က raw request ပို့နိုင်လို့ server-side enforcement မဖြစ်မနေလိုပါတယ်။

Apollo Server — Authentication and AuthorizationGraphQL

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

  • Authorization check ကို frontend UI level (button hide) မှာသာ လုပ်ပြီး resolver ထဲ server-side check မထားပါနှင့်—GraphQL client ကို anyone က raw request ပို့နိုင်လို့ server-side enforcement မဖြစ်မနေလိုပါတယ်။
  • နမူနာ query/mutation ကို production API ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test server နှင့် recoverable data ပေါ်တွင် အရင်အတည်ပြုပါ။

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

`publishTutorial` mutation ကို `author` (own tutorials only) သို့ `editor` (any tutorial) role ခွင့်ပြုသော authorization rule နှင့်တကွ ရေးပါ။

You'll know it worked when: Resolver ထဲမှာ authentication/authorization check နှစ်ခုကို မှန်ကန်စွာ ခွဲရေးနိုင်မည်။

GraphQL မှာ Auth — Authentication နှင့် Authorization | Thuta Learning