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

แนวทางการจัดเก็บโทเค็นอย่างปลอดภัย

ทำความเข้าใจแนวทางปฏิบัติที่ดีที่สุดในการจัดเก็บ JWT และโทเค็นรีเฟรชฝั่งไคลเอ็นต์ เพื่อป้องกันการโจมตีทั่วไป

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

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

Why Secure Token Storage Matters

When building secure applications with JWTs, where you store these tokens on the client-side is crucial. Improper storage can expose your users to various security risks.

This lesson explores the best practices for handling JWTs and refresh tokens in client environments like web browsers, ensuring your application remains robust against common attacks.

Client-Side Storage Options

Web browsers offer several ways to store data, each with different security implications for sensitive tokens:

  • LocalStorage: Stores data persistently across browser sessions.
  • SessionStorage: Stores data only for the duration of the browser session.
  • Cookies: Small pieces of data sent by the server and stored by the browser, sent back with subsequent requests.

Choosing the right option is key to token security.

LocalStorage & SessionStorage Risks

While convenient, LocalStorage and SessionStorage are generally not recommended for storing sensitive JWTs or refresh tokens.

They are vulnerable to Cross-Site Scripting (XSS) attacks. If a malicious script is injected into your page, it can easily access and steal any tokens stored here.

XSS: The Token Thief

Cross-Site Scripting (XSS) is a common web security vulnerability. It allows attackers to inject malicious client-side scripts into web pages viewed by other users.

These scripts can then:

  • Access and steal data from LocalStorage or SessionStorage.
  • Perform actions on behalf of the user.
  • Even hijack user sessions.

This is why tokens in these storages are at high risk.

Introducing HTTP-Only Cookies

For better protection against XSS, HTTP-Only cookies are a strong choice, especially for refresh tokens. An HTTP-Only cookie cannot be accessed by client-side JavaScript.

This means even if an XSS attack occurs, the malicious script cannot read or steal the cookie's content, significantly reducing the risk of token compromise.

Essential Cookie Security Flags

Beyond HTTP-Only, two other flags are critical for cookie security:

  • Secure: Ensures the cookie is only sent over HTTPS connections. Never use sensitive cookies without this flag in production.
  • SameSite: Prevents the browser from sending the cookie with cross-site requests, providing robust protection against Cross-Site Request Forgery (CSRF) attacks.

Always use Secure and a suitable SameSite policy (e.g., Lax or Strict).

Setting a Secure Cookie in Spring

Here's how a Spring Boot backend can set an HTTP-Only, Secure, and SameSite cookie. This cookie would typically hold a refresh token.

The browser automatically handles sending this cookie with subsequent requests to your domain, while JavaScript cannot access it.

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CookieController {

    @GetMapping("/set-secure-cookie")
    public String setSecureCookie(HttpServletResponse response) {
        Cookie refreshTokenCookie = new Cookie("refreshToken", "your_long_refresh_token");
        refreshTokenCookie.setHttpOnly(true); // JS cannot access
        refreshTokenCookie.setSecure(true);   // Only over HTTPS
        refreshTokenCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
        refreshTokenCookie.setPath("/");
        // Set SameSite to Lax or Strict for CSRF protection
        // Note: For Spring, SameSite often set via application properties
        // or a custom filter for older Servlet versions.
        // With modern Servlet API (e.g., Servlet 4+), can be set directly:
        // refreshTokenCookie.setAttribute("SameSite", "Lax");

        response.addCookie(refreshTokenCookie);
        return "Secure cookie set!";
    }

    public static void main(String[] args) {
        // This is a conceptual example for a Spring Controller.
        // A full Spring Boot app would run this via SpringApplication.run().
        // The main method here is just for completeness as per guidelines,
        // but this code needs a Spring context to fully execute.
        System.out.println("To run, integrate into a Spring Boot application.");
    }
}

Access Token Storage: In-Memory

Access tokens are typically short-lived. The most secure place for an access token on the client-side is often in-memory (e.g., a JavaScript variable).

This means the token is not written to persistent storage and is lost when the browser tab is closed or the page is refreshed. It minimizes exposure, as an XSS attack would only be able to steal the token while the user is actively on the compromised page.

The Combined Secure Strategy

A robust strategy combines the best of both worlds:

  • Access Token: Store in a JavaScript variable (in-memory). Send it in the Authorization header for API requests. It's short-lived.
  • Refresh Token: Store in an HTTP-Only, Secure, SameSite cookie. This token is used to obtain new access tokens when the current one expires. It's longer-lived and highly protected.

This approach balances usability with strong security against XSS and CSRF.

Check Your Knowledge

Which of the following are considered best practices for securely storing JWTs and refresh tokens on the client-side?

Recap: Secure Storage Principles

You've learned critical strategies for secure client-side token storage:

  • Avoid LocalStorage/SessionStorage for sensitive tokens due to XSS risks.
  • Use HTTP-Only, Secure, SameSite cookies for refresh tokens to protect against XSS and CSRF.
  • Keep access tokens in-memory (JavaScript variables) as they are short-lived.

By following these practices, you significantly enhance the security posture of your JWT-based authentication system.

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

บทเรียน “แนวทางการจัดเก็บโทเค็นอย่างปลอดภัย” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “แนวทางการจัดเก็บโทเค็นอย่างปลอดภัย”

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

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

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

บทเรียน “แนวทางการจัดเก็บโทเค็นอย่างปลอดภัย” ใช้เวลานานแค่ไหน

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

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

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

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

  1. การนำโทเค็นรีเฟรชไปใช้งาน
  2. กลยุทธ์การเพิกถอนโทเค็น JWT
  3. แนวทางการจัดเก็บโทเค็นอย่างปลอดภัย
  4. การหมุนเวียนคีย์ลายเซ็นและการจัดการคีย์
← กลับไปที่ Spring Security 6 & JWT Authentication