Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import in.mateusz.spring.security.config.security.exception.AccountLocked;
- import in.mateusz.spring.security.config.security.exception.InvalidUsernameOrPassword;
- import in.mateusz.spring.security.entity.User;
- import in.mateusz.spring.security.repository.UserRepository;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.security.authentication.AuthenticationProvider;
- import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.core.context.SecurityContext;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.stereotype.Component;
- import java.time.LocalDateTime;
- import java.util.Optional;
- @Component
- public class AuthenticationProviderImpl implements AuthenticationProvider {
- private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationProviderImpl.class);
- private final int maxFailedLoginAttempts;
- private final UserRepository userRepository;
- public AuthenticationProviderImpl(@Value("${auth.maxFailedLoginAttempts:5}")
- int maxFailedLoginAttempts,
- UserRepository userRepository) {
- this.maxFailedLoginAttempts = maxFailedLoginAttempts;
- this.userRepository = userRepository;
- }
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- if (authentication.isAuthenticated()) {
- return authentication;
- }
- String username = (String) authentication.getPrincipal();
- String password = (String) authentication.getCredentials();
- LOGGER.debug("Authenticate: username: {}, password: {}", username, password);
- User user = userRepository.findByUsername(username)
- .orElseThrow(InvalidUsernameOrPassword::new);
- isLocked(user);
- isCorrectPassword(password, user);
- return success(user);
- }
- private void isLocked(User user) {
- Integer failedLoginAttempts = Optional.ofNullable(user.getFailedLoginAttempts()).orElse(0);
- if (failedLoginAttempts > maxFailedLoginAttempts) {
- LOGGER.debug("Too many failed attempts. Account locked");
- throw new AccountLocked();
- }
- }
- private void isCorrectPassword(String password, User user) {
- boolean isPasswordCorrect = new BCryptPasswordEncoder().matches(password, user.getPassword());
- if (!isPasswordCorrect) {
- LOGGER.debug("Incorrect password");
- int failedLoginCount = Optional.ofNullable(user.getFailedLoginAttempts()).orElse(0) + 1;
- user.setFailedLoginAttempts(failedLoginCount);
- user.setLastFailedLogin(LocalDateTime.now());
- userRepository.save(user);
- throw new InvalidUsernameOrPassword();
- }
- }
- private Authentication success(User user) {
- LOGGER.debug("User logged");
- user.setFailedLoginAttempts(0);
- user.setLastSuccessfulLogin(LocalDateTime.now());
- userRepository.save(user);
- return createAuthentication(user);
- }
- private Authentication createAuthentication(User user) {
- UserInfo userInfo = UserInfo.builder()
- .username(user.getUsername())
- .userType(user.getType())
- .build();
- Authentication authenticatedUser = new AuthenticatedUser(user, userInfo);
- SecurityContext ctx = SecurityContextHolder.getContext();
- ctx.setAuthentication(authenticatedUser);
- return authenticatedUser;
- }
- @Override
- public boolean supports(Class<?> authentication) {
- return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement