AI Powered SaaS: Stripe + Auth + Billing + Deploy · レッスン

保護されたルートとミドルウェア

JWTを検証し、認証済みユーザーだけにアクセスを制限するミドルウェアを実装して、APIエンドポイントを保護する方法を学びます。

レッスン 3/411 ステップ

「保護されたルートとミドルウェア」はCoddyKit上の無料AI Powered SaaS: Stripe + Auth + Billing + Deployレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Powered SaaS: Stripe + Auth + Billing + Deploy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Powered SaaS: Stripe + Auth + Billing + Deployコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Securing Your Digital Doors

Imagine a VIP lounge. Not everyone can just walk in, right? Some areas of your application, like a user's profile or settings, are just like that VIP lounge. They contain sensitive data or allow critical actions.

These are called protected routes. They ensure that only authenticated and authorized users can access specific resources or perform certain operations. Without them, anyone could potentially view or alter sensitive user data.

Your API's Security Guard: Middleware

How do we protect these routes? That's where middleware comes in!

Middleware functions are like security guards that stand between a client's request and your server's route handler. They can inspect, modify, or even terminate requests before they reach their final destination.

Think of it as a checkpoint. Every request must pass through, and the middleware decides if it's allowed to proceed.

The Middleware Flow

Middleware fits right into the request-response cycle. When a request hits your server, it first goes through any configured middleware functions, one by one.

  • Intercept: Middleware intercepts the incoming request.
  • Process: It performs its logic (e.g., logging, authentication, data parsing).
  • Pass On: If all checks pass, it uses a special function (often called next()) to pass control to the next middleware or the final route handler.
  • Block: If a check fails (e.g., unauthorized), it can send a response directly and stop the request from going further.

First Middleware Steps

Let's see a basic example. Here's a simple Node.js Express middleware that logs requests. Notice the next() function – it's crucial for passing control.

Try running this example and see the console output!

const express = require('express');
const app = express();

// Define our simple logging middleware
function requestLogger(req, res, next) {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next(); // Crucial: pass control to the next handler
}

// Apply the middleware to all incoming requests
app.use(requestLogger);

// Define a simple route
app.get('/', (req, res) => {
  res.send('Hello from the server!');
});

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Locating the Authentication Token

For authentication, our middleware needs to find the JSON Web Token (JWT) sent by the client. JWTs are typically sent in the Authorization header of an HTTP request, using the Bearer scheme.

It looks like this: Authorization: Bearer YOUR_JWT_TOKEN_HERE

Our middleware's first job is to extract this token from the request headers.

Checking the Token's Authenticity

Once we have the token, we need to verify it. This involves checking its signature using the secret key that was used to sign it. If the token's signature is valid, we know it hasn't been tampered with.

Here's how you might verify a token using a common library (like jsonwebtoken in Node.js). For this example, we'll simulate a valid token.

const jwt = require('jsonwebtoken'); // npm install jsonwebtoken

const SECRET_KEY = 'my_super_secret_key'; // Keep this secure in real apps!
const mockPayload = { id: 'user123', username: 'alice' };

// 1. Create a mock token (what a login endpoint would generate)
const mockToken = jwt.sign(mockPayload, SECRET_KEY, { expiresIn: '1h' });
console.log('Generated Token:', mockToken);

// 2. Verify the token in our middleware
jwt.verify(mockToken, SECRET_KEY, (err, user) => {
  if (err) {
    console.log('Token verification failed:', err.message);
  } else {
    console.log('Token is valid! User:', user);
    // In a real middleware, you'd attach 'user' to req object
  }
});

Denying Access

What if the token is missing or invalid? Our middleware must respond with an error and prevent the request from reaching the protected route.

  • Missing Token: If no Authorization header or token is found, return a 401 Unauthorized status.
  • Invalid Token: If the token exists but is malformed, expired, or has an invalid signature, return a 403 Forbidden status.

This is crucial for security!

Making User Info Available

If the JWT is successfully verified, it contains a payload with user information (like user ID, username, etc.). Our middleware can extract this data and attach it to the request object.

This means that any subsequent route handler for a protected route will have direct access to the authenticated user's details without needing to re-parse the token.

Example: req.user = decodedPayload;

Full Authentication Middleware

Here's a complete Node.js Express setup with our authentication middleware. Notice how authenticateToken is applied to the /profile route, making it protected.

Run this. Try accessing /profile without a token, then with a valid token (from Scene 6).

const express = require('express');
const jwt = require('jsonwebtoken'); // npm install jsonwebtoken
const app = express();

const SECRET_KEY = 'my_super_secret_key'; // Use env vars in production!

// Middleware to authenticate JWT
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (token == null) {
    return res.status(401).send('Access Denied: No token provided');
  }

  jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) {
      return res.status(403).send('Access Denied: Invalid token');
    }
    req.user = user; // Attach user payload to request
    next(); // Pass to the next handler/route
  });
}

// An unprotected public route
app.get('/public', (req, res) => {
  res.send('This is a public route. No authentication needed.');
});

// A protected route
app.get('/profile', authenticateToken, (req, res) => {
  res.json({
    message: `Welcome to your profile, ${req.user.username}!`, 
    userId: req.user.id
  });
});

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Middleware Checkpoint

Consider an authentication middleware designed to protect a route. What is the primary purpose of calling next() within the middleware function?

Lesson Summary: Secure Routes

Great job! In this lesson, you've learned to secure your API endpoints with protected routes.

  • We explored how middleware acts as an intermediary, inspecting requests before they reach sensitive parts of your application.
  • You saw how to implement an authentication middleware to extract and validate JWTs from incoming requests.
  • We covered handling missing or invalid tokens by sending appropriate error responses (401, 403).
  • Finally, you learned how to attach authenticated user data to the request object and apply this middleware to specific routes, ensuring only authorized users can access them.

Your API is now much more secure!

無料で開始

AI チューターと学ぶ AI Powered SaaS: Stripe + Auth + Billing + Deploy — 無料

ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。

コース
12
レッスン
48

よくある質問

「保護されたルートとミドルウェア」レッスンは無料ですか?

はい。「保護されたルートとミドルウェア」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Powered SaaS: Stripe + Auth + Billing + Deployコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Powered SaaS: Stripe + Auth + Billing + Deployコースには全4レッスンが含まれています。

「保護されたルートとミドルウェア」で何を学びますか?

JWTを検証し、認証済みユーザーだけにアクセスを制限するミドルウェアを実装して、APIエンドポイントを保護する方法を学びます。 ブラウザで直接実行するハンズオンコードでAI Powered SaaS: Stripe + Auth + Billing + Deployを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Powered SaaS: Stripe + Auth + Billing + Deployを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Powered SaaS: Stripe + Auth + Billing + Deployは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「保護されたルートとミドルウェア」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンでコードを書いて実行できますか?

はい。すべてのAI Powered SaaS: Stripe + Auth + Billing + Deployレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ユーザー登録とハッシュ化
  2. ログインとJWTの生成
  3. 保護されたルートとミドルウェア
  4. パスワードリセットとメール認証
← AI Powered SaaS: Stripe + Auth + Billing + Deployに戻る