Skip to content

Commit 1d026ac

Browse files
author
Eugen
committed
Merge pull request eugenp#136 from Doha2012/master
prevent brute force authentications
2 parents 7771097 + 10e9f8b commit 1d026ac

20 files changed

Lines changed: 121 additions & 396 deletions

File tree

‎spring-security-login-and-registration/src/main/java/org/baeldung/persistence/model/User.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.Collection;
44

5+
import javax.persistence.Column;
56
import javax.persistence.Entity;
67
import javax.persistence.GeneratedValue;
78
import javax.persistence.GenerationType;
@@ -23,6 +24,7 @@ public class User {
2324

2425
private String email;
2526

27+
@Column(length = 60)
2628
private String password;
2729

2830
private boolean enabled;
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package org.baeldung.security;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.ApplicationListener;
5+
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
6+
import org.springframework.security.web.authentication.WebAuthenticationDetails;
7+
import org.springframework.stereotype.Component;
8+
9+
@Component
10+
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
11+
12+
@Autowired
13+
private LoginAttemptService loginAttemptService;
14+
15+
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
16+
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
17+
loginAttemptService.loginFailed(auth.getRemoteAddress());
18+
}
19+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package org.baeldung.security;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.ApplicationListener;
5+
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
6+
import org.springframework.security.web.authentication.WebAuthenticationDetails;
7+
import org.springframework.stereotype.Component;
8+
9+
@Component
10+
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {
11+
12+
@Autowired
13+
private LoginAttemptService loginAttemptService;
14+
15+
public void onApplicationEvent(AuthenticationSuccessEvent e) {
16+
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
17+
loginAttemptService.loginSucceeded(auth.getRemoteAddress());
18+
}
19+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package org.baeldung.security;
2+
3+
import java.util.concurrent.ExecutionException;
4+
import java.util.concurrent.TimeUnit;
5+
6+
import org.springframework.stereotype.Service;
7+
8+
import com.google.common.cache.CacheBuilder;
9+
import com.google.common.cache.CacheLoader;
10+
import com.google.common.cache.LoadingCache;
11+
12+
@Service
13+
public class LoginAttemptService {
14+
15+
private final int MAX_ATTEMPT = 10;
16+
private LoadingCache<String, Integer> attemptsCache;
17+
18+
public LoginAttemptService() {
19+
super();
20+
attemptsCache = CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.DAYS).build(new CacheLoader<String, Integer>() {
21+
public Integer load(String key) {
22+
return 0;
23+
}
24+
});
25+
}
26+
27+
public void loginSucceeded(String key) {
28+
attemptsCache.invalidate(key);
29+
}
30+
31+
public void loginFailed(String key) {
32+
int attempts = 0;
33+
try {
34+
attempts = attemptsCache.get(key);
35+
} catch (ExecutionException e) {
36+
attempts = 0;
37+
}
38+
attempts++;
39+
attemptsCache.put(key, attempts);
40+
}
41+
42+
public boolean isBlocked(String key) {
43+
try {
44+
return attemptsCache.get(key) >= MAX_ATTEMPT;
45+
} catch (ExecutionException e) {
46+
return false;
47+
}
48+
}
49+
}

‎spring-security-login-and-registration/src/main/java/org/baeldung/security/MyUserDetailsService.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import java.util.Collection;
66
import java.util.List;
77

8+
import javax.servlet.http.HttpServletRequest;
9+
810
import org.baeldung.persistence.dao.RoleRepository;
911
import org.baeldung.persistence.dao.UserRepository;
1012
import org.baeldung.persistence.model.Privilege;
@@ -34,6 +36,12 @@ public class MyUserDetailsService implements UserDetailsService {
3436
@Autowired
3537
private RoleRepository roleRepository;
3638

39+
@Autowired
40+
private LoginAttemptService loginAttemptService;
41+
42+
@Autowired
43+
private HttpServletRequest request;
44+
3745
public MyUserDetailsService() {
3846
super();
3947
}
@@ -42,6 +50,11 @@ public MyUserDetailsService() {
4250

4351
@Override
4452
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
53+
String ip = request.getRemoteAddr();
54+
if (loginAttemptService.isBlocked(ip)) {
55+
throw new RuntimeException("blocked");
56+
}
57+
4558
try {
4659
final User user = userRepository.findByEmail(email);
4760
if (user == null) {

‎spring-security-login-and-registration/src/main/resources/messages_en.properties‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,5 @@ message.resendToken=We will send you a message with a new registration token to
5858
message.forgetPassword=Forget Password
5959
message.resetPassword=Reset Password
6060
message.updatePassword=Update Password
61-
message.userNotFound=User Not Found
61+
message.userNotFound=User Not Found
62+
auth.message.blocked=This ip is blocked for 24 hours

‎spring-security-login-and-registration/src/main/resources/messages_es_ES.properties‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,5 @@ message.resendToken=Le enviaremos un mensaje con un nuevo token de registro en s
5858
message.forgetPassword=Olvide la contraseña
5959
message.resetPassword=Restablecer contraseña
6060
message.updatePassword=Actualizar contraseña
61-
message.userNotFound=Usuario no encontrado
61+
message.userNotFound=Usuario no encontrado
62+
auth.message.blocked=Esta IP se bloquea durante 24 horas

‎spring-security-login-and-registration/src/main/webapp/WEB-INF/view/login.jsp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@
2121
<spring:message code="auth.message.expired"></spring:message>
2222
</div>
2323
</c:when>
24+
<c:when
25+
test="${SPRING_SECURITY_LAST_EXCEPTION.message == 'blocked'}">
26+
<div class="alert alert-error">
27+
<spring:message code="auth.message.blocked"></spring:message>
28+
</div>
29+
</c:when>
2430
<c:otherwise>
2531
<div class="alert alert-error">
2632
<!-- <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/> -->

‎spring-security-login-and-registration/src/main/webapp/WEB-INF/web.xml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@
1616
<listener>
1717
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
1818
</listener>
19-
19+
20+
<listener>
21+
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
22+
</listener>
23+
2024
<servlet>
2125
<servlet-name>mvc</servlet-name>
2226
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

‎spring-security-oauth/src/main/java/org/baeldung/config/MyAccessTokenProviderChain.java‎

Lines changed: 0 additions & 134 deletions
This file was deleted.

0 commit comments

Comments
 (0)