title: ClassCastException - Spring Security With User
body: <p>I'm currently making an E-Commerce application and I'm trying to add "Add To Cart" functionality. I haven't yet worked with httprequests, so everyone has to login before accessing the website.</p>
  
  <p>When a user logs in, goes onto the home page and tries to add a product to cart, it will send a post request to add that product. </p>
  
  <pre><code>    @PostMapping("/cart/{id}")
  public String addProduct(@PathVariable Long id, @ModelAttribute("cartItem") CartItems cartItem, Model model) {
      Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      User user = ((User) principal);
  
          Optional&lt;Product&gt; product = productService.findById(id);
          cartItem.setProduct(product.get());
          cartItem.setPrice(cartItem.getQuantity() * cartItem.getProduct().getPrice());
  
          user.getCart().getCartItems().add(cartItem);
  
          return "redirect:/cart";
     }
  </code></pre>
  
  <p>User Class:</p>
  
  <pre><code>@Entity
  @EntityListeners(AuditingEntityListener.class)
  @Table(name = "users")
  public class User implements Serializable, UserDetails 
  {
  
  private static final long serialVersionUID = -8903772563656397127L;
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "user_id")
  private Long id;
  
  @Column(name = "username")
  private String username;
  
  @Column(name = "email")
  private String email;
  
  @Column(name = "password")
  private String password;
  
  @Column(name = "first_name")
  private String firstName;
  
  @Column(name = "last_name")
  private String lastName;
  
  @OneToOne(mappedBy = "user")
  private Cart cart;
  
  @Column(name = "address")
  private String address;
  </code></pre>
  
  <p>USER DETAILS:</p>
  
  <pre><code>    @Override
  @Transactional
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      User user = userService.findByUsername(username);
  
      Set&lt;GrantedAuthority&gt; grantedAuthorities = new HashSet&lt;&gt;();
      grantedAuthorities.add(new SimpleGrantedAuthority("UNDEFINED"));
  
      return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
  }
  </code></pre>
  
  <p>The problem is casting the User class to Object principal from user details. I am getting the following error: </p>
  
  <p>java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.nickjojo.ecomapp.entity.User (org.springframework.security.core.userdetails.User and com.nickjojo.ecomapp.entity.User are in unnamed module of loader 'app')</p>