как обработать исключение, выброшенное из org.springframework.security.core.userdetails.User для неверных учетных данных - PullRequest
4 голосов
/ 27 марта 2019

Я хочу вызвать событие, если есть недопустимые учетные данные, в моем коде он переходит в блок orelsethrow (пытается добиться блокировки учетной записи). Возможно перехватить исключение, выданное из "org.springframework.security.core. userdetails.User (lowercaseLogin, user.getPassword (), grantAuthorities) ", чтобы я мог вызвать событие, которое обрабатывает блокировку учетной записи

Я создал собственный обработчик событий (AuthenticationFailureEventListener не работает) для блокировки учетной записи после 3 или 5 попыток. Я использую 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"));

------- Класс блокировки учетной записи

     @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;
        }
    }
}

---- Пользовательский слушатель

@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);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...