0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

การลงลายมือชื่อและตรวจสอบ JWT ด้วย python-jose

เข้ารหัสและถอดรหัส JWT พร้อมตรวจสอบข้อมูลอ้างสิทธิ์ อายุหมดอายุ และผู้รับเป้าหมาย พร้อมปกป้องเส้นทางจากการแก้ไขปลอมแปลง

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

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

Why JWTs for Stateless Auth

A JWT (JSON Web Token) is a compact, signed token that carries claims about a user. Once your FastAPI app issues a JWT at login, the client sends it back on every request, and you verify it without touching a session store.

  • Stateless — the server doesn't store sessions; the signature proves authenticity.
  • Tamper-evident — any change to the payload invalidates the signature.
  • Portable — the same token works across services that share the secret or public key.

In this lesson we use python-jose to encode (sign) and decode (verify) tokens with claims, expiry, and audience validation.

Anatomy of a JWT

A JWT has three Base64URL parts joined by dots: header.payload.signature.

  • Header — algorithm and token type, e.g. {"alg": "HS256", "typ": "JWT"}.
  • Payload — the claims (data) such as sub, exp, aud.
  • Signature — keyed hash of header + payload, proving the token wasn't altered.

Standard (registered) claims you'll use most: sub (subject/user id), exp (expiry), iat (issued at), aud (audience), iss (issuer). The payload is only encoded, not encrypted, so never put secrets like passwords inside it.

Installing and Importing python-jose

Install python-jose with its cryptography backend so RSA and EC algorithms work too:

  • pip install "python-jose[cryptography]"

The two functions you'll use constantly live in jose.jwt: jwt.encode(...) to sign and jwt.decode(...) to verify. Errors are raised as subclasses of JWTError, which lets you catch all token problems cleanly.

from jose import jwt
from jose.exceptions import JWTError, ExpiredSignatureError, JWTClaimsError

print("encode:", callable(jwt.encode))
print("decode:", callable(jwt.decode))
print("base error:", issubclass(ExpiredSignatureError, JWTError))

Encoding Your First Token

To sign a token, pass a claims dict, a secret key, and an algorithm. For symmetric signing we use HS256, where the same secret signs and verifies.

  • Put the user id in sub — it must be a string.
  • Keep the secret long and random; load it from an environment variable in real apps.

The result is a single URL-safe string you can hand back to the client.

from jose import jwt

SECRET = "a-very-long-random-secret-string-change-me"
ALGO = "HS256"

claims = {"sub": "user-42", "role": "admin"}
token = jwt.encode(claims, SECRET, algorithm=ALGO)
print(token[:40] + "...")
print("dot count:", token.count("."))

Decoding and Verifying

jwt.decode does two things at once: it checks the signature and returns the claims. If the signature is wrong, it raises a JWTError instead of returning data.

  • Pass the same algorithm(s) you signed with via algorithms=[...] — never trust the algorithm advertised in the token header alone.
  • A successful decode means the token is authentic and untampered.

The example below signs a token, then verifies it and reads the claims back out.

from jose import jwt

SECRET = "a-very-long-random-secret-string-change-me"

token = jwt.encode({"sub": "user-42", "role": "admin"}, SECRET, algorithm="HS256")
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
print("sub:", payload["sub"])
print("role:", payload["role"])

Detecting Tampering

This is the whole point of signing. If an attacker flips a single character in the payload, verification fails because the signature no longer matches.

  • Catch JWTError to reject the request with 401 Unauthorized.
  • Never decode with verify_signature=False in production — that skips the security check entirely.

The snippet corrupts a token and shows the verification raising an error.

from jose import jwt
from jose.exceptions import JWTError

SECRET = "a-very-long-random-secret-string-change-me"
token = jwt.encode({"sub": "user-42"}, SECRET, algorithm="HS256")

# Tamper: change the last character of the token
tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
try:
    jwt.decode(tampered, SECRET, algorithms=["HS256"])
    print("accepted (BAD)")
except JWTError as e:
    print("rejected tampered token:", type(e).__name__)

Adding Expiry with exp

Tokens should be short-lived. The exp claim is a Unix timestamp (seconds since epoch, UTC). python-jose automatically rejects expired tokens at decode time, raising ExpiredSignatureError.

  • Compute expiry with timezone-aware UTC: datetime.now(timezone.utc) + timedelta(...).
  • Access tokens are typically 15-30 minutes; refresh tokens last longer.

You can pass a datetime or an int for exp — jose converts datetimes to timestamps for you.

from datetime import datetime, timedelta, timezone
from jose import jwt

SECRET = "a-very-long-random-secret-string-change-me"
expire = datetime.now(timezone.utc) + timedelta(minutes=30)
claims = {"sub": "user-42", "exp": expire}

token = jwt.encode(claims, SECRET, algorithm="HS256")
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
print("exp claim (unix):", payload["exp"])
print("valid for ~30 min")

Handling Expired Tokens

When a token's exp is in the past, jwt.decode raises ExpiredSignatureError (a subclass of JWTError). Handle it separately so you can tell the client to refresh instead of re-login.

  • Catch ExpiredSignatureError first, then a generic JWTError.
  • jose applies a small default leeway for clock skew; you can tune it with options.

Here we issue an already-expired token to prove the check fires.

from datetime import datetime, timedelta, timezone
from jose import jwt
from jose.exceptions import ExpiredSignatureError, JWTError

