Spring Cloud 中防止重放攻击 代码
时间: 2024-02-18 07:00:45 浏览: 20
下面是一个基于 Spring Cloud 的防止重放攻击的示例代码:
1.使用 JWT 验证:
```java
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
private static final String SECRET_KEY = "YOUR_SECRET_KEY";
private static final long EXPIRATION_TIME = 86400 * 7;
public static String createToken(String username) {
Date now = new Date();
Date expiration = new Date(now.getTime() + EXPIRATION_TIME * 1000);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public static String getUsernameFromToken(String token) {
try {
Claims claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
return claims.getSubject();
} catch (Exception ex) {
logger.error("Failed to parse JWT token: {}", ex.getMessage());
return null;
}
}
}
```
2.使用 Token Bucket 算法进行限流处理:
```java
public class TokenBucket {
private int bucketSize;
private int tokens;
private long lastRefillTime;
public TokenBucket(int bucketSize, int tokens) {
this.bucketSize = bucketSize;
this.tokens = tokens;
this.lastRefillTime = System.currentTimeMillis();
}
public synchronized boolean tryConsume() {
refill();
if (tokens > 0) {
tokens--;
return true;
}
return false;
}
private void refill() {
long now = System.currentTimeMillis();
if (now > lastRefillTime) {
int elapsedTime = (int) (now - lastRefillTime);
int newTokens = elapsedTime / 1000;
tokens = Math.min(tokens + newTokens, bucketSize);
lastRefillTime = now;
}
}
}
```
3.使用缓存来存储已经处理过的请求:
```java
public class CacheUtils {
private static final int MAX_CACHE_SIZE = 1000;
private static final int EXPIRATION_TIME = 5; // 缓存时间:5 秒
private static final LoadingCache<String, Boolean> CACHE = CacheBuilder.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.expireAfterWrite(EXPIRATION_TIME, TimeUnit.SECONDS)
.build(new CacheLoader<String, Boolean>() {
@Override
public Boolean load(String key) throws Exception {
return Boolean.TRUE;
}
});
public static boolean isRequestCached(String requestId) {
return CACHE.getIfPresent(requestId) != null;
}
public static void cacheRequest(String requestId) {
CACHE.put(requestId, Boolean.TRUE);
}
}
```
4.使用 HTTPS 协议进行通信:
这部分不需要特别的代码实现,只需要配置好 SSL 证书即可。在 Spring Cloud 中,可以使用 Spring Boot 提供的自动配置来实现 SSL 配置,例如:
```yaml
server:
port: 443
ssl:
key-store: classpath:ssl/keystore.p12
key-store-password: YOUR_PASSWORD
key-store-type: PKCS12
key-alias: YOUR_ALIAS
```
阅读全文