Advertisement
Guest User

Untitled

a guest
Apr 15th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.98 KB | None | 0 0
  1. import in.mateusz.spring.security.config.security.exception.AccountLocked;
  2. import in.mateusz.spring.security.config.security.exception.InvalidUsernameOrPassword;
  3. import in.mateusz.spring.security.entity.User;
  4. import in.mateusz.spring.security.repository.UserRepository;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.security.authentication.AuthenticationProvider;
  9. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  10. import org.springframework.security.core.Authentication;
  11. import org.springframework.security.core.AuthenticationException;
  12. import org.springframework.security.core.context.SecurityContext;
  13. import org.springframework.security.core.context.SecurityContextHolder;
  14. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  15. import org.springframework.stereotype.Component;
  16.  
  17. import java.time.LocalDateTime;
  18. import java.util.Optional;
  19.  
  20. @Component
  21. public class AuthenticationProviderImpl implements AuthenticationProvider {
  22.  
  23. private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationProviderImpl.class);
  24.  
  25. private final int maxFailedLoginAttempts;
  26. private final UserRepository userRepository;
  27.  
  28. public AuthenticationProviderImpl(@Value("${auth.maxFailedLoginAttempts:5}")
  29. int maxFailedLoginAttempts,
  30. UserRepository userRepository) {
  31. this.maxFailedLoginAttempts = maxFailedLoginAttempts;
  32. this.userRepository = userRepository;
  33. }
  34.  
  35. @Override
  36. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  37. if (authentication.isAuthenticated()) {
  38. return authentication;
  39. }
  40. String username = (String) authentication.getPrincipal();
  41. String password = (String) authentication.getCredentials();
  42. LOGGER.debug("Authenticate: username: {}, password: {}", username, password);
  43.  
  44. User user = userRepository.findByUsername(username)
  45. .orElseThrow(InvalidUsernameOrPassword::new);
  46. isLocked(user);
  47. isCorrectPassword(password, user);
  48.  
  49. return success(user);
  50. }
  51.  
  52. private void isLocked(User user) {
  53. Integer failedLoginAttempts = Optional.ofNullable(user.getFailedLoginAttempts()).orElse(0);
  54. if (failedLoginAttempts > maxFailedLoginAttempts) {
  55. LOGGER.debug("Too many failed attempts. Account locked");
  56. throw new AccountLocked();
  57. }
  58. }
  59.  
  60. private void isCorrectPassword(String password, User user) {
  61. boolean isPasswordCorrect = new BCryptPasswordEncoder().matches(password, user.getPassword());
  62. if (!isPasswordCorrect) {
  63. LOGGER.debug("Incorrect password");
  64. int failedLoginCount = Optional.ofNullable(user.getFailedLoginAttempts()).orElse(0) + 1;
  65.  
  66. user.setFailedLoginAttempts(failedLoginCount);
  67. user.setLastFailedLogin(LocalDateTime.now());
  68. userRepository.save(user);
  69.  
  70. throw new InvalidUsernameOrPassword();
  71. }
  72. }
  73.  
  74. private Authentication success(User user) {
  75. LOGGER.debug("User logged");
  76. user.setFailedLoginAttempts(0);
  77. user.setLastSuccessfulLogin(LocalDateTime.now());
  78. userRepository.save(user);
  79.  
  80. return createAuthentication(user);
  81. }
  82.  
  83. private Authentication createAuthentication(User user) {
  84. UserInfo userInfo = UserInfo.builder()
  85. .username(user.getUsername())
  86. .userType(user.getType())
  87. .build();
  88. Authentication authenticatedUser = new AuthenticatedUser(user, userInfo);
  89. SecurityContext ctx = SecurityContextHolder.getContext();
  90. ctx.setAuthentication(authenticatedUser);
  91. return authenticatedUser;
  92. }
  93.  
  94. @Override
  95. public boolean supports(Class<?> authentication) {
  96. return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement