JWT 토큰 생성 및 검증
JSON 웹 토큰(JWT)을 이해하고 안전한 API 접근을 위해 토큰의 생성과 검증을 구현합니다.
JWT 토큰 생성 및 검증은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 6개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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
PyJWTlibrary. - 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 토큰 생성 및 검증” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.
“JWT 토큰 생성 및 검증”에서 뭘 배우나요?
JSON 웹 토큰(JWT)을 이해하고 안전한 API 접근을 위해 토큰의 생성과 검증을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 2번째 강의입니다.
“JWT 토큰 생성 및 검증” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.