0Pricing
Spring Security 6 & JWT Authentication · 강의

사용자 지정 UserDetailsService 구현

인증을 위해 애플리케이션의 데이터 저장소에서 사용자별 데이터를 불러오는 사용자 지정 `UserDetailsService`를 만듭니다.

사용자 지정 UserDetailsService 구현은(는) CoddyKit의 무료 Spring Security 6 & JWT Authentication 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Security 6 & JWT Authentication 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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!

자주 묻는 질문

“사용자 지정 UserDetailsService 구현” 강의는 무료인가요?

네 — “사용자 지정 UserDetailsService 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Security 6 & JWT Authentication 강의 전체를 잠금 해제할 수 있습니다. Spring Security 6 & JWT Authentication 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 지정 UserDetailsService 구현”에서 뭘 배우나요?

인증을 위해 애플리케이션의 데이터 저장소에서 사용자별 데이터를 불러오는 사용자 지정 `UserDetailsService`를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Security 6 & JWT Authentication을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Security 6 & JWT Authentication을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Security 6 & JWT Authentication은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“사용자 지정 UserDetailsService 구현” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Security 6 & JWT Authentication 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Security 6 & JWT Authentication 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 지정 UserDetailsService 구현
  2. 비밀번호 인코더 이해하기
  3. 데이터베이스 사용자 관리 통합
  4. Granted Authorities를 사용한 역할 기반 권한 부여
← Spring Security 6 & JWT Authentication(으)로 돌아가기