Dark mode
WorkOS Authentication
WorkOS ช่วยให้การเพิ่ม Enterprise Authentication ง่ายขึ้นด้วยการรองรับ SSO, Directory Sync, และ Multi-factor Authentication (MFA)
การติดตั้ง
ติดตั้งแพ็คเกจที่จำเป็น:
bash
bun add @workos-inc/node @workos-inc/authkit-nextjs
bash
npm install @workos-inc/node @workos-inc/authkit-nextjs
bash
pnpm add @workos-inc/node @workos-inc/authkit-nextjs
bash
yarn add @workos-inc/node @workos-inc/authkit-nextjs
การตั้งค่า
1. ตั้งค่า Environment Variables
สร้างไฟล์ .env.local
และเพิ่มค่าต่อไปนี้:
bash
WORKOS_CLIENT_ID=your_workos_client_id
WORKOS_API_KEY=your_workos_api_key
WORKOS_REDIRECT_URI=http://localhost:3000/api/auth/callback
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_nextauth_secret
2. สร้าง WorkOS Configuration
สร้างไฟล์ lib/workos.ts
:
ts
import { WorkOS } from "@workos-inc/node";
export const workos = new WorkOS(process.env.WORKOS_API_KEY);
export const clientId = process.env.WORKOS_CLIENT_ID!;
วิธีการใช้งาน
1. ตั้งค่า Auth Provider
สร้างไฟล์ app/api/auth/[...nextauth]/route.ts
:
ts
import { workos } from "@/lib/workos";
import NextAuth from "next-auth";
export const authOptions = {
providers: [
{
id: "workos",
name: "WorkOS",
type: "oauth",
authorization: {
url: "https://api.workos.com/sso/authorize",
params: {
response_type: "code",
client_id: process.env.WORKOS_CLIENT_ID,
redirect_uri: process.env.WORKOS_REDIRECT_URI,
},
},
token: {
async request(context) {
const { code } = context.params;
const token = await workos.sso.getToken({
code,
clientId: process.env.WORKOS_CLIENT_ID!,
grantType: "authorization_code",
redirectUri: process.env.WORKOS_REDIRECT_URI!,
});
return { tokens: { access_token: token.accessToken } };
},
},
userinfo: {
async request(context) {
const { access_token } = context.tokens;
const profile = await workos.sso.getProfile(access_token!);
return {
id: profile.id,
email: profile.email,
name: [profile.firstName, profile.lastName].filter(Boolean).join(
" ",
),
image: profile.picture,
};
},
},
idToken: false,
checks: ["pkce", "state"],
profile(profile) {
return {
id: profile.id,
email: profile.email,
name: profile.name,
image: profile.picture,
};
},
},
],
callbacks: {
async session({ session, token }) {
if (session?.user) {
session.user.id = token.sub;
}
return session;
},
},
secret: process.env.NEXTAUTH_SECRET,
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
2. หน้า Login
สร้างไฟล์ app/login/page.tsx
:
tsx
"use client";
import { signIn } from "next-auth/react";
export default function LoginPage() {
const handleLogin = () => {
signIn("workos", { callbackUrl: "/dashboard" });
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full space-y-8 p-8 bg-white rounded-lg shadow-md">
<h2 className="text-2xl font-bold text-center">เข้าสู่ระบบ</h2>
<button
onClick={handleLogin}
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>
เข้าสู่ระบบด้วย WorkOS
</button>
</div>
</div>
);
}
3. หน้า Dashboard
สร้างไฟล์ app/dashboard/page.tsx
:
tsx
"use client";
import { signOut, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
export default function DashboardPage() {
const { data: session, status } = useSession();
const router = useRouter();
if (status === "loading") {
return (
<div className="min-h-screen flex items-center justify-center">
กำลังโหลด...
</div>
);
}
if (!session) {
router.push("/login");
return null;
}
const handleSignOut = async () => {
await signOut({ callbackUrl: "/login" });
};
return (
<div className="min-h-screen bg-gray-50 p-8">
<div className="max-w-4xl mx-auto bg-white rounded-lg shadow p-6">
<div className="flex justify-between items-center mb-8">
<h1 className="text-2xl font-bold">แดชบอร์ด</h1>
<button
onClick={handleSignOut}
className="px-4 py-2 bg-red-500 hover:bg-red-600 text-white rounded-md"
>
ออกจากระบบ
</button>
</div>
<div className="space-y-4">
<div className="p-4 bg-gray-50 rounded-lg">
<h2 className="text-lg font-semibold mb-2">ข้อมูลผู้ใช้</h2>
<p>
<span className="font-medium">ชื่อ:</span> {session.user?.name}
</p>
<p>
<span className="font-medium">อีเมล:</span> {session.user?.email}
</p>
{session.user?.image && (
<img
src={session.user.image}
alt="Profile"
className="w-20 h-20 rounded-full mt-4"
/>
)}
</div>
</div>
</div>
</div>
);
}
การใช้งานกับ Enterprise SSO
1. ตั้งค่า Enterprise Connection
สร้างไฟล์ app/api/sso/route.ts
:
ts
import { workos } from "@/lib/workos";
import { NextResponse } from "next/server";
export async function GET() {
const authorizationUrl = workos.sso.getAuthorizationURL({
// ระบุ Connection ID หรือ Organization ID
connection: "conn_xxxxxxxxxxxxx",
clientId: process.env.WORKOS_CLIENT_ID!,
redirectUri: process.env.WORKOS_REDIRECT_URI!,
state: JSON.stringify({
custom_state: "your_custom_state",
}),
});
return NextResponse.redirect(authorizationUrl);
}
ข้อดีของ WorkOS
- รองรับ Enterprise SSO - เชื่อมต่อกับ SAML, OIDC, Google Workspace, Microsoft 365 และอื่นๆ
- Directory Sync - ซิงค์ข้อมูลผู้ใช้จาก Active Directory และ LDAP
- Multi-factor Authentication - เพิ่มความปลอดภัยด้วย MFA
- Audit Logs - บันทึกการเข้าถึงและกิจกรรมต่างๆ
- Developer Experience - API ที่ใช้งานง่ายและเอกสารที่ครบถ้วน
ข้อควรระวัง
- ตั้งค่า
WORKOS_API_KEY
และWORKOS_CLIENT_ID
ให้ถูกต้อง - ตรวจสอบ Redirect URI ใน WorkOS Dashboard
- ใช้ HTTPS ใน production
- ตั้งค่า CORS ให้เหมาะสม
แหล่งข้อมูลเพิ่มเติม
ตัวอย่างการใช้งานเพิ่มเติม
1. ตรวจสอบสิทธิ์ใน API Route
สร้างไฟล์ app/api/protected/route.ts
:
ts
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { getServerSession } from "next-auth";
import { NextResponse } from "next/server";
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401 },
);
}
return NextResponse.json({
message: "ข้อมูลลับ",
user: session.user,
});
}
2. ใช้กับ Middleware
สร้างไฟล์ middleware.ts
:
ts
import { withAuth } from "next-auth/middleware";
export default withAuth({
callbacks: {
authorized: ({ token }) => !!token,
},
});
export const config = {
matcher: ["/dashboard/:path*", "/api/protected/:path*"],
};
ด้วย WorkOS คุณสามารถเพิ่มระบบ Authentication ระดับองค์กรให้กับแอปพลิเคชัน Next.js ของคุณได้อย่างง่ายดายและปลอดภัย