Add brute-force protection with rate limiting on login
- Caffeine cache used to allow max 5 login attempts per minute. - Login endpoint blocks IPs exceeding rate, returns 429 status. - Failed attempts are reset after successful login or after 1 minute.
This commit is contained in:
@@ -24,12 +24,26 @@ public class AuthController {
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
|
||||
authManager.authenticate(new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
|
||||
public ResponseEntity<?> login(@RequestBody LoginRequest request, HttpServletRequest servletRequest) {
|
||||
String ip = servletRequest.getRemoteAddr(); // or use request.getEmail() as key
|
||||
|
||||
if (rateLimiterService.isBlocked(ip)) {
|
||||
return ResponseEntity.status(429).body("Too many login attempts. Please try again later.");
|
||||
}
|
||||
|
||||
try {
|
||||
authManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
|
||||
);
|
||||
} catch (Exception ex) {
|
||||
rateLimiterService.recordFailedAttempt(ip);
|
||||
return ResponseEntity.status(401).body("Invalid credentials.");
|
||||
}
|
||||
|
||||
User user = userRepository.findByEmail(request.getEmail())
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
|
||||
rateLimiterService.resetAttempts(ip);
|
||||
String token = jwtService.generateToken(user);
|
||||
return ResponseEntity.ok().body(token);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user