Passport.js 통합
유연하고 견고한 인증 흐름을 위해 Local 및 JWT와 같은 Passport.js 전략을 통합하는 방법을 학습합니다.
Passport.js 통합은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 6개 중 6번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 integrationpassport: Core Passport.js librarypassport-local: For username/password authenticationpassport-jwt: For JSON Web Token authentication
npm install @nestjs/passport passport passport-local passport-jwtPassport 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 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 6개의 강의가 포함되어 있습니다.
“Passport.js 통합”에서 뭘 배우나요?
유연하고 견고한 인증 흐름을 위해 Local 및 JWT와 같은 Passport.js 전략을 통합하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 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 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- NextAuth.js 통합
- JWT 전략 구현
- 경로 및 데이터 보호
- 가드와 역할
- 사용자 지정 인증 전략
- Passport.js 통합