Spring Security 6 & JWT Authentication · 강의

JWT 블랙리스트 및 화이트리스트

토큰 블랙리스트 또는 화이트리스트를 관리하는 방법을 포함해 고급 토큰 폐기 기법을 자세히 살펴봅니다.

레슨 2/411개 단계

JWT 블랙리스트 및 화이트리스트은(는) CoddyKit의 무료 Spring Security 6 & JWT Authentication 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Security 6 & JWT Authentication 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Revoke JWTs?

JSON Web Tokens (JWTs) are powerful for authentication, but sometimes you need to invalidate them before their natural expiry. This process is called token revocation.

  • Compromised Token: If a token is stolen.
  • User Logout: To immediately end a user's session.
  • Password Change: To invalidate all old tokens.
  • Role Changes: To force re-authentication with new permissions.

The Stateless Challenge

JWTs are inherently stateless. Once issued, they contain all necessary information for validation and don't require the server to store session data.

This statelessness is a strength, but it makes direct server-side revocation tricky. The server typically doesn't hold a list of active tokens to simply 'turn off'.

Blacklisting Explained

Blacklisting is a common strategy to revoke JWTs. When a token needs to be invalidated, its unique identifier (often the JTI claim) is added to a 'blacklist' — a list of forbidden tokens.

  • Any token whose JTI is on this list is rejected, even if it's cryptographically valid and not expired.
  • This allows you to 'undo' a token's validity.

Implementing a Blacklist

The blacklist needs to be stored in a highly available, fast-access data store. Speed is crucial because every incoming request might need to check this list.

  • Redis: An excellent choice due to its in-memory nature and support for time-to-live (TTL) on entries, which can match token expiry.
  • Database: A simple table can work, but might be slower for high-volume checks.
  • Each entry typically stores the JWT's JTI and its original expiry time.

Simple Blacklist Service

Here's a basic interface for a service that manages a token blacklist. In a real application, this would interact with a database or a caching system like Redis.

public interface TokenBlacklistService {
  void blacklistToken(String jti, long expirySeconds);
  boolean isBlacklisted(String jti);
}

JWT Filter with Blacklist Check

When a request arrives, a security filter would first validate the JWT's signature and expiry. Then, it would check if the token's JTI is present on the blacklist before granting access.

Try running this example:

import java.util.HashSet;
import java.util.Set;

// A simplified in-memory blacklist for demonstration
class MockTokenBlacklistService {
    private Set<String> blacklistedJtis = new HashSet<>();

    public void blacklistToken(String jti, long expirySeconds) {
        System.out.println("Action: Blacklisting JTI " + jti);
        blacklistedJtis.add(jti);
        // In a real app, 'expirySeconds' would set a TTL on the blacklist entry
    }

    public boolean isBlacklisted(String jti) {
        boolean result = blacklistedJtis.contains(jti);
        System.out.println("Check: Is JTI " + jti + " blacklisted? " + result);
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        MockTokenBlacklistService blacklist = new MockTokenBlacklistService();

        String userTokenJti = "user-abc-123";
        String adminTokenJti = "admin-def-456";

        // Simulate an admin token being revoked after a security event
        blacklist.blacklistToken(adminTokenJti, 3600); // Token expires in 1 hour

        // Check access for different tokens
        System.out.println("\n--- Access Checks ---");
        System.out.println("User token access: " + (blacklist.isBlacklisted(userTokenJti) ? "DENIED" : "GRANTED"));
        System.out.println("Admin token access: " + (blacklist.isBlacklisted(adminTokenJti) ? "DENIED" : "GRANTED"));
    }
}

Whitelisting Explained

Whitelisting is an alternative revocation strategy. Instead of listing forbidden tokens, you maintain a list of active, allowed tokens.

  • When a token is issued, its JTI is added to a 'whitelist'.
  • For every request, the token's JTI must be found on this whitelist to be considered valid.
  • If a token's JTI is not on the whitelist, it's rejected.

Implementing a Whitelist

Similar to blacklisting, a whitelist requires a fast, persistent store (e.g., Redis). The key difference is what you store and how you manage it:

  • Each entry typically stores the JWT's JTI, often associated with a user ID.
  • When a user logs out or changes their password, all active JTIs associated with that user can be efficiently removed from the whitelist.

Blacklist vs. Whitelist Comparison

Both strategies achieve revocation but have different implications:

  • Blacklist: Ideal for rare, specific revocations (e.g., single token compromise). Requires less storage if revocations are infrequent.
  • Whitelist: Better for frequent revocations (e.g., user logout invalidates all tokens). Can simplify session management but requires more storage for all active tokens.
  • The choice depends on your application's specific needs and the frequency of revocations.

Revocation Scenario

Consider an application where users frequently log out, and you need to ensure all their issued tokens are immediately invalidated upon logout.

Recap: Revocation Strategies

In this lesson, we've explored advanced strategies for revoking JWTs, which is crucial for robust security:

  • Blacklisting: Marking specific tokens as invalid by adding their JTI to a forbidden list.
  • Whitelisting: Only allowing tokens that are explicitly listed as active, often tied to a user session.
  • The best approach depends on your application's requirements, especially the frequency and nature of token invalidation.

Next, we'll analyze the performance implications of these techniques.

무료로 시작

AI 튜터와 함께 Java을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
48

자주 묻는 질문

“JWT 블랙리스트 및 화이트리스트” 강의는 무료인가요?

네 — “JWT 블랙리스트 및 화이트리스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Security 6 & JWT Authentication 강의 전체를 잠금 해제할 수 있습니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

“JWT 블랙리스트 및 화이트리스트”에서 뭘 배우나요?

토큰 블랙리스트 또는 화이트리스트를 관리하는 방법을 포함해 고급 토큰 폐기 기법을 자세히 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Security 6 & JWT Authentication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Security 6 & JWT Authentication을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Security 6 & JWT Authentication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“JWT 블랙리스트 및 화이트리스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Security 6 & JWT Authentication 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Security 6 & JWT Authentication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 단기 JWT와 리프레시 주기
  2. JWT 블랙리스트 및 화이트리스트
  3. JWT 성능 고려 사항
  4. 확장성을 위한 토큰 검증 캐싱
← Spring Security 6 & JWT Authentication(으)로 돌아가기