Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between a Custom UserDetailsService and using in-memory authentication? कस्टम UserDetailsService और इन-मेमोरी ऑथेंटिकेशन में क्या अंतर है?

Answer

In-memory authentication defines a fixed set of users, passwords, and roles directly in configuration using InMemoryUserDetailsManager, which is useful only for demos, prototypes, or tests since users can't be added or changed without redeploying the application.

A custom UserDetailsService implementation loads user data from a real source, typically a database via a repository, overriding loadUserByUsername() to return a UserDetails object built from the stored user's credentials and authorities. This is the standard approach for any real application, since it allows dynamic user management and integrates with the rest of the persistence layer.

@Service
public class CustomUserDetailsService implements UserDetailsService {
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("Not found"));
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    }
}

इन-मेमोरी ऑथेंटिकेशन InMemoryUserDetailsManager का उपयोग करके कॉन्फिगरेशन में सीधे यूज़र्स, पासवर्ड और रोल्स का एक निश्चित सेट डिफाइन करता है, जो केवल डेमो, प्रोटोटाइप या टेस्ट के लिए उपयोगी है।

एक कस्टम UserDetailsService इम्प्लीमेंटेशन असली स्रोत से यूज़र डेटा लोड करता है, आमतौर पर रिपॉज़िटरी के ज़रिए डेटाबेस से, loadUserByUsername() को ओवरराइड करके एक UserDetails ऑब्जेक्ट रिटर्न करता है। यह किसी भी वास्तविक एप्लिकेशन के लिए मानक दृष्टिकोण है।

@Service
public class CustomUserDetailsService implements UserDetailsService {
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("Not found"));
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(), user.getPassword(), user.getAuthorities());
    }
}

Was this answer clear?