0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

Passport.js 集成

学习集成 Passport.js 策略,例如本地策略和 JWT 策略,以实现灵活而健壮的身份验证流程。

Passport.js 集成 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 6 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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!

常见问题解答

「Passport.js 集成」课时是免费的吗?

是的 — 「Passport.js 集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 6 节课。

「Passport.js 集成」这节课中我会学到什么?

学习集成 Passport.js 策略,例如本地策略和 JWT 策略,以实现灵活而健壮的身份验证流程。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 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)