59. Brute force attack cache - Guava LoadingCache Service Implementation (#6)
This commit is contained in:
@ -60,6 +60,12 @@
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>30.1.1-jre</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
||||
@ -0,0 +1,46 @@
|
||||
package net.shyshkin.study.fullstack.supportportal.backend.service;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Primary
|
||||
public class GuavaCacheLoginAttemptService implements LoginAttemptService {
|
||||
|
||||
private LoadingCache<String, Integer> loginAttemptsCache = CacheBuilder.newBuilder()
|
||||
.expireAfterWrite(15, TimeUnit.MINUTES)
|
||||
.maximumSize(100)
|
||||
.build(new CacheLoader<>() {
|
||||
@Override
|
||||
public Integer load(String key) throws Exception {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
@Override
|
||||
public void loginFailed(String username) {
|
||||
int attempts = getAttempts(username);
|
||||
loginAttemptsCache.put(username, attempts + ATTEMPT_INCREMENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loginSucceeded(String username) {
|
||||
loginAttemptsCache.invalidate(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasExceededMaxAttempts(String username) {
|
||||
return getAttempts(username) >= MAX_ATTEMPTS;
|
||||
}
|
||||
|
||||
private int getAttempts(String username) {
|
||||
Integer attempts = loginAttemptsCache.getIfPresent(username);
|
||||
return Objects.requireNonNullElse(attempts, 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user