Next.js 15 Fullstack (App Router + Server Actions) · Aula

Integração com Passport.js

Aprenda a integrar estratégias do Passport.js, como Local e JWT, para obter fluxos de autenticação flexíveis e robustos.

Aula 6 de 611 etapas

Integração com Passport.js é uma aula grátis de Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit. Esta é a aula 6 de 6. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack (App Router + Server Actions), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 6 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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!

Grátis para começar

Aprenda TypeScript com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
22
Aulas
88

Perguntas Frequentes

A aula “Integração com Passport.js” é grátis?

Sim — o texto completo de “Integração com Passport.js” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack (App Router + Server Actions), atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 6 aulas no total.

O que vou aprender em “Integração com Passport.js”?

Aprenda a integrar estratégias do Passport.js, como Local e JWT, para obter fluxos de autenticação flexíveis e robustos. Você pratica Next.js 15 Fullstack (App Router + Server Actions) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Next.js 15 Fullstack (App Router + Server Actions)?

Nenhuma experiência prévia é necessária. Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 6 de 6.

Quanto tempo leva a aula “Integração com Passport.js”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Next.js 15 Fullstack (App Router + Server Actions)?

Sim. Cada aula de Next.js 15 Fullstack (App Router + Server Actions) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Integrando o NextAuth.js
  2. Implementação de Estratégias JWT
  3. Protegendo rotas e dados
  4. Guardas e Funções
  5. Estratégias de autenticação personalizadas
  6. Integração com Passport.js
← Voltar para Next.js 15 Fullstack (App Router + Server Actions)