I want to trigger an event if there is an invalid credential,in my code it goes to orelsethrow block(trying to achieve account lock).Is it possible to catch the exception thrown from "org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(),grantedAuthorities)" so that I can trigger an event which handles account lock
I have created a custom event handler(AuthenticationFailureEventListener din't work) to lock account after 3 or 5 attempts.I am using jhipster UAA
Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
log.info("User " + login + " was not activated");
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin, user.getPassword(),
grantedAuthorities);
})
.orElseThrow(
() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"));
------- Account Lock Class
@Service
public class AccountLockService {
private final int MAX_ATTEMPT = 3;
private LoadingCache<String, Integer> attemptsCache;
public AccountLockService() {
super();
attemptsCache = CacheBuilder.newBuilder().
expireAfterWrite(1, TimeUnit.MINUTES).build(new CacheLoader<String, Integer>() {
public Integer load(String key) {
return 0;
}
});
}
public void loginFailed(String key) {
int attempts = 0;
try {
attempts = attemptsCache.get(key);
} catch (ExecutionException e) {
attempts = 0;
}
attempts++;
attemptsCache.put(key, attempts);
}
public boolean isBlocked(String key) {
try {
return attemptsCache.get(key) >= MAX_ATTEMPT;
} catch (ExecutionException e) {
return false;
}
}
}
----Custom Listener
@Component
public class CustomCreatedEventListener {
@Autowired
private AccountLockService accountLockService;
@Autowired
private HttpServletRequest request;
public CustomCreatedEventListener(AccountLockService accountLockService, HttpServletRequest request) {
this.accountLockService = accountLockService;
this.request = request;
}
@EventListener
public void accountLock(Authentication auth) {
String xfHeader = request.getHeader("X-Forwarded-For");
if (xfHeader == null) {
xfHeader = request.getRemoteAddr();
}
xfHeader = xfHeader.split(",")[0];
accountLockService.loginFailed(xfHeader);
}
}