ความปลอดภัยโดยใช้ JWT
นำการยืนยันตัวตนโดยใช้โทเคนไปใช้ด้วย JSON Web Tokens (JWT) สำหรับ API แบบไร้สถานะ
ความปลอดภัยโดยใช้ JWT เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Intro to JWT-Based Security
Welcome to the final lesson on Spring Security! Today, we'll explore JSON Web Tokens (JWTs), a popular method for securing stateless APIs.
Unlike traditional session-based authentication, JWTs allow the server to remain stateless, making them ideal for microservices and mobile applications.
What is a JWT?
A JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object.
- Compact: Small size, can be sent through URL, POST parameter, or inside an HTTP header.
- Self-contained: Contains all necessary information about the user, avoiding database lookups for every request.
Anatomy of a JWT
A JWT consists of three parts, separated by dots (.):
- Header
- Payload
- Signature
It typically looks like: xxxxx.yyyyy.zzzzz
The Header: Algorithm & Type
The Header usually consists of two parts: the type of the token (which is JWT) and the signing algorithm being used (e.g., HS256 or RS256).
This JSON is then Base64Url-encoded to form the first part of the JWT.
{"alg":"HS256","typ":"JWT"}The Payload: Claims
The Payload contains the 'claims' – statements about an entity (typically, the user) and additional data. There are three types of claims:
- Registered claims: Standard, non-mandatory claims (e.g.,
issfor issuer,expfor expiration,subfor subject). - Public claims: Defined by users, require collision-resistant names.
- Private claims: Custom claims agreed upon by sender and receiver.
The Signature: Trust & Integrity
The Signature is created by taking the encoded header, the encoded payload, a secret key, and the algorithm specified in the header. It ensures the token hasn't been tampered with.
If someone changes the header or payload, the signature verification will fail, making the token invalid. The secret key must be kept confidential!
Generating JWT Parts (Code)
Let's see how the header and payload are Base64Url-encoded. The signature would then be computed using these encoded parts and a secret.
import java.util.Base64;
public class JwtPartsDemo {
public static void main(String[] args) {
String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
String payloadJson = "{\"sub\":\"coddyUser\",\"iat\":1678886400,\"exp\":1678890000}";
String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(headerJson.getBytes());
String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payloadJson.getBytes());
System.out.println("Encoded Header: " + encodedHeader);
System.out.println("Encoded Payload: " + encodedPayload);
System.out.println("\nJWT format: EncodedHeader.EncodedPayload.Signature");
}
}JWT Flow in Spring Security
When a user successfully authenticates (e.g., logs in with username/password), the server:
- Generates a JWT.
- Sends the JWT back to the client.
For subsequent requests, the client:
- Stores the JWT (e.g., in local storage).
- Attaches the JWT in the
Authorizationheader (e.g.,Bearer YOUR_TOKEN).
The server then intercepts and validates this token for each protected request.
Validating JWTs (Code Concept)
A custom filter in Spring Security would extract the token, decode its parts, and then critically, verify the signature and validate claims like expiration.
import java.util.Base64;
public class JwtValidationDemo {
public static void main(String[] args) {
// A simplified example token (signature part is placeholder)
String jwtToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb2RkeVVzZXIiLCJpYXQiOjE2Nzg4ODY0MDAsImV4cCI6MTY3ODg5MDAwMH0.SIGNATURE_PLACEHOLDER";
String[] parts = jwtToken.split("\\.");
if (parts.length == 3) {
String decodedHeader = new String(Base64.getUrlDecoder().decode(parts[0]));
String decodedPayload = new String(Base64.getUrlDecoder().decode(parts[1]));
System.out.println("Decoded Header: " + decodedHeader);
System.out.println("Decoded Payload: " + decodedPayload);
// In a real application, you would:
// 1. Verify the 'SIGNATURE_PLACEHOLDER' using the secret key.
// 2. Parse 'decodedPayload' JSON to check claims like 'exp' (expiration).
if (decodedPayload.contains("\"sub\":\"coddyUser\"")) {
System.out.println("Payload contains expected subject 'coddyUser'.");
}
} else {
System.out.println("Invalid JWT format.");
}
}
}Quick Check: JWT Parts
Based on what we've learned, which of the following are standard parts of a JSON Web Token (JWT) that are transmitted?
Recap: JWT-Based Security
In this lesson, we explored JWT-based security, understanding its three key parts: Header, Payload, and Signature.
We learned how JWTs enable stateless authentication, making them highly scalable and suitable for modern APIs and mobile applications. You also saw conceptual code examples for generating and validating JWTs.
This concludes our Spring Security course! You've learned to secure applications from basic authentication to advanced token-based systems.
คำถามที่พบบ่อย
บทเรียน “ความปลอดภัยโดยใช้ JWT” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ความปลอดภัยโดยใช้ JWT” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ความปลอดภัยโดยใช้ JWT”
นำการยืนยันตัวตนโดยใช้โทเคนไปใช้ด้วย JSON Web Tokens (JWT) สำหรับ API แบบไร้สถานะ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “ความปลอดภัยโดยใช้ JWT” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พื้นฐาน Spring Security
- การยืนยันตัวตนและการอนุญาตสิทธิ์
- ความปลอดภัยโดยใช้ JWT
- การผสานรวม OAuth2 และการเข้าสู่ระบบด้วยบัญชีโซเชียล