Gestion personnalisée des événements d’authentification
Créez des écouteurs personnalisés pour les événements de réussite et d’échec de l’authentification afin de mettre en œuvre la journalisation, l’audit ou d’autres actions.
Gestion personnalisée des événements d’authentification est une leçon Spring Security 6 & JWT Authentication gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Security 6 & JWT Authentication, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Security 6 & JWT Authentication comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
@EventListenerannotation to create custom listeners. - Handle
AuthenticationSuccessEventfor successful logins. - Handle
AbstractAuthenticationFailureEventfor various login failures.
By using these events, you gain powerful control and visibility into your application's authentication process.
Apprends Java avec un tuteur IA — gratuit
Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.
- Cours
- 12
- Leçons
- 48
Questions Fréquemment Posées
La leçon « Gestion personnalisée des événements d’authentification » est-elle gratuite ?
Oui — le texte complet de « Gestion personnalisée des événements d’authentification » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Security 6 & JWT Authentication, passe à CoddyKit PRO. Le cours Spring Security 6 & JWT Authentication comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Gestion personnalisée des événements d’authentification » ?
Créez des écouteurs personnalisés pour les événements de réussite et d’échec de l’authentification afin de mettre en œuvre la journalisation, l’audit ou d’autres actions. Tu pratiques Spring Security 6 & JWT Authentication avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Spring Security 6 & JWT Authentication ?
Aucune expérience préalable n'est requise. Spring Security 6 & JWT Authentication sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Gestion personnalisée des événements d’authentification » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Spring Security 6 & JWT Authentication ?
Oui. Chaque leçon Spring Security 6 & JWT Authentication inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Mise en œuvre de l’authentification multifacteur
- Limitation du débit d’accès aux API
- Gestion personnalisée des événements d’authentification
- Verrouillage des comptes et protection contre la force brute