0Pricing
Spring Security 6 & JWT Authentication · Ders

Özel UserDetailsService Uygulaması

Kimlik doğrulama için uygulamanızın veri deposundan kullanıcıya özgü verileri yükleyen özel bir `UserDetailsService` oluşturun.

Özel UserDetailsService Uygulaması, CoddyKit'te ücretsiz bir Spring Security 6 & JWT Authentication dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Spring Security 6 & JWT Authentication öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Spring Security 6 & JWT Authentication kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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:

  1. Receive the username.
  2. Look up the user in your data source.
  3. If found, create a UserDetails object with their details (username, password, roles).
  4. 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 UserDetails object, 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:

  1. User submits login credentials (username, password).
  2. Spring Security receives the request.
  3. It calls your custom UserDetailsService's loadUserByUsername() method with the provided username.
  4. Your method fetches user data and returns a UserDetails object.
  5. Spring Security then compares the provided password with the password from UserDetails (after encoding/decoding).
  6. 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 loadUserByUsername method.
  • This method returns a UserDetails object, 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!

Sıkça Sorulan Sorular

“Özel UserDetailsService Uygulaması” dersi ücretsiz mi?

Evet — “Özel UserDetailsService Uygulaması” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Spring Security 6 & JWT Authentication kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Spring Security 6 & JWT Authentication kursu toplamda 4 dersten oluşur.

“Özel UserDetailsService Uygulaması” dersinde ne öğreneceğim?

Kimlik doğrulama için uygulamanızın veri deposundan kullanıcıya özgü verileri yükleyen özel bir `UserDetailsService` oluşturun. Spring Security 6 & JWT Authentication ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Spring Security 6 & JWT Authentication öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Spring Security 6 & JWT Authentication, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Özel UserDetailsService Uygulaması” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Spring Security 6 & JWT Authentication dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Spring Security 6 & JWT Authentication dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Özel UserDetailsService Uygulaması
  2. Parola Kodlayıcılarını Anlama
  3. Veritabanı Kullanıcı Yönetimi Entegrasyonu
  4. Granted Authorities ile Role Dayalı Yetkilendirme
← Spring Security 6 & JWT Authentication Sayfasına Dön