Spring Security - AuthenticationSuccessHandler ClassCastException

时间:2017-03-12 05:44:46

标签: java spring spring-boot spring-security

我正在使用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);
  }
}

0 个答案:

没有答案