title: Spring Security @AuthenticationPrincipal
body: <p>I've been trying to get @AuthenticationPrincipal to work properly with a custom User class. Unfortunately, the user is always null. Here's the code:</p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>@RequestMapping(value = "/", method = RequestMethod.GET)
  public ModelAndView index(@AuthenticationPrincipal User user) {
      ModelAndView mav= new ModelAndView("/web/index");
      mav.addObject("user", user);
      return mav;
  }
  </code></pre>
  
  <p><strong>Security Config</strong></p>
  
  <pre><code>@Configuration
  @EnableWebMvcSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      CustomUserDetailsService customUserDetailsService;
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
      }
  </code></pre>
  
  <p>}</p>
  
  <p><strong>CustomUserDetailsService</strong></p>
  
  <pre><code>@Component
  public class CustomUserDetailsService implements UserDetailsService {
  
  @Autowired
  UserRepository userRepository;
  
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      // Spring Data findByXY function
      return userRepository.findByUsername(username);
  }
  </code></pre>
  
  <p><strong>User Entity</strong></p>
  
  <pre><code>public class User implements UserDetails{
      private String username;
      private String password;
      private Collection&lt;Authority&gt; authorities;
  
      // Getters and Setters
  
  }
  </code></pre>
  
  <p><strong>Authority Entity</strong></p>
  
  <pre><code>public class Authority implements GrantedAuthority{
      private User user;
      private String role;
  
      // Getters and Setters
  
      @Override
      public String getAuthority() {
          return this.getRole();
      }
  }
  </code></pre>
  
  <p>I've tried various solutions to this I found online, e.g. converting my custom user object like this:</p>
  
  <pre><code>return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), true, true, true, true,  authorities);
  </code></pre>
  
  <p>The other ways to get the active users are working without a problem, but I find the @AuthenticationProvider CustomUserObject to be the cleanest way, which is why I would like to get this to work. Any help is greatly appreciated.</p>