Spring Security Custom User Detail Service: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
No edit summary
Line 18: Line 18:
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
public interface UserDetailsService {
public interface UserDetailsService {
     UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
 
@Service
public class UserRepositoryUserDetailsService implements UserDetailsService {
 
  private UserRepository userRepository;
 
  @Autowired
  public UserRepositoryUserDetailsService(UserRepository userRepository) {
     this.userRepository = userRepository;
  }
 
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("\"" + username + "\" not found");
    }
    return user;
  }
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 20:29, 10 November 2018

Internal

Overview

This approach is useful for the situation in which the user information should be part of the application's domain model.

Combining application authentication and authorization with domain model user information largely consists in the following steps:

  • Declare a User entity that should implement the Spring UserDetails interface. Implementation of UserDetails provides essential user information to the framework, in a standard fashion (whether the account is enabled or not, authorities, etc.). Implementing UserInterface on a generic user domain model entity is the programmatic way of modifying the generic user entity to make it useful for authentication.
  • Declare the corresponding repository interface:
public interface UserRepository extends CrudRepository<User, Long> {
    User findByUsername(String username);
}
  • Declare a UserDetailsService interface and use it to implement a Spring @Service:
public interface UserDetailsService {
  UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

@Service
public class UserRepositoryUserDetailsService implements UserDetailsService {

  private UserRepository userRepository;

  @Autowired
  public UserRepositoryUserDetailsService(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("\"" + username + "\" not found");
    }
    return user;
  }
}

Playground Example

Playground - Spring Security - User Detail Service