0Pricing
Node.js Backend Development Bootcamp · บทเรียน

การสร้างและตรวจสอบโทเค็น JWT

ทำความเข้าใจโทเค็นเว็บ JSON (JWT) และใช้งานการสร้างกับการตรวจสอบโทเค็นเพื่อเข้าถึง API อย่างปลอดภัย

การสร้างและตรวจสอบโทเค็น JWT เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 6 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 6 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to JWT: What & Why

Welcome! In this lesson, we'll dive into JSON Web Tokens (JWTs), a popular way to secure APIs.

A JWT is a compact, URL-safe means of representing claims to be transferred between two parties. Think of it as a digital ID card for your API.

Why Use JWTs for APIs?

JWTs offer several advantages for modern web and mobile APIs:

  • Statelessness: The server doesn't need to store session information. Each request carries the user's authentication details.
  • Scalability: Easier to scale applications horizontally as there's no shared session state across servers.
  • Security: If implemented correctly, JWTs provide a secure way to verify user identity and prevent tampering.

JWT Structure: Three Parts

A JWT is a string made of three parts, separated by dots (.). Each part is Base64Url-encoded:

HEADER.PAYLOAD.SIGNATURE

Let's break down what each of these parts means and why they're important for security.

The JWT Header

The Header typically consists of two parts:

  • alg (Algorithm): Specifies the cryptographic algorithm used for signing the token (e.g., HS256, RS256).
  • typ (Type): Indicates that the token is a JWT.

Example (Base64Url-decoded):

{"alg": "HS256", "typ": "JWT"}

The JWT Payload (Claims)

The Payload contains the "claims" – statements about an entity (like a user) and additional data.

Claims can be:

  • Registered: Standard fields like iss (issuer), exp (expiration time), sub (subject).
  • Public: Custom claims registered in the IANA JWT Registry.
  • Private: Custom claims agreed upon by the sender and receiver.

Example Payload:

{"sub": "user123", "name": "Alice", "exp": 1678886400}

The JWT Signature

The Signature is crucial for verifying the token's authenticity and integrity. It ensures the token hasn't been tampered with.

It's created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header, then signing them.

Formula (simplified):

HMACSHA256(encodedHeader + "." + encodedPayload, secretKey)

Python: Generating a JWT

Let's generate a JWT using Python's PyJWT library. First, install it: pip install PyJWT.

We define a payload with an expiration time and a secret key.

import jwt
import datetime

def main():
    SECRET_KEY = "your-super-secret-key"

    # Define payload with some claims
    payload = {
        "sub": "user123",
        "name": "Alice",
        "exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
        "iat": datetime.datetime.utcnow()
    }

    # Encode the token
    token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
    print(f"Generated JWT: {token}")

if __name__ == "__main__":
    main()

Secret Keys & Security

The SECRET_KEY used to sign and verify JWTs is extremely important. If this key is compromised, an attacker could forge valid tokens, granting unauthorized access.

  • Always use a strong, randomly generated key.
  • Never hardcode it in your application; use environment variables or a secure key management service.
  • Keep it absolutely confidential!

Python: Validating a JWT

To validate a JWT, you decode it using the same secret key and algorithm. PyJWT automatically verifies the signature and checks claims like expiration (`exp`).

import jwt
import datetime
import time

def main():
    SECRET_KEY = "your-super-secret-key"

    # Generate a token to validate (short expiry for demo)
    payload_gen = {
        "sub": "user123",
        "name": "Bob",
        "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=5), 
        "iat": datetime.datetime.utcnow()
    }
    token_to_validate = jwt.encode(payload_gen, SECRET_KEY, algorithm="HS256")
    print(f"Token to validate: {token_to_validate}\n")
    time.sleep(1) # Wait a bit for demonstration

    # Attempt to decode/validate it
    try:
        decoded_payload = jwt.decode(token_to_validate, SECRET_KEY, algorithms=["HS256"])
        print("Token is valid!")
        print(f"Decoded Payload: {decoded_payload}")
    except jwt.ExpiredSignatureError:
        print("Token has expired!")
    except jwt.InvalidTokenError:
        print("Invalid token (e.g., bad signature or format).")

if __name__ == "__main__":
    main()

JWT Best Practices

To keep your JWT implementation secure:

  • Set Expiration (exp): Always include an expiration claim to limit the window of a compromised token.
  • HTTPS: Always transmit JWTs over HTTPS to prevent eavesdropping.
  • Secure Storage: Store tokens securely on the client-side (e.g., HTTP-only cookies for web, secure storage for mobile).
  • Refresh Tokens: For long sessions, use short-lived access tokens and longer-lived refresh tokens.

Check Your Understanding

Review the components of a JWT. Which of the following parts is responsible for ensuring the token hasn't been tampered with?

Recap: JWT Essentials

In this lesson, we explored JSON Web Tokens (JWTs) for secure API authentication.

  • JWTs are compact, URL-safe tokens with a Header, Payload, and Signature.
  • The Header defines the token type and signing algorithm.
  • The Payload carries "claims" (data like user ID, roles, expiration).
  • The Signature verifies the token's integrity and authenticity.
  • We learned to generate and validate JWTs using Python's PyJWT library.
  • Always use strong, secret keys and set expiration times for security.

Next, we'll integrate JWTs into FastAPI using OAuth2 for a complete authentication flow!

คำถามที่พบบ่อย

บทเรียน “การสร้างและตรวจสอบโทเค็น JWT” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างและตรวจสอบโทเค็น JWT” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 6 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างและตรวจสอบโทเค็น JWT”

ทำความเข้าใจโทเค็นเว็บ JSON (JWT) และใช้งานการสร้างกับการตรวจสอบโทเค็นเพื่อเข้าถึง API อย่างปลอดภัย คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 6 บทเรียน

บทเรียน “การสร้างและตรวจสอบโทเค็น JWT” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การลงทะเบียนและเข้าสู่ระบบผู้ใช้
  2. การสร้างและตรวจสอบโทเค็น JWT
  3. JWT สำหรับการยืนยันตัวตนแบบไร้สถานะ
  4. การผสานรวมโฟลว์รหัสผ่าน OAuth2
  5. การควบคุมการเข้าถึงตามบทบาท
  6. การควบคุมการเข้าถึงตามบทบาท (RBAC)
← กลับไปที่ Node.js Backend Development Bootcamp