0Pricing
Spring Security 6 & JWT Authentication · Урок

Обработка пользовательских событий аутентификации

Создайте пользовательские обработчики событий успешной и неудачной аутентификации для ведения журналов, аудита и выполнения других действий.

«Обработка пользовательских событий аутентификации» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to Auth Events

Welcome to Custom Authentication Event Handling! In Spring Security, many important actions, like a user logging in or failing to log in, trigger events.

These events are like signals that your application can 'listen' for. By listening, you can react to these security-related happenings.

  • Logging: Record who logged in and when.
  • Auditing: Track security-sensitive actions.
  • Custom Logic: Implement specific actions on success or failure (e.g., lock accounts after too many failed attempts).

Spring's Event System

Spring Framework has a powerful event publication and subscription model. Spring Security leverages this to publish various authentication-related events.

You can create custom components that 'listen' for these events and execute logic whenever they occur. This keeps your security logic separate and clean.

Key Authentication Events

Two of the most common and useful authentication events you'll encounter are:

  • AuthenticationSuccessEvent: Fired when a user successfully authenticates. This is perfect for logging successful logins or updating last login times.
  • AbstractAuthenticationFailureEvent: This is a base class for all authentication failure events. Specific failure types (e.g., bad credentials, disabled account) extend this. You can listen to the base class to catch all failures or specific subclasses.

Creating a Custom Listener

To create a listener, you typically use the @EventListener annotation on a method within a Spring component. Spring automatically detects these methods and registers them as event listeners.

The method's parameter type determines which event it will listen to. For example, a method with an AuthenticationSuccessEvent parameter will only be called when that specific event occurs.

Code: Success Listener Setup

Let's set up a simple Spring Boot application with in-memory authentication. This will allow us to trigger authentication events and see our listeners in action.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@SpringBootApplication
@EnableWebSecurity
public class EventHandlingApp {

    public static void main(String[] args) {
        SpringApplication.run(EventHandlingApp.class, args);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .formLogin();
        return http.build();
    }
}

Code: Implementing Success Listener

Now, let's create our custom listener for successful authentication. We'll simply log a message when a user successfully logs in.

Save this as a new Java file (e.g., AuthenticationSuccessListener.java) in the same package as EventHandlingApp. Then, run EventHandlingApp and try to log in via a browser (e.g., localhost:8080 with user/password).

import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationSuccessListener {

    @EventListener
    public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) {
        String username = event.getAuthentication().getName();
        System.out.println("SUCCESS: User '" + username + "' logged in successfully!");
        // You could also log full details, update a database, etc.
    }
}

Handling Authentication Failures

Just as important as successful logins are failed attempts. Spring Security provides AbstractAuthenticationFailureEvent and its subclasses to handle these scenarios.

By listening to this event, you can:

  • Log failed attempts for security auditing.
  • Implement brute-force protection (e.g., locking an account after N failures).
  • Trigger alerts for suspicious activity.

Code: Implementing Failure Listener

Let's add a listener for authentication failures. This listener will catch any type of failure and log the username and the reason for the failure.

Add this as another @Component or as a method in your existing AuthenticationSuccessListener. Try logging in with incorrect credentials to see it in action.

import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationFailureListener {

    @EventListener
    public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) {
        String username = event.getAuthentication().getName();
        String failureReason = event.getException().getMessage();
        System.err.println("FAILURE: User '" + username + "' failed to log in. Reason: " + failureReason);
        // You can check event.getException() for specific failure types
    }
}

Distinguishing Failure Types

AbstractAuthenticationFailureEvent is a parent class. For more granular control, you can listen to specific subclasses:

  • BadCredentialsEvent: Incorrect username/password.
  • DisabledExceptionEvent: User account is disabled.
  • LockedExceptionEvent: User account is locked.
  • AccountExpiredExceptionEvent: User account has expired.

You can create separate @EventListener methods for each or use instanceof checks within a single listener.

Custom Event Handling Check

You've learned how to create listeners for Spring Security authentication events. Let's check your understanding.

Recap: Event Handling

We've covered how Spring Security leverages Spring's event system to publish authentication-related events. You learned to:

  • Understand the purpose of authentication events for logging and auditing.
  • Use the @EventListener annotation to create custom listeners.
  • Handle AuthenticationSuccessEvent for successful logins.
  • Handle AbstractAuthenticationFailureEvent for various login failures.

By using these events, you gain powerful control and visibility into your application's authentication process.

Часто задаваемые вопросы

Урок «Обработка пользовательских событий аутентификации» бесплатный?

Да — полный текст урока «Обработка пользовательских событий аутентификации» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

Чему я научусь в уроке «Обработка пользовательских событий аутентификации»?

Создайте пользовательские обработчики событий успешной и неудачной аутентификации для ведения журналов, аудита и выполнения других действий. Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?

Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Обработка пользовательских событий аутентификации»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?

Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Реализация многофакторной аутентификации
  2. Ограничение частоты доступа к API
  3. Обработка пользовательских событий аутентификации
  4. Блокировка учётных записей и защита от перебора
← Назад к Spring Security 6 & JWT Authentication