Benutzerdefinierte UserDetailsService-Implementierung
Erstellen Sie einen benutzerdefinierten `UserDetailsService`, der benutzerspezifische Daten zur Authentifizierung aus dem Datenspeicher Ihrer Anwendung lädt.
Benutzerdefinierte UserDetailsService-Implementierung ist eine kostenlose Spring Security 6 & JWT Authentication-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Security 6 & JWT Authentication-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Beyond In-Memory Users
In previous lessons, you might have used in-memory users for simple authentication. This means usernames and passwords are hardcoded directly in your application's configuration.
While easy for testing, real-world applications need to load user data from a persistent source like a database, LDAP, or another service. This is where a custom UserDetailsService comes in!
The UserDetailsService Interface
Spring Security uses the UserDetailsService interface to retrieve user-specific data during authentication. It has just one method you need to implement:
UserDetails loadUserByUsername(String username)
This method is crucial. When a user tries to log in, Spring Security calls this method, passing the username provided by the user.
What is UserDetails?
The loadUserByUsername method must return a UserDetails object. This interface represents the authenticated user's information, including:
- Username
- Password
- Authorities (roles/permissions)
- Account status (e.g., enabled, locked, expired)
Spring Security provides a default implementation called org.springframework.security.core.userdetails.User that you'll often use.
Creating Your Custom Service
To create a custom user service, you simply create a class that implements UserDetailsService. Inside, you'll override the loadUserByUsername method.
This method is where you'll write the logic to fetch user data from your chosen data store. For now, we'll use some hardcoded examples.
Implementing loadUserByUsername
Inside loadUserByUsername, you'll perform these steps:
- Receive the
username. - Look up the user in your data source.
- If found, create a
UserDetailsobject with their details (username, password, roles). - If not found, throw a
UsernameNotFoundException.
Remember, password encoding is vital for security, but we'll cover that in a later lesson. For now, we'll use a plain text password prefix: {noop}.
Code: Basic UserDetailsService
Let's see a simple implementation. This example hardcodes users, simulating fetching from a data source. Run it to see how it works!
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.core.userdetails.UsernameNotFoundException;
import java.util.Arrays;
import java.util.Collections;
class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// In a real app, you'd fetch user from a database
if ("user".equals(username)) {
return User.withUsername("user")
.password("{noop}password") // {noop} for plain text
.roles("USER")
.build();
}
if ("admin".equals(username)) {
return User.withUsername("admin")
.password("{noop}adminpass")
.roles("ADMIN", "USER")
.build();
}
throw new UsernameNotFoundException("User not found: " + username);
}
}
public class Main {
public static void main(String[] args) {
MyUserDetailsService service = new MyUserDetailsService();
System.out.println("Attempting to load 'user'...");
try {
UserDetails user = service.loadUserByUsername("user");
System.out.println("Loaded User: " + user.getUsername());
System.out.println("Authorities: " + user.getAuthorities());
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("\nAttempting to load 'admin'...");
try {
UserDetails admin = service.loadUserByUsername("admin");
System.out.println("Loaded Admin: " + admin.getUsername());
System.out.println("Authorities: " + admin.getAuthorities());
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
System.out.println("\nAttempting to load 'unknown'...");
try {
service.loadUserByUsername("unknown");
} catch (UsernameNotFoundException e) {
System.out.println(e.getMessage());
}
}
}Adding Roles and Authorities
Notice in the example, we used .roles("USER") and .roles("ADMIN", "USER").
- Roles are high-level permissions, like 'ADMIN' or 'USER'.
- These roles are converted into GrantedAuthority objects by Spring Security.
- When building the
UserDetailsobject, you specify the roles/authorities the user possesses.
These authorities are later used by Spring Security for authorization (determining what a user can access).
Registering Your Service
Once you've created your custom UserDetailsService, Spring Security needs to know about it. In a Spring Boot application, you typically register it as a Spring bean.
By simply defining your custom service as a @Bean, Spring Security's auto-configuration will usually pick it up and use it for authentication.
The Custom Authentication Flow
Here's how custom authentication typically works with your service:
- User submits login credentials (username, password).
- Spring Security receives the request.
- It calls your custom
UserDetailsService'sloadUserByUsername()method with the provided username. - Your method fetches user data and returns a
UserDetailsobject. - Spring Security then compares the provided password with the password from
UserDetails(after encoding/decoding). - If they match, authentication succeeds!
Check Your Understanding
Consider the core purpose and components of implementing a custom UserDetailsService.
Recap: Custom UserDetailsService
You've learned how to implement a custom UserDetailsService, a fundamental component for advanced user authentication in Spring Security:
- It allows loading user data from any source.
- You implement the
loadUserByUsernamemethod. - This method returns a
UserDetailsobject, containing user credentials and authorities. - It's essential for moving beyond in-memory user management.
Next, we'll dive into securing those passwords with proper encoding!
Häufig gestellte Fragen
Ist die Lektion „Benutzerdefinierte UserDetailsService-Implementierung“ kostenlos?
Ja — der vollständige Text von „Benutzerdefinierte UserDetailsService-Implementierung“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Security 6 & JWT Authentication-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Security 6 & JWT Authentication-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Benutzerdefinierte UserDetailsService-Implementierung“?
Erstellen Sie einen benutzerdefinierten `UserDetailsService`, der benutzerspezifische Daten zur Authentifizierung aus dem Datenspeicher Ihrer Anwendung lädt. Du übst Spring Security 6 & JWT Authentication mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Security 6 & JWT Authentication zu starten?
Keine Vorkenntnisse erforderlich. Spring Security 6 & JWT Authentication auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Benutzerdefinierte UserDetailsService-Implementierung“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Security 6 & JWT Authentication-Lektion Code schreiben und ausführen?
Ja. Jede Spring Security 6 & JWT Authentication-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Benutzerdefinierte UserDetailsService-Implementierung
- Passwort-Encoder verstehen
- Integration der Benutzerverwaltung mit einer Datenbank
- Rollenbasierte Autorisierung mit Granted Authorities