SECRET = "a-very-long-random-secret-string-change-me"
past = datetime.now(timezone.utc) - timedelta(minutes=5)
token = jwt.encode({"sub": "user-42", "exp": past}, SECRET, algorithm="HS256")

try:
    jwt.decode(token, SECRET, algorithms=["HS256"])
except ExpiredSignatureError:
    print("token expired -> ask client to refresh")
except JWTError:
    print("other token error")

Audience Validation with aud

The aud (audience) claim names who the token is for — e.g. your API. If you set it when encoding, you must pass the matching audience= when decoding, or jose raises JWTClaimsError.

  • Prevents a token minted for one service from being replayed against another.
  • If you omit audience= but the token has aud, validation fails — pass it explicitly.

The example signs with an audience and validates it on decode.

from jose import jwt
from jose.exceptions import JWTClaimsError

SECRET = "a-very-long-random-secret-string-change-me"
token = jwt.encode(
    {"sub": "user-42", "aud": "fastapi-bootcamp-api"},
    SECRET, algorithm="HS256",
)

payload = jwt.decode(token, SECRET, algorithms=["HS256"], audience="fastapi-bootcamp-api")
print("aud ok:", payload["aud"])

try:
    jwt.decode(token, SECRET, algorithms=["HS256"], audience="some-other-api")
except JWTClaimsError as e:
    print("wrong audience rejected:", type(e).__name__)

A Reusable Token Helper

In a real bootcamp project you wrap signing and verifying in small helpers so routes stay clean. Bundle the standard claims — sub, exp, iat, aud, iss — in one place.

  • create_access_token builds claims and signs.
  • verify_token decodes with all validations and returns the payload or raises.

This pure-Python module has no FastAPI imports, so it's easy to unit-test on its own.

from datetime import datetime, timedelta, timezone
from jose import jwt
from jose.exceptions import JWTError

SECRET = "a-very-long-random-secret-string-change-me"
ALGO, AUD, ISS = "HS256", "fastapi-bootcamp-api", "auth-service"

def create_access_token(sub, minutes=30):
    now = datetime.now(timezone.utc)
    claims = {"sub": sub, "iat": now, "exp": now + timedelta(minutes=minutes),
              "aud": AUD, "iss": ISS}
    return jwt.encode(claims, SECRET, algorithm=ALGO)

def verify_token(token):
    return jwt.decode(token, SECRET, algorithms=[ALGO], audience=AUD, issuer=ISS)

t = create_access_token("user-42")
print("verified sub:", verify_token(t)["sub"])

Protecting a FastAPI Route

In FastAPI you plug verification into a dependency. OAuth2PasswordBearer pulls the token from the Authorization: Bearer ... header, then your dependency verifies it and returns the current user — or raises HTTPException(401).

  • Any route that declares Depends(get_current_user) is now protected.
  • Convert JWTError into a proper 401 so tampered or expired tokens are rejected with the right status.

This is framework code, so it runs inside a server, not a standalone judge.

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from jose.exceptions import JWTError

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
SECRET, ALGO, AUD = "change-me", "HS256", "fastapi-bootcamp-api"

def get_current_user(token: str = Depends(oauth2_scheme)):
    creds_exc = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET, algorithms=[ALGO], audience=AUD)
    except JWTError:
        raise creds_exc
    user_id = payload.get("sub")
    if user_id is None:
        raise creds_exc
    return user_id

@app.get("/me")
def read_me(user_id: str = Depends(get_current_user)):
    return {"user_id": user_id}

Quick Check: Audience Validation

You sign tokens with aud="fastapi-bootcamp-api". A teammate's decode call sometimes throws JWTClaimsError even for freshly issued, untampered tokens. What is the most likely cause?

Recap: Signing and Verifying JWTs

You can now mint and validate JWTs with python-jose end to end:

  • Encode claims with jwt.encode(claims, secret, algorithm="HS256"); keep sub a string and the secret in an env var.
  • Decode with jwt.decode(token, secret, algorithms=[...]) and always pin the algorithm list.
  • Tampering breaks the signature and raises JWTError — reject with 401.
  • Expiry via exp auto-raises ExpiredSignatureError; handle it to trigger refresh.
  • Audience via aud must be matched with audience= on decode or you get JWTClaimsError.
  • In FastAPI, verify inside a Depends(get_current_user) dependency and convert errors into HTTPException(401).

Next up: refresh tokens and rotating signing keys.

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

บทเรียน “การลงลายมือชื่อและตรวจสอบ JWT ด้วย python-jose” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การลงลายมือชื่อและตรวจสอบ JWT ด้วย python-jose”

เข้ารหัสและถอดรหัส JWT พร้อมตรวจสอบข้อมูลอ้างสิทธิ์ อายุหมดอายุ และผู้รับเป้าหมาย พร้อมปกป้องเส้นทางจากการแก้ไขปลอมแปลง คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

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

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

บทเรียน “การลงลายมือชื่อและตรวจสอบ JWT ด้วย python-jose” ใช้เวลานานแค่ไหน

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

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

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

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

  1. โฟลว์รหัสผ่าน OAuth2 และการออกโทเค็น
  2. การลงลายมือชื่อและตรวจสอบ JWT ด้วย python-jose
  3. โทเค็นรีเฟรชและการหมุนเวียนโทเค็น
  4. การอนุญาตตามขอบเขตและตัวป้องกันบทบาท
← กลับไปที่ FastAPI Backend Development Bootcamp