0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 강의

JWT 전략 구현

상태를 저장하지 않는 인증을 위해 JSON 웹 토큰(JWT)을 통합하고 토큰 생성과 검증을 다룹니다.

JWT 전략 구현은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 6개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is a JSON Web Token (JWT)?

Welcome! In this lesson, we'll dive into JSON Web Tokens (JWTs), a popular method for securing APIs.

  • JWTs are compact, URL-safe means of representing claims to be transferred between two parties.
  • They are often used for stateless authentication, meaning the server doesn't need to store session information.
  • This makes APIs more scalable and easier to manage, especially in distributed systems.

JWT's Three Main Parts

A JWT is essentially a long string, but it's structured into three distinct parts, separated by dots (.):

  1. Header: Contains metadata about the token itself (e.g., type of token, signing algorithm).
  2. Payload: Contains the actual claims or data about the user and additional properties.
  3. Signature: Used to verify the token's integrity and authenticity.

Each part is Base64Url-encoded.

Header & Payload in Detail

Let's look closer at the first two parts:

  • Header: Typically contains two fields:"alg" (algorithm, e.g., HS256) and "typ" (type, which is JWT).
  • Payload: This is where you put your data, known as 'claims'. Common claims include:
    • sub (subject): Usually the user ID.
    • exp (expiration time): When the token expires.
    • iat (issued at): When the token was issued.
    • Custom claims: Any other data you need, like "username" or "role".

The Cryptographic Signature

The signature is the crucial third part that ensures security:

  • It's created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header.
  • This combination is then cryptographically hashed.
  • Why is it important? If anyone tries to tamper with the header or payload, the signature verification will fail, indicating the token is invalid or has been altered.
  • The secret key must be kept confidential on the server side!

NestJS and JWTs

NestJS provides excellent support for integrating JWTs, leveraging the power of the jsonwebtoken library under the hood.

We'll primarily use the @nestjs/jwt package, which offers a JwtModule and JwtService to handle token generation and verification seamlessly within your application.

First, you'll need to install the package if you haven't already:

npm install @nestjs/jwt passport-jwt --save

Configuring the JwtModule

To use JWTs in NestJS, you need to import and configure the JwtModule in your application's module (e.g., AppModule or a dedicated AuthModule).

The most important option is the secret key, which is used to sign and verify tokens.

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';

@Module({
  imports: [
    JwtModule.register({
      secret: 'yourSuperSecretKey',
      signOptions: { expiresIn: '60s' }, // e.g., 60s, 7d, 1h
    }),
  ],
  // ... other providers, controllers
})
export class AppModule {}

Generating a JWT in NestJS

Once JwtModule is configured, you can inject JwtService into your services to generate (sign) new tokens. The sign() method takes a payload (usually an object) and creates the JWT string.

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  async signIn(user: any): Promise<string> {
    const payload = { username: user.username, sub: user.userId };
    return this.jwtService.sign(payload); // Signs with configured secret & options
  }
}

Code Demo: Token Generation

Let's see how a token is generated conceptually. This example uses the underlying jsonwebtoken library directly, similar to how NestJS does it.

Run this code to see a JWT being created:

// To run this, install 'jsonwebtoken':
// npm install jsonwebtoken --save

const jwt = require('jsonwebtoken');

const payload = {
  sub: 'user123',
  username: 'coder_kit'
};

const secret = 'mySuperSecretKey123'; // Keep this secret safe!

// Sign the token with an expiration of 1 hour
const token = jwt.sign(payload, secret, { expiresIn: '1h' });

console.log('--- Generated JWT ---');
console.log(token);
console.log('\nThis token is valid for 1 hour.');

Verifying a JWT in NestJS

When a client sends a JWT, your server needs to verify it. The JwtService.verify() method checks several things:

  • Is the signature valid (i.e., was it signed with our secret)?
  • Has the token expired?
  • Are there any other validation rules specified?

If valid, it returns the decoded payload. If invalid, it throws an error.

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private jwtService: JwtService) {}

  async verifyToken(token: string): Promise<any> {
    try {
      const payload = this.jwtService.verify(token);
      return payload; // Token is valid, return its data
    } catch (error) {
      // Token is invalid or expired
      throw new Error('Invalid or expired token');
    }
  }
}

Code Demo: Token Verification

Here's how token verification works. You can use the token generated in the previous step (or the example provided) and see it being verified.

Remember, the secret used for verification MUST be the same one used for signing!

// To run this, install 'jsonwebtoken':
// npm install jsonwebtoken --save

const jwt = require('jsonwebtoken');

// IMPORTANT: Replace with a REAL token you generated,
// or use this example token (signed with 'mySuperSecretKey123')
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwidXNlcm5hbWUiOiJjb2Rlcl9raXQiLCJpYXQiOjE3MDcwOTMyMTMsImV4cCI6MTcwNzE3OTYxM30.4i-J_q_e_x_a_m_p_l_e_s_i_g_n_a_t_u_r_e_f_o_r_d_e_m_o'; 

const secret = 'mySuperSecretKey123'; // Must match the signing secret!

console.log('--- Attempting to Verify Token ---');
try {
  const decoded = jwt.verify(testToken, secret);
  console.log('Token is VALID!');
  console.log('Decoded Payload:');
  console.log(decoded);
} catch (error) {
  console.error('Token is INVALID or EXPIRED!');
  console.error('Error:', error.message);
}

JWT Concept Check

You've learned about the three main parts of a JWT. Which of the following components is primarily responsible for ensuring the token's integrity (that it hasn't been tampered with)?

Recap: JWT Essentials

Great job! You've covered the fundamentals of JWTs:

  • What they are: Compact, stateless tokens for authentication.
  • Their structure: Header, Payload, and Signature.
  • Key concepts: How the signature protects integrity and the role of the secret key.
  • NestJS integration: Using @nestjs/jwt to configure, sign, and verify tokens.

Next, we'll explore how to protect routes using Guards and implement role-based access control!

자주 묻는 질문

“JWT 전략 구현” 강의는 무료인가요?

네 — “JWT 전략 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 6개의 강의가 포함되어 있습니다.

“JWT 전략 구현”에서 뭘 배우나요?

상태를 저장하지 않는 인증을 위해 JSON 웹 토큰(JWT)을 통합하고 토큰 생성과 검증을 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 2번째 강의입니다.

“JWT 전략 구현” 강의는 얼마나 걸리나요?

대부분의 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)(으)로 돌아가기