title: org.springframework.security.core.userdetails.User cannot be cast to MyUser
body: <p>This is a spring security question.</p>
  
  <p>I want to be able to retrieve my custom User object object using </p>
  
  <pre><code>SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  </code></pre>
  
  <p>because I need additional details like user id and stuff for further business logic in my classes.  </p>
  
  <p>For this, I have a custom class derived from org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl where I've overriden loadUsersByUsername() to populate additional user fields and return an object of MyUser with the extra fields like user id etc.</p>
  
  <p>Code -</p>
  
  <pre><code>public class MyJdbcDaoImpl extends JdbcDaoImpl {
  
  @Override
  protected List&lt;UserDetails&gt; loadUsersByUsername(String username) {
      return getJdbcTemplate().query(getUsersByUsernameQuery(), new String[] {username}, new RowMapper&lt;UserDetails&gt;() {
          public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
              Long id = rs.getLong(1);
              String username = rs.getString(2);
              String password = rs.getString(3);
              boolean enabled = rs.getBoolean(4);
              MyUser user = new MyUser(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
              user.setId(id);
              return user;
          }
  
      });
  }
  }
  </code></pre>
  
  <p>My application context -</p>
  
  <pre><code>&lt;beans:bean id="myJdbcDaoImpl" class="package.MyJdbcDaoImpl"&gt;
          &lt;beans:property name="dataSource" ref="securityDB"/&gt;
          &lt;beans:property name="authoritiesByUsernameQuery" value="select username,role_id from app_user,user_role where app_user.id = user_role.user_id and username=?"/&gt;
          &lt;beans:property name="usersByUsernameQuery" value="select id,username,password,account_enabled from app_user where username = ?"/&gt;
  &lt;/beans:bean&gt;
  
  &lt;authentication-manager alias="authenticationManager"&gt;
  &lt;authentication-provider user-service-ref="myJdbcDaoImpl"&gt;
         &lt;password-encoder hash="sha"/&gt;
  &lt;/authentication-provider&gt;
  </code></pre>
  
  <p>The issue is, when I do a </p>
  
  <pre><code>MyUser user = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  </code></pre>
  
  <p>I get an exception 
      java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to package.MyUser</p>
  
  <p>What should I do to access my user object with additional fields from SecurityContextHolder?</p>
  
  <p>Thanks</p>