Spring Security 6 & JWT Authentication · บทเรียน

การลงลายมือชื่อและตรวจสอบ JWT

เรียนรู้หลักการเข้ารหัสเบื้องหลังการลงลายมือชื่อ JWT และวิธีตรวจสอบความถูกต้องกับความน่าเชื่อถือของโทเค็น

บทเรียน 3 จาก 411 ขั้นตอน

การลงลายมือชื่อและตรวจสอบ JWT เป็นบทเรียน Spring Security 6 & JWT Authentication ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Security 6 & JWT Authentication และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Security 6 & JWT Authentication มีบทเรียนทั้งหมด 4 บทเรียน

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

What is JWT Signing?

JSON Web Tokens (JWTs) are powerful, but how do we trust them? Signing is the answer! It's a cryptographic process that ensures a token hasn't been tampered with and comes from a trusted source.

  • Integrity: Confirms the token's content hasn't been changed since it was issued.
  • Authenticity: Verifies the token was issued by the expected sender.

Without a signature, anyone could create or alter a JWT!

Keys to Security: The Secret

For symmetric signing algorithms like HMAC (e.g., HS256), a single secret key is used. This key is known only to the issuer and the intended verifier(s).

  • The secret key is a string of bytes, crucial for both signing and verifying.
  • It must be kept highly confidential.
  • If the secret key is compromised, your JWTs are no longer secure!

Algorithms: HS256 & RS256

JWTs use cryptographic algorithms to create the signature. The algorithm type is specified in the token's header.

  • HS256 (HMAC SHA-256): A symmetric algorithm. Uses a single secret key for both signing and verification. Simpler to implement.
  • RS256 (RSA SHA-256): An asymmetric algorithm. Uses a private key for signing and a public key for verification. More complex but better for distributed systems.

We'll focus on HS256 for our examples due to its simplicity.

Building the Signature (HS256)

The signature is created by combining the Base64Url encoded header, the Base64Url encoded payload, and your secret key using the chosen algorithm.

  1. Take the Base64Url encoded header.
  2. Take the Base64Url encoded payload.
  3. Concatenate them with a dot: encodedHeader + "." + encodedPayload.
  4. Hash this combined string using HMAC SHA-256 with your secret key.
  5. Base64Url encode the resulting hash to get the final signature.

Result: encodedHeader.encodedPayload.signature

Code: Generating HS256 Signature

Here's a Java example to generate an HS256 signature for a JWT. Notice how the secret key is essential for the hashing process.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class JwtSigner {
    public static void main(String[] args) throws Exception {
        String encodedHeader = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"; // {"alg":"HS256","typ":"JWT"}
        String encodedPayload = "eyJpZCI6MSwicm9sZSI6InVzZXIifQ";     // {"id":1,"role":"user"}
        String secret = "coddykit-secret-lesson-key-1234567890";

        String dataToSign = encodedHeader + "." + encodedPayload;

        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
        hmacSha256.init(secretKey);

        byte[] signatureBytes = hmacSha256.doFinal(dataToSign.getBytes("UTF-8"));
        String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(signatureBytes);

        System.out.println("Data to Sign: " + dataToSign);
        System.out.println("Generated Signature: " + encodedSignature);
        System.out.println("Full JWT: " + dataToSign + "." + encodedSignature);
    }
}

Verifying a JWT's Signature

Verification is the reverse process of signing. When you receive a JWT, you need to ensure its signature is valid.

  1. Separate the received JWT into its three parts: header, payload, and signature.
  2. Reconstruct the "data to sign" string: encodedHeader + "." + encodedPayload.
  3. Using the same secret key and algorithm, calculate a new signature from this data.
  4. Compare your newly calculated signature with the signature provided in the JWT.

If they match, the token is valid and untampered! If not, it's invalid.

Secure Key Management

The security of your JWTs critically depends on how well you manage your signing keys. A compromised key invalidates all your security efforts!

  • Confidentiality: Keep secret keys private. Never hardcode them in client-side code.
  • Rotation: Regularly change your keys to limit the impact of a potential compromise.
  • Strength: Use strong, random, and sufficiently long keys.
  • Store keys in secure environments, like environment variables or dedicated key management services.

Code: Verifying HS256 Signature

This example demonstrates how to verify a JWT's signature. We use the same secret key to recalculate the signature and compare it against the one in the token.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class JwtVerifier {
    public static void main(String[] args) throws Exception {
        String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwicm9sZSI6InVzZXIifQ.qS6pQ_6_q-P_5_o-O_6_n-N_7_m-M_8_l-L_9_k-K_0_j-J_1_i-I_2_h-H_3_g-G_4_f-F_5_e-E_6_d-D_7_c-C_8_b-B_9_a-A"; 
        String secret = "coddykit-secret-lesson-key-1234567890";

        String[] parts = jwt.split("\\.");
        String encodedHeader = parts[0];
        String encodedPayload = parts[1];
        String receivedSignature = parts[2];

        String dataToSign = encodedHeader + "." + encodedPayload;

        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
        hmacSha256.init(secretKey);

        byte[] calculatedSignatureBytes = hmacSha256.doFinal(dataToSign.getBytes("UTF-8"));
        String calculatedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(calculatedSignatureBytes);

        if (calculatedSignature.equals(receivedSignature)) {
            System.out.println("Signature is VALID!");
        } else {
            System.out.println("Signature is INVALID!");
            System.out.println("Received: " + receivedSignature);
            System.out.println("Calculated: " + calculatedSignature);
        }
    }
}

Symmetric vs. Asymmetric Signing

While HS256 (HMAC SHA-256) uses a shared secret, RS256 (RSA SHA-256) and ES256 (ECDSA SHA-256) use key pairs.

  • Symmetric (e.g., HS256): Same key for signing and verifying. Best for single-service applications or when the verifier is also the issuer.
  • Asymmetric (e.g., RS256, ES256): Private key for signing, public key for verifying. Ideal for distributed systems where multiple services need to verify tokens issued by a central authority. The public key can be shared widely without compromising security.

Quick Check: JWT Security

You've learned about JWT signing and verification. Let's test your understanding.

Recap: Secure JWTs

Great job! We've demystified how JWTs are secured through signing and verification.

  • Signing ensures a JWT's integrity and authenticity using a cryptographic algorithm and a secret key.
  • HS256 (HMAC SHA-256) is a symmetric algorithm using a single shared secret.
  • Verification involves recalculating the signature and comparing it to the received one.
  • Secure key management is paramount for JWT security.
  • Asymmetric algorithms like RS256 use key pairs for distributed verification.

Next up, we'll see how to integrate JWTs with Spring Security!

เริ่มต้นได้ฟรี

เรียนรู้ Java ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

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

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

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

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

เรียนรู้หลักการเข้ารหัสเบื้องหลังการลงลายมือชื่อ JWT และวิธีตรวจสอบความถูกต้องกับความน่าเชื่อถือของโทเค็น คุณปฏิบัติ Spring Security 6 & JWT Authentication ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Security 6 & JWT Authentication หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Security 6 & JWT Authentication บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

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

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

ฉันเขียนและรันโค้ดในบทเรียน Spring Security 6 & JWT Authentication นี้ได้ไหม

ได้ บทเรียน Spring Security 6 & JWT Authentication ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. ทำความเข้าใจ JSON Web Tokens
  2. โครงสร้างและข้อมูลอ้างสิทธิ์ของ JWT
  3. การลงลายมือชื่อและตรวจสอบ JWT
  4. กฎการหมดอายุและการตรวจสอบ JWT
← กลับไปที่ Spring Security 6 & JWT Authentication