So I'm trying to save a user on to a "course" object that I created, but every time I try to save it I get the error org.springframework.security.core.userdetails.User cannot be cast to com.example.domain.User
I'm not sure where my problem is but I'm trying to get the principal and save it on to the course when it's submitted and I'm doing this inside the controller. When I run it in debug mode I can see that the principal is being populated with the correct user
If anyone can see where I'm going wrong and could point me in the right direction that would be awesome. Thanks in advance.
Here's my controller
@RequestMapping(value="createCourse", method=RequestMethod.GET)
public String createCourseGet (ModelMap model)
{
Course course = new Course();
model.put("course", course);
return "createCourse";
}
@RequestMapping(value="createCourse", method=RequestMethod.POST)
public String createCoursePost (@ModelAttribute Course course, Long userId, ModelMap model)
{
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = (User)auth.getPrincipal();
currentUser = userRepo.findOne(userId);
course.setUser(currentUser);
currentUser.getCourses().add(course);
courseRepo.save(course);
return "redirect:/courses";
}
Let me know if there's any other code that you would need to see in order to see the problem. Thanks.
UPDATE
Ok, so I now know that the principal and user aren't the same, and now I'm retrieving the principal name and setting it to the course, but the course wants a user id. Is it possible to now get the id from the user from what I have now?
@RequestMapping(value="createCourse", method=RequestMethod.POST)
public String createCoursePost (@ModelAttribute Course course, ModelMap model)
{
String name = SecurityContextHolder.getContext().getAuthentication().getName();
User user = this.userRepo.findByUsername(name);
course.setUser(user);
courseRepo.save(course);
return "redirect:/courses";
}