Junior — Middle
What methods can be used to protect your application from unwanted mass activity and spam attacks?
sobes.tech AI
Answer from AI
To protect an application from unwanted mass activity and spam attacks, the following methods can be used:
- Rate Limiting: limiting the number of requests from a single user or IP over a certain period.
- CAPTCHA: verifying that requests are made by a human and not a bot.
- Authentication and Authorization: requiring registration and login to access certain features.
- Data Filtering and Validation: checking incoming data for spam or suspicious content.
- IP and User Blacklists: blocking known spam sources.
- Using a Web Application Firewall (WAF): automatic protection against known attacks.
An example of simple rate limiting in Java using the Bucket4j library:
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Refill;
import java.time.Duration;
public class RateLimiter {
private final Bucket bucket;
public RateLimiter() {
Bandwidth limit = Bandwidth.classic(10, Refill.greedy(10, Duration.ofMinutes(1)));
this.bucket = Bucket.builder().addLimit(limit).build();
}
public boolean tryConsume() {
return bucket.tryConsume(1);
}
}
This code allows accepting no more than 10 requests per minute.