JWT vs Token+Redis: Which Authentication Strategy Wins for Your Backend?
This article thoroughly compares JWT and Token‑plus‑Redis authentication approaches, detailing their underlying principles, Java implementations, performance, security trade‑offs, and ideal use‑cases, and even proposes a hybrid solution that combines the strengths of both methods for modern applications.
1. Authentication and Authorization
Before diving into the two schemes, we clarify two basic concepts:
Authentication : Who are you? The process of verifying a user's identity.
Authorization : What can you do? The process of verifying a user's permissions.
Both JWT and Token+Redis aim to solve these two problems.
2. JWT Scheme
2.1 What is JWT?
JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information as a JSON object. A JWT consists of three parts: header.payload.signature Header : token type and signing algorithm.
Payload : claims such as user info and expiration time.
Signature : ensures the token has not been tampered with.
2.2 JWT Workflow
The following diagram illustrates a complete login flow for JWT:
2.3 JWT Java Implementation Example
A simple JWT utility class:
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
public class JwtUtil {
// Secret key (should be loaded from configuration in real projects)
private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
// Expiration time: 2 hours
private static final long EXPIRATION_TIME = 2 * 60 * 60 * 1000;
/** Generate JWT */
public static String generateToken(String userId, String username, List<String> roles) {
return Jwts.builder()
.setSubject(userId)
.claim("username", username)
.claim("roles", roles)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(key)
.compact();
}
/** Parse and validate JWT */
public static Claims parseToken(String token) {
try {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
throw new RuntimeException("Token has expired", e);
} catch (JwtException e) {
throw new RuntimeException("Token is invalid", e);
}
}
/** Refresh JWT */
public static String refreshToken(String token) {
Claims claims = parseToken(token);
return generateToken(claims.getSubject(), claims.get("username", String.class), claims.get("roles", List.class));
}
}2.4 Advantages and Disadvantages of JWT
Advantages:
Stateless – the server does not need to store session data.
Cross‑domain friendly – suitable for distributed systems and micro‑services.
Self‑contained – all necessary information is inside the token.
Highly extensible – custom claims can be added easily.
Disadvantages:
Cannot be actively revoked – a token remains valid until it expires.
Token size can become large when many claims are added.
Security depends entirely on the signing key; key leakage is catastrophic.
3. Token+Redis Scheme
3.1 What is Token+Redis?
This scheme generates a random token as a session identifier and stores the session data in Redis, making it a stateful solution.
3.2 Token+Redis Workflow
3.3 Token+Redis Java Implementation Example
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
public class RedisSessionManager {
private final RedisTemplate<String, Object> redisTemplate;
private static final long SESSION_EXPIRE_TIME = 2 * 60 * 60; // seconds
public RedisSessionManager(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/** Create session */
public String createSession(User user) {
String token = UUID.randomUUID().toString().replace("-", "");
SessionInfo sessionInfo = new SessionInfo(user.getId(), user.getUsername(), user.getRoles());
redisTemplate.opsForValue().set("session:" + token, sessionInfo, SESSION_EXPIRE_TIME, TimeUnit.SECONDS);
return token;
}
/** Get session */
public SessionInfo getSession(String token) {
return (SessionInfo) redisTemplate.opsForValue().get("session:" + token);
}
/** Delete session */
public void deleteSession(String token) {
redisTemplate.delete("session:" + token);
}
/** Refresh session expiration */
public void refreshSession(String token) {
redisTemplate.expire("session:" + token, SESSION_EXPIRE_TIME, TimeUnit.SECONDS);
}
@Data
@AllArgsConstructor
public static class SessionInfo {
private String userId;
private String username;
private List<String> roles;
private long createTime = System.currentTimeMillis();
}
}3.4 Advantages and Disadvantages of Token+Redis
Advantages:
Active control – tokens can be invalidated at any time.
Small token size – the token is just an identifier.
High flexibility – complex session state can be stored.
Good security – a leaked token can be revoked immediately.
Disadvantages:
Stateful – the server must maintain session data.
Redis becomes a single point of failure.
Network overhead – each request requires a Redis lookup.
Scalability challenges – managing Redis clusters and data synchronization.
4. In‑Depth Comparison
4.1 Performance
Aspect
JWT
Token+Redis
Authentication speed
Fast (local verification)
Slow (requires Redis query)
Network overhead
Low
High (Redis access per request)
Server load
Low
High (Redis handles many queries)
Scalability cost
Low
High (needs Redis cluster)
4.2 Security
JWT considerations:
Key management – signing keys must be protected and rotated regularly.
Token leakage – cannot be revoked proactively; only expires.
Algorithm choice – use strong algorithms such as HS256 or RS256.
Token+Redis considerations:
Redis security – the Redis instance must be secured.
Token randomness – tokens must be sufficiently random to prevent guessing.
Transport security – always use HTTPS to prevent eavesdropping.
4.3 Suitable Scenarios
When JWT fits best:
Distributed systems and micro‑service architectures.
Cross‑domain SPA authentication.
Stateless API services.
Mobile back‑ends.
When Token+Redis fits best:
Monolithic or few‑service architectures needing fine‑grained session control.
Enterprise applications that require real‑time permission revocation.
Traditional web apps with complex session data.
High‑security financial systems.
5. Hybrid Scheme
A hybrid approach combines short‑lived JWTs with a Redis blacklist to achieve both stateless performance and active revocation.
5.1 Short‑Lived JWT + Redis Blacklist
public class HybridAuthManager {
private final JwtUtil jwtUtil;
private final RedisTemplate<String, Object> redisTemplate;
private static final long SHORT_EXPIRATION = 15 * 60 * 1000; // 15 minutes
private static final long REFRESH_EXPIRATION = 7 * 24 * 60 * 60 * 1000; // 7 days
/** Generate access and refresh tokens */
public AuthResponse generateTokenPair(User user) {
String accessToken = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRoles(), SHORT_EXPIRATION);
String refreshToken = UUID.randomUUID().toString();
storeRefreshToken(refreshToken, user.getId());
return new AuthResponse(accessToken, refreshToken);
}
/** Refresh access token */
public String refreshAccessToken(String refreshToken) {
String userId = validateRefreshToken(refreshToken);
if (userId == null) throw new RuntimeException("Invalid refresh token");
User user = userService.getUserById(userId);
return jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRoles(), SHORT_EXPIRATION);
}
/** Logout – add JWT to blacklist and delete refresh token */
public void logout(String accessToken, String refreshToken) {
Claims claims = jwtUtil.parseToken(accessToken);
long expiration = claims.getExpiration().getTime() - System.currentTimeMillis();
if (expiration > 0) {
redisTemplate.opsForValue().set("blacklist:" + accessToken, "logout", expiration, TimeUnit.MILLISECONDS);
}
if (refreshToken != null) {
redisTemplate.delete("refresh_token:" + refreshToken);
}
}
/** Check if token is blacklisted */
public boolean isTokenBlacklisted(String token) {
return redisTemplate.hasKey("blacklist:" + token);
}
}5.2 Hybrid Workflow
6. Practical Selection Advice
Based on years of experience, consider the following guidelines:
6.1 Choose JWT when:
The system is distributed and needs stateless authentication.
Cross‑domain access is required.
API consumers are third‑party apps or mobile clients.
The team can manage keys securely.
6.2 Choose Token+Redis when:
The architecture is monolithic or has few services.
Fine‑grained session control and real‑time permission revocation are needed.
A dedicated ops team can maintain a Redis cluster.
Security requirements are extremely high.
6.3 Choose the Hybrid scheme when:
You want JWT’s stateless benefits but also need active logout.
User experience must be smooth without frequent logins.
The team can handle the added token‑management logic.
A balanced trade‑off between security and convenience is desired.
7. Conclusion
There is no universally best authentication solution; the optimal choice depends on the specific business scenario.
JWT excels in statelessness and extensibility, making it ideal for distributed APIs.
Token+Redis provides precise control and flexibility, suited for enterprise applications that require real‑time session management.
A hybrid approach can combine the strengths of both, fitting most modern web applications.
Remember, security is a process, not a single feature. Choose the simplest, most reliable solution that meets your actual requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
