Next.js 15 Fullstack (App Router + Server Actions) · บทเรียน

การผสานรวม Passport.js

เรียนรู้การผสานรวมกลยุทธ์ของ Passport.js เช่น Local และ JWT เพื่อสร้างกระบวนการยืนยันตัวตนที่ยืดหยุ่นและทนทาน

บทเรียน 6 จาก 611 ขั้นตอน

การผสานรวม Passport.js เป็นบทเรียน Next.js 15 Fullstack (App Router + Server Actions) ฟรีบน CoddyKit นี่คือบทเรียนที่ 6 จากทั้งหมด 6 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack (App Router + Server Actions) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 6 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Meet Passport.js

Welcome to integrating Passport.js with NestJS! Passport is a popular authentication middleware for Node.js applications.

It provides a flexible and modular way to handle different authentication mechanisms, known as 'strategies'. NestJS has excellent integration with Passport, making it easy to secure your APIs.

Setting Up Passport.js

To get started, you'll need to install a few packages. We'll install the core Passport packages for NestJS and specific strategies for local (username/password) and JWT authentication.

  • @nestjs/passport: NestJS integration
  • passport: Core Passport.js library
  • passport-local: For username/password authentication
  • passport-jwt: For JSON Web Token authentication
npm install @nestjs/passport passport passport-local passport-jwt

Passport Strategy: Local

The Local Strategy is used for traditional username and password authentication. When a user tries to log in, Passport.js uses this strategy to verify their credentials.

You'll create a class that extends PassportStrategy(Strategy, 'local') and implement a validate method. This method receives the username and password from the request.

Local Strategy Logic

The validate method is the heart of any Passport strategy. It's where you define the logic to verify credentials (e.g., checking against a database). If validation succeeds, it returns the user object; otherwise, it returns null or throws an error.

Try running this simplified example of the validate logic:

class MockLocalStrategy {
  async validate(username: string, password: string): Promise<any> {
    // In a real app, you'd query a database here
    if (username === 'testuser' && password === 'mypass') {
      return { userId: 1, username: 'testuser' };
    }
    return null; // Or throw an error for invalid credentials
  }
}

async function main() {
  const strategy = new MockLocalStrategy();
  const user = await strategy.validate('testuser', 'mypass');

  if (user) {
    console.log(`Auth successful for: ${user.username}`);
  } else {
    console.log('Auth failed: Invalid credentials');
  }
}

main();

Using Local Strategy with Guards

Once your LocalStrategy is defined and registered, you can protect routes using NestJS Guards. The AuthGuard('local') leverages your strategy to authenticate incoming requests.

If the user is authenticated, the user object returned by your validate method will be attached to the request (req.user).

@Post('login')
@UseGuards(AuthGuard('local'))
async login(@Request() req) {
  return req.user;
}

Passport Strategy: JWT

The JWT Strategy is used to validate JSON Web Tokens. Instead of username/password, it extracts the JWT from the request (usually from the Authorization header) and verifies its signature.

Your JwtStrategy also has a validate method, but it receives the decrypted JWT payload. You then use this payload to identify and return the user.

JWT Strategy Logic

For the JWT Strategy, the validate method receives the token's payload after Passport has already verified the token's signature. Your job here is usually to retrieve the user associated with that payload (e.g., from a database).

Here's a simplified example of the validate logic:

class MockJwtStrategy {
  async validate(payload: any): Promise<any> {
    // In a real app, you'd fetch user from DB based on payload.sub
    if (payload && payload.sub === 101) {
      return { userId: payload.sub, username: 'apiuser' };
    }
    return null; // User not found or invalid payload
  }
}

async function main() {
  const strategy = new MockJwtStrategy();
  // Imagine this payload came from a verified JWT
  const mockPayload = { sub: 101, username: 'apiuser', iat: 123, exp: 456 };

  const user = await strategy.validate(mockPayload);

  if (user) {
    console.log(`JWT validation successful for: ${user.username}`);
  } else {
    console.log('JWT validation failed: User not found');
  }
}

main();

Using JWT Strategy with Guards

Similar to the local strategy, you use AuthGuard('jwt') to protect routes that require a valid JWT. This guard automatically extracts, validates, and decodes the token using your JwtStrategy.

If the token is valid, the user object returned by validate is attached to req.user.

@Get('profile')
@UseGuards(AuthGuard('jwt'))
getProfile(@Request() req) {
  return req.user;
}

Flexible Authentication Flows

Passport.js excels in its flexibility. You can use multiple strategies within a single application and even specify multiple strategies for a single route using AuthGuard(['jwt', 'local']).

This allows you to support various authentication methods, like social logins (OAuth strategies), API keys, or session-based auth, all managed by Passport's unified interface.

Check Your Understanding

Let's test your knowledge about Passport.js strategies.

Recap: Passport.js Integration

In this lesson, we explored how to integrate Passport.js into your NestJS applications. We covered:

  • The core concept of Passport.js and its strategies.
  • Implementing a Local Strategy for username/password authentication.
  • Implementing a JWT Strategy for token-based authentication.
  • Using AuthGuards to protect your API routes with these strategies.

Passport.js provides a powerful and flexible foundation for building robust authentication flows!

เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
22
บทเรียน
88

คำถามที่พบบ่อย

บทเรียน “การผสานรวม Passport.js” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การผสานรวม Passport.js” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack (App Router + Server Actions) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack (App Router + Server Actions) มีบทเรียนทั้งหมด 6 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวม Passport.js”

เรียนรู้การผสานรวมกลยุทธ์ของ Passport.js เช่น Local และ JWT เพื่อสร้างกระบวนการยืนยันตัวตนที่ยืดหยุ่นและทนทาน คุณปฏิบัติ Next.js 15 Fullstack (App Router + Server Actions) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack (App Router + Server Actions) หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack (App Router + Server Actions) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 6 จากทั้งหมด 6 บทเรียน

บทเรียน “การผสานรวม Passport.js” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack (App Router + Server Actions) นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack (App Router + Server Actions) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การผสาน NextAuth.js
  2. การใช้งานกลยุทธ์ JWT
  3. การปกป้องเส้นทางและข้อมูล
  4. การ์ดและบทบาท
  5. กลยุทธ์การยืนยันตัวตนแบบกำหนดเอง
  6. การผสานรวม Passport.js
← กลับไปที่ Next.js 15 Fullstack (App Router + Server Actions)