title: Spring security get User object
body: <p>I have implemented user authentication through Spring Security Framework and everything works fine. I can log in and log out, I can get logged user name for example like this:</p>
  
  <pre><code>String userName = ((UserDetails) auth.getPrincipal()).getUsername();
  </code></pre>
  
  <p>Now i want to get user like an object from database(i need user id and other user properties).  </p>
  
  <p>This how i have tried so far:</p>
  
  <pre><code>User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  </code></pre>
  
  <p>Thereafter i got following exception:</p>
  
  <pre><code>Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to net.viralpatel.contact.model.User
  </code></pre>
  
  <p>Here is a question - how can i get User as object, how should i modify my classes UserDetailsServiceImpl and UserAssembler, any ideas?</p>
  
  <pre><code>@Component
  @Transactional
  public class UserDetailsServiceImpl implements UserDetailsService{
  
      @Autowired
      private UserDAO userDAO;
  
      @Autowired
      private UserAssembler userAssembler;
  
      private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
  
      @Transactional(readOnly = true)
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
          User user = userDAO.findByEmail(username);
  
          if(null == user) throw new UsernameNotFoundException("User not found");
          return userAssembler.buildUserFromUser(user);
      }
  }
  </code></pre>
  
  <p>And another one:</p>
  
  <pre><code>@Service("assembler")
  public class UserAssembler {
  
      @Autowired
      private UserDAO userDAO;
  
      @Transactional(readOnly = true)
      public User buildUserFromUser(net.viralpatel.contact.model.User user) {
          String role = "ROLE_USER";//userEntityDAO.getRoleFromUserEntity(userEntity);
  
          Collection&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;GrantedAuthority&gt;();
          authorities.add(new GrantedAuthorityImpl(role));
  
          return new User(user.getLogin(), user.getPassword(), true, true, true, true,  authorities);
      }
  }
  </code></pre>