我正在使用Spring Boot + Spring Security并尝试实现AuthenticationSuccessHandler
,以便应用程序可以为用户保存数据库的上次登录时间戳。
以下是我对代码的尝试。问题是我得到了一个类强制转换异常,因为它不喜欢我从User
转换为authentication
。
错误
java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.example.model.User
代码
@Component
public class SecurityHandler implements AuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
// Exception throw here during cast
User user = (User)authentication.getPrincipal();
user.setLastLogin(new Date());
userService.saveUser(user);
handle(request, response, authentication);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = "/dashboard";
redirectStrategy.sendRedirect(request, response, targetUrl);
}
}