-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathTokenDenylist.java
More file actions
55 lines (46 loc) · 1.87 KB
/
TokenDenylist.java
File metadata and controls
55 lines (46 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.iemr.admin.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class TokenDenylist {
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
private static final String PREFIX = "denied_";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private String getKey(String jti) {
return PREFIX + jti;
}
// Add a token's jti to the denylist with expiration time
public void addTokenToDenylist(String jti, Long expirationTime) {
if (jti == null || jti.trim().isEmpty()) {
return;
}
if (expirationTime == null || expirationTime <= 0) {
throw new IllegalArgumentException("Expiration time must be positive");
}
try {
String key = getKey(jti); // Use helper method to get the key
redisTemplate.opsForValue().set(key, " ", expirationTime, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new RuntimeException("Failed to denylist token", e);
}
}
// Check if a token's jti is in the denylist
public boolean isTokenDenylisted(String jti) {
if (jti == null || jti.trim().isEmpty()) {
return false;
}
try {
String key = getKey(jti); // Use helper method to get the key
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
} catch (Exception e) {
logger.error("Failed to check denylist status for jti: " + jti, e);
// In case of Redis failure, consider the token as not denylisted to avoid blocking all requests
return false;
}
}
}