title: Spring Security custom UserDetailsService and custom User class
body: <p>I am trying to save additional data in de user principal object.</p>
  
  <p>What i did was:</p>
  
  <p>implement the "UserDetails" interface to my existing user class where my additional data is saved ( like email address etc. ).</p>
  
  <pre><code>@Entity
  public class User implements UserDetails {
  </code></pre>
  
  <p>Then i created a UserDetailsService implementation:</p>
  
  <pre><code>@Service
  public class UserDetailsServiceImpl implements UserDetailsService {
  
      @Autowired
      UserDAO userDAO;
  
      @Override
      public UserDetails loadUserByUsername(String username)
              throws UsernameNotFoundException {
          User user = userDAO.findOneByUsername(username);
          if (user == null)
              throw new UsernameNotFoundException("username " + username
                      + " not found");
  
          System.out.println("---------------------&gt; FOUND -------------&gt;"
                  + user.getEmail());
  
          return user;
      }
  
  }
  </code></pre>
  
  <p>Last step was to add the UserDetailsService in my Security configuration.</p>
  
  <pre><code>@Configuration
  @EnableWebMvcSecurity
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
  @Autowired
  UserDetailsService userDetailsService;
  
  
  
  @Override
  protected void configure(AuthenticationManagerBuilder auth)
          throws Exception {
      auth.userDetailsService(userDetailsService());
  // ...
  
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.userDetailsService(userDetailsService());
  // ...
  }
  
  @Override
  protected UserDetailsService userDetailsService() {
      return userDetailsService;
  }
  </code></pre>
  
  <p>I see in my console that "loadUserByName" gets called twice ( because of the "Found" output ).</p>
  
  <p>When i try to access the principal object in my controller -></p>
  
  <pre><code>System.out.println(SecurityContextHolder.getContext()
                  .getAuthentication().getPrincipal());
  </code></pre>
  
  <p>I dont get my additional data.
  When i try to cast it to my User object i get a could not cast exception.</p>
  
  <p>Is there anything I am missing??</p>
  
  <p>Thank you in advance.</p>