0Pricing
Spring Security 6 & JWT Authentication · Aula

Bloqueio de contas e proteção contra força bruta

Aprenda a defender endpoints de login contra tentativas de adivinhar senhas rastreando falhas e bloqueando contas temporariamente no Spring Security.

Bloqueio de contas e proteção contra força bruta é uma aula grátis de Spring Security 6 & JWT Authentication no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Security 6 & JWT Authentication, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

The Brute-Force Threat

Attackers automate thousands of login attempts to guess passwords. Without limits, even rate limiting may not stop a slow, distributed guessing campaign against a single account.

Lockout as Defense

Account lockout blocks login for an account after too many failed attempts within a window. This makes online guessing impractical.

Listening for Failures

Spring Security publishes events on authentication outcomes. Listen for AuthenticationFailureBadCredentialsEvent to count failures.

@EventListener
public void onFailure(AuthenticationFailureBadCredentialsEvent e) {
    String user = (String) e.getAuthentication().getPrincipal();
    attempts.recordFailure(user);
}

Tracking Attempt Counts

Keep a counter per username (or per username+IP). A simple cache with a time-to-live resets the count automatically after the window passes.

void recordFailure(String user) {
    int count = cache.getOrDefault(user, 0) + 1;
    cache.put(user, count, Duration.ofMinutes(15));
}

Resetting on Success

A successful login should clear the counter, so legitimate users who mistyped a few times are not punished later.

@EventListener
public void onSuccess(AuthenticationSuccessEvent e) {
    attempts.reset(e.getAuthentication().getName());
}

Enforcing the Lock

Implement a UserDetailsService (or check during login) that throws LockedException when the threshold is exceeded.

if (attempts.isBlocked(username)) {
    throw new LockedException('Account temporarily locked');
}

Marking the Account Non-Locked

The UserDetails contract has isAccountNonLocked(). Return false to make Spring reject the login automatically.

@Override
public boolean isAccountNonLocked() {
    return !attempts.isBlocked(username);
}

Temporary vs Permanent Locks

Prefer temporary locks that auto-expire (for example 15 minutes). Permanent locks frustrate users and create a denial-of-service vector where attackers lock victims out on purpose.

Avoid User Enumeration

Return the same generic error for wrong password and locked account when possible, so attackers cannot tell which usernames exist or are locked.

Adding Exponential Backoff

Instead of a hard lock, increase the delay after each failure. The first retry waits a second, the next two, then four, slowing attackers without fully blocking users.

long delayMs = (long) Math.pow(2, count) * 1000;

Persisting State

In a multi-instance deployment, store attempt counts in a shared store like Redis so a lock applies across all nodes, not just the one that saw the failures.

Quick Check

Test your understanding of brute-force protection.

Recap

You learned to protect logins from brute force:

  • Count failures via Spring authentication events
  • Lock the account through isAccountNonLocked() or a thrown LockedException
  • Reset counters on success and prefer temporary locks
  • Use backoff, avoid enumeration, and share state across instances

These measures make password guessing impractical without hurting real users.

Perguntas Frequentes

A aula “Bloqueio de contas e proteção contra força bruta” é grátis?

Sim — o texto completo de “Bloqueio de contas e proteção contra força bruta” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Security 6 & JWT Authentication, atualize para CoddyKit PRO. O curso de Spring Security 6 & JWT Authentication inclui 4 aulas no total.

O que vou aprender em “Bloqueio de contas e proteção contra força bruta”?

Aprenda a defender endpoints de login contra tentativas de adivinhar senhas rastreando falhas e bloqueando contas temporariamente no Spring Security. Você pratica Spring Security 6 & JWT Authentication com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Security 6 & JWT Authentication?

Nenhuma experiência prévia é necessária. Spring Security 6 & JWT Authentication no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Bloqueio de contas e proteção contra força bruta”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Security 6 & JWT Authentication?

Sim. Cada aula de Spring Security 6 & JWT Authentication inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Implementação de autenticação multifator
  2. Limitação de taxa de acesso à API
  3. Tratamento personalizado de eventos de autenticação
  4. Bloqueio de contas e proteção contra força bruta
← Voltar para Spring Security 6 & JWT Authentication