{"id":15099088,"url":"https://github.com/washira/next-auth0","last_synced_at":"2026-01-06T10:54:50.390Z","repository":{"id":226692296,"uuid":"768932376","full_name":"Washira/next-auth0","owner":"Washira","description":null,"archived":false,"fork":false,"pushed_at":"2024-03-13T02:55:17.000Z","size":73,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-02-01T17:45:04.037Z","etag":null,"topics":["auth0","javascript","nextjs14"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Washira.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-03-08T02:01:56.000Z","updated_at":"2024-03-09T01:56:50.000Z","dependencies_parsed_at":"2024-03-13T03:41:55.902Z","dependency_job_id":"f289ac5c-8c15-424b-805a-fea824e5129c","html_url":"https://github.com/Washira/next-auth0","commit_stats":null,"previous_names":["washira/next-auth0"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Washira%2Fnext-auth0","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Washira%2Fnext-auth0/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Washira%2Fnext-auth0/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Washira%2Fnext-auth0/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Washira","download_url":"https://codeload.github.com/Washira/next-auth0/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245854995,"owners_count":20683446,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth0","javascript","nextjs14"],"created_at":"2024-09-25T17:05:12.280Z","updated_at":"2026-01-06T10:54:50.357Z","avatar_url":"https://github.com/Washira.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).\n\n- [Getting Started](#getting-started)\n- [Learn More](#learn-more)\n- [Deploy on Vercel](#deploy-on-vercel)\n- [Auth0 Workflow](#auth0-workflow)\n- [Auth0 Configuration](#auth0-configuration)\n- [Configure SDK](#configure-sdk)\n- [Auth0 APIs](#auth0-apis)\n- [การใช้งาน](#การใช้งาน)\n- [ตั้งค่าใน Auth0 dashboard settings](#ตั้งค่าใน-auth0-dashboard-settings)\n- [User Management](#user-management)\n- [Profile page](#profile-page)\n  - [Redirecting to the profile page](#redirecting-to-the-profile-page)\n- [RBAC (Role-Based Access Control)](#rbac-role-based-access-control)\n  - [การสร้าง API](#การสร้าง-api)\n  - [สร้าง Permission](#สร้าง-permission)\n  - [เพิ่ม Permission ให้กับ User](#เพิ่ม-permission-ให้กับ-user)\n  - [กำหนด audience ให้กับ API](#กำหนด-audience-ให้กับ-api)\n  - [JWT Decode](#jwt-decode)\n  - [สร้าง Role](#สร้าง-role)\n  - [สรุป](#สรุป)\n- [Flow](#flow)\n\n## Getting Started\n\nFirst, run the development server:\n\n```bash\nnpm run dev\n# or\nyarn dev\n# or\npnpm dev\n# or\nbun dev\n```\n\nOpen [http://localhost:3000](http://localhost:3000) with your browser to see the result.\n\nYou can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.\n\nThis project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.\n\n## Learn More\n\nTo learn more about Next.js, take a look at the following resources:\n\n- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.\n- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.\n\nYou can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!\n\n## Deploy on Vercel\n\nThe easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template\u0026filter=next.js\u0026utm_source=create-next-app\u0026utm_campaign=create-next-app-readme) from the creators of Next.js.\n\nCheck out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.\n\n## Auth0 Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Auth0\n    participant Application\n\n    User-\u003e\u003eApplication: Request to access protected resource\n    Application-\u003e\u003eUser: Redirect to Auth0 login page\n    User-\u003e\u003eAuth0: Enter login credentials\n    Auth0--\u003e\u003eUser: Verify login credentials\n    User--\u003e\u003eAuth0: Confirm login\n    Auth0--\u003e\u003eApplication: Provide authentication token\n    Application-\u003e\u003eApplication: Validate token\n    Application--\u003e\u003eUser: Grant access to resource\n```\n\n## Auth0 Configuration\n\nเริ่มที่การสร้่าง Application ที่ Auth0 dashboard ที่นี่ [Auth0 Dashboard](https://manage.auth0.com/dashboard)\n\nจากนั้น สร้าง Next.js ขึ้นมา แล้วติดตั้ง `auth0` โดยใช้คำสั่ง\n\n```bash\nnpm install @auth0/nextjs-auth0\n```\n\n## Configure SDK\n\nสร้างไฟล์ `.env.local` และเพิ่มข้อมูลดังนี้\n\n```bash\nAUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'\nAUTH0_BASE_URL='http://localhost:3000'\nAUTH0_ISSUER_BASE_URL='YOUR_AUTH0_ISSUER_BASE_URL'\nAUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'\nAUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'\n```\n\n## Auth0 APIs\n\nAuth0 จะมี APIs ที่ใช้ในการทำงาน ดังนี้\n\n- `/api/auth/login` - ใช้ในการเข้าสู่ระบบ\n- `/api/auth/logout` - ใช้ในการออกจากระบบ\n- `/api/auth/me` - ใช้ในการดึงข้อมูลของผู้ใช้\n- `/api/auth/callback` - ใช้ในการรับข้อมูลจาก Auth0 หลังจากที่ผู้ใช้เข้าสู่ระบบ\n\n## การใช้งาน\n\nนำเอา `auth0` มาติดตั้งใน `app/layout.js` ก่อน\n\n```javascript\nimport { UserProvider } from '@auth0/nextjs-auth0'\n\nexport default function RootLayout({ children }) {\n  return (\n    \u003chtml lang=\"en\"\u003e\n      \u003cUserProvider\u003e\n        \u003cbody className={inter.className}\u003e{children}\u003c/body\u003e\n      \u003c/UserProvider\u003e\n    \u003c/html\u003e\n  )\n}\n```\n\nจากนั้น นำเอา `\u003ca href=\"/api/auth/login\"\u003eLogin\u003c/a\u003e` ไปเพิ่มใน `app/page.js` เพื่อให้ไปหน้า login\n\nแต่ยังไม่สามารถ login ได้เพราะยังไม่ได้ตั้งค่าใน Auth0 ให้เรียบร้อย\n\n## ตั้งค่าใน Auth0 dashboard settings\n\nเข้าไปที่ dashboard \u003e Applications \u003e Applications \u003e เลือก application ที่เราสร้างขึ้นมา \u003e Settings\n\n1. ไปที่ [Auth0 Dashboard](https://manage.auth0.com/dashboard)\n2. ไปที่ `Applications` แล้วสร้าง Application ใหม่\n3. ตั้งค่า `Allowed Callback URLs` เป็น path ที่เราต้องการให้ redirect เมื่อกด login เช่น `http://localhost:3000/api/auth/callback`\n4. ตั้งค่า `Allowed Web Origins` ให้ตรงกับที่เราใช้งาน เช่น `http://localhost:3000`\n5. ตั้งค่า `Allowed Origins (CORS)` ให้ตรงกับที่เราใช้งาน เช่น `http://localhost:3000`\n6. ตั้งค่า `Application URIs` ให้ตรงกับที่เราใช้งาน เช่น `http://localhost:3000`\n7. ตั้งค่า `Token Endpoint Authentication Method` ให้เป็น `Post`\n8. ตั้งค่า `Use Auth0 instead of the IdP to do Single Sign On` ให้เป็น `True`\n9.  ตั้งค่า `OIDC Conformant` ให้เป็น `True`\n10. ตั้งค่า `Application Type` ให้เป็น `Regular Web Application`\n11. ตั้งค่า `Allowed Logout URLs` ให้เป็น path ที่เราต้องการให้ redirect หลังจาก logout แล้ว เช่น `http://localhost:3000`\n\nจากนั้น กด `Save Changes`\n\nเมื่อทำการตั้งค่าเรียบร้อยแล้ว ก็สามารถ login ได้แล้ว\n\n## User Management\n\nเมื่อมีการ login เข้ามา เราสามารถดูคนที่ login ได้ โดยเข้าไปดูที่ dashboard \u003e User Management \u003e Users\n\nจะเห็นหน้่ารายชื่อของคนที่ login เข้ามาทั้งหมด\n\n## Profile page\n\nเราสามารถดึงข้อมูลของผู้ใช้ที่ login เข้ามาได้ \n\nถ้าดึงข้อมูลแบบ Server-side ให้ใข้ `useUser` จาก `@auth0/nextjs-auth0`\n\n```javascript\n// app/profile/page.js\nimport { getSession } from '@auth0/nextjs-auth0'\n\nexport default async function ProfileServer() {\n  const { user } = await getSession()\n\n  return (\n      user \u0026\u0026 (\n          \u003cdiv\u003e\n            \u003cimg src={user.picture} alt={user.name} /\u003e\n            \u003ch2\u003e{user.name}\u003c/h2\u003e\n            \u003cp\u003e{user.email}\u003c/p\u003e\n          \u003c/div\u003e\n      )\n  )\n}\n```\n\nถ้าต้องการ ดึง แบบ Client-side ให้ใช้ `useUser` จาก `@auth0/nextjs-auth0/client`\n\n```javascript\n// app/profile/page.js\n'use client'\n\nimport { useUser } from '@auth0/nextjs-auth0/client'\n\nexport default function ProfileClient() {\n  const { user, error, isLoading } = useUser()\n\n  if (isLoading) return \u003cdiv\u003eLoading...\u003c/div\u003e\n  if (error) return \u003cdiv\u003e{error.message}\u003c/div\u003e\n\n  return (\n    user \u0026\u0026 (\n      \u003cdiv\u003e\n        \u003cimg src={user.picture} alt={user.name} /\u003e\n        \u003ch2\u003e{user.name}\u003c/h2\u003e\n        \u003cp\u003e{user.email}\u003c/p\u003e\n      \u003c/div\u003e\n    )\n  )\n}\n```\n\nเราจะสามารถดึงข้อมูลมาแสดงได้เหมือนกับเรียก API `GET /api/auth/me`\n\n### Redirecting to the profile page\n\nเราสามารถทำการ redirect ไปที่ หลังจาก login แล้ว ให้ไปที่ profile page ได้ และถ้าไม่ได้ login ก็ให้ไปที่หน้า login แทน\nโดยใช้ `middleware.js`\n\n```javascript\nimport { NextResponse } from 'next/server'\nimport {\n  withMiddlewareAuthRequired,\n  getSession,\n} from '@auth0/nextjs-auth0/edge'\n\nexport default withMiddlewareAuthRequired(async (req) =\u003e {\n  const res = NextResponse.next()\n  const user = await getSession(req, res)\n  if (!user) {\n    return NextResponse.redirect('/api/auth/login')\n  }\n  return res\n})\n\nexport const config = {\n  matcher: '/profile',\n}\n```\n\nและเพิ่ม `haddleLogin` ใน `app/api/auth/[auth0]/route.js`\n\n```javascript\nimport { handleAuth, handleLogin } from '@auth0/nextjs-auth0'\n\nexport const GET = handleAuth({\n  login: handleLogin({\n    returnTo: '/profile',\n  }),\n})\n```\n\n## RBAC (Role-Based Access Control)\n\nการสร้าง Permission โดยแบ่งตาม Role ใน Auth0 และให้สิทธิ์ในการเข้าถึง API ต่าง ๆ\n\n### การสร้าง API\n\n1. ไปที่ dashboard \u003e APIs \u003e APIs\n2. กด `Create API`\n3. กรอกข้อมูลดังนี้\n   - Name: ชื่อ API\n   - Identifier: ชื่อ API ที่เราต้องการให้มี ในที่นี้เราให้เป็น `http://localhost:3000`\n   - Signing Algorithm: ให้เลือก `RS256`\n  แล้วกด `Create`\n\n### สร้าง Permission\n\n1. ไปที่ dashboard \u003e APIs \u003e APIs\n2. เลือก API ที่เราสร้างขึ้นมา\n3. ไปที่ `Permissions` แล้วกด `Create Permission`\n4. กรอกข้อมูลดังนี้\n   - Name: ชื่อ Permission\n   - Description: คำอธิบายของ Permission\n - แล้วกด `add`\n\nสามารถสร้าง permission ได้หลาย ๆ อัน\n\nจากนั้นไปที่ `settings` แล้วเลือก `RBAC` แล้วกด enable `Enable RBAC` และ `Add Permissions in the Access Token` แล้วกด `Save`\n\n### เพิ่ม Permission ให้กับ User\n\n1. ไปที่ dashboard \u003e User Management \u003e Users\n2. เลือก User ที่เราต้องการให้มี Permission\n3. ไปที่ `Permissions` แล้วกด `Assign Permissions`\n4. ให้เลือก API ที่เราสร้างขึ้นมา\n5. ให้เลือก Permission ที่เราสร้างขึ้นมา\n6. แล้วกด `Add Permissions`\n\n### กำหนด audience ให้กับ API\n\nเราต้องการให้ API ที่เราสร้างขึ้นมา รู้ว่าเราต้องการให้มีการเข้าถึง Permission ที่เราสร้างขึ้นมา ดังนั้นเราต้องกำหนด `audience` ให้กับ API ด้วย\n\n`audience` คือ ชื่อ API ที่เราสร้างขึ้นมา เช่น `http://localhost:3000`\n\nส่วนของ Next.js ที่เราต้องการให้มีการเข้าถึง Permission ที่เราสร้างขึ้นมา ต้องกำหนด `audience` ให้กับ API ด้วย\n\n```javascript\n// app/api/auth/[auth0]/route.js\nimport { handleAuth, handleLogin } from '@auth0/nextjs-auth0'\n\nexport const GET = handleAuth({\n  login: handleLogin({\n+    authorizationParams: {\n+      audience: \"http://localhost:3000\",\n+    },\n    returnTo: '/profile',\n  }),\n})\n```\n\n### JWT Decode\n\nติดตั้ง `jwt-decode` เพื่อใช้ในการ decode token ที่ได้จาก Auth0\n\n```bash\nnpm install jwt-decode\n```\n\nจากนั้นเราสามารถดึงข้อมูลของ token ที่ได้จาก Auth0 ได้ และดูว่ามี Permission อะไรบ้าง\n\n```javascript\n// middleware.js\n\n...\nconst user = await getSession(req, res)\n...\n\nconst userPermissionData = jwtDecode(user.accessToken)\nconsole.log(userPermissionData)\n\n...\n```\n\nเราจะเห็นว่ามีข้อมูลของ Permission ที่เราสร้างขึ้นมา\n\n```bash\nuserPermissionData {\n  iss: '...',\n  sub: '...',\n  aud: [ 'http://localhost:3000', '...' ],\n  iat: 1710172049,\n  exp: 1710258449,\n  azp: '...',\n  scope: 'openid profile email',\n  permissions: [ 'read:next-auth-test' ]\n}\n```\n\nสังเกตว่า `userPermissionData` ที่เราสร้างขึ้นมา มี `scope` และ `permissions` \n\n`scope` คือ ข้อมูลของ User ที่ application สามารถดึงข้อมูลมาใช้ได้ ซึ่งปกติจะมี `openid profile email` ที่ผ่านการขออนุญาตจาก User แล้ว\n\nส่วน `permissions` คือ สิทธิ์ที่เราสามารถทำได้ ใน application ใดๆ\n\nเราสามารถเพิ่ม `scope` ด้วย `permissions` ได้ เพิ่มสิทธิ์ให้กับ user ใน application นั้น ๆ เช่น `read:next-auth-test`\n\n```javascript\n// app/api/auth/[auth0]/route.js\nimport { handleAuth, handleLogin } from '@auth0/nextjs-auth0'\n\nexport const GET = handleAuth({\n  login: handleLogin({\n    authorizationParams: {\n      audience: \"http://localhost:3000\",\n+      scope: \"openid profile email read:next-auth-test\"\n    },\n    returnTo: '/profile',\n  }),\n})\n```\n\nเมื่อ login อีกที เราจะเจอส่วนของการขออนุญาตใช้ `scope` นี้เพิ่มขึ้นมา\n\nทีนี้ เราจะได้ `scope` เป็น `openid profile email read:next-auth-test` แล้ว\n\n```bash\nuserPermissionData {\n  iss: '...',\n  sub: '...',\n  aud: [ 'http://localhost:3000', '...' ],\n  iat: 1710172049,\n  exp: 1710258449,\n  azp: '...',\n  scope: 'openid profile email read:next-auth-test',\n  permissions: [ 'read:next-auth-test' ]\n}\n```\n\n### สร้าง Role\n\nเราสามารถสร้าง Role ให้กับ User ได้ และกำหนด Permission ให้กับ Role นั้น ๆ\n\n1. ไปที่ dashboard \u003e User Management \u003e Roles\n2. กด `Create Role`\n3. กรอกข้อมูลดังนี้\n   - Name: ชื่อ Role\n   - Description: คำอธิบายของ Role\n   - แล้วกด `Create`\n4. กด `Add Permissions` \u003e เลือก API ที่เราสร้างขึ้นมา \u003e เลือก Permission ที่มี\n5. กด `Add Users` เพื่อกำหนด User ที่เราต้องการให้มี Role นี้ แล้วกด `Save`\n6. เข้าไปดูใน User ที่เรากำหนด Role ไว้ จะเห็นว่ามี Role ที่เรากำหนดไว้ และมี Permission ที่เรากำหนดใน Role เพิ่มมาด้วย\n\n### สรุป\n\nเราสามารถกำหนดสิทธิ์ให้กับ User ได้ โดยการกำหนด Permission ให้กับ User โดยตรง หรือกำหนด Permission ให้กับ Role แล้วกำหนด Role ให้กับ User ได้ เราเรียก Role ว่า เป็นการ group permissions ไว้ด้วยกัน\n\n## Flow\n\nFlow คือ การแทรกการทำงานระหว่างกลางของ application และ Auth0 โดยเราสามารถทำได้หลายอย่าง เช่น\n\n- `Login Flow` - การทำงานเมื่อมีการ login\n- `Machine to Machine Flow` - การทำงานก่อน token issued เสร็จ\n- `Pre User Registration Flow` - การทำงานก่อนมีการลงทะเบียน\n- `Post User Registration Flow` - การทำงานเมื่อมีการลงทะเบียน\n- `Post Change Password Flow` - การทำงานเมื่อมีการเปลี่ยนรหัสผ่าน\n- `Send Phone Message Flow` - การทำงานก่อนการส่งข้อความไปยังโทรศัพท์\n- `Password Reset / Post Challenge Flow` - การทำงานเมื่อมีการเปลี่ยนรหัสผ่านหลังจากที่ทำการ reset password","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwashira%2Fnext-auth0","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwashira%2Fnext-auth0","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwashira%2Fnext-auth0/lists"}