// Handler deciding where to redirect user after successful login
 @Bean
 public SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler() {
   SavedRequestAwareAuthenticationSuccessHandler successRedirectHandler =
       new SavedRequestAwareAuthenticationSuccessHandler();
   successRedirectHandler.setDefaultTargetUrl("/landing");
   return successRedirectHandler;
 }
    @Override
    public void onAuthenticationSuccess(
        HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
      DefaultSavedRequest defaultSavedRequest =
          (DefaultSavedRequest)
              request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY");

      if (defaultSavedRequest != null) {
        log.debug("saved url: " + defaultSavedRequest.getRedirectUrl());
        getRedirectStrategy().sendRedirect(request, response, defaultSavedRequest.getRedirectUrl());
      } else {
        super.onAuthenticationSuccess(request, response, authentication);
      }
    }
 @Override
 public void onAuthenticationSuccess(
     HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
   log.info("Usuário [" + authentication.getName() + "] autenticado com sucesso.");
   request.getSession().setAttribute("usuarioLogado", authentication.getDetails());
   try {
     super.onAuthenticationSuccess(request, response, authentication);
   } catch (ServletException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   } catch (IOException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   }
 }
  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws ServletException, IOException {
    Object principal = authentication.getPrincipal();
    IUserDetailsVOWrapper userDetailsVOWrapper =
        (principal instanceof IUserDetailsVOWrapper) ? (IUserDetailsVOWrapper) principal : null;
    UserDetailsVO userDetailsVO = userDetailsVOWrapper.getUserDetailsVO();
    if (userDetailsVO != null) {

      //			if (request.getServletContext().getFilterRegistration("areaFilter") != null) { // TODO
      //				AreaDetailsManager.setCurrAreaDetailsVO(request.getSession(),
      // AreaDetailsManager.getCityAreaDetailsVO(userDetailsVO.getAreaCd()));
      //			}

      //			userDetailsVO.setIp(HttpUtil.getRemoteAddr(request));
      //			userDetailsVO.setAdvertisingMedia(GlobalVars.getAdvertisingMedia(request));

      //			if (casAvailable) {
      //    			if (authentication instanceof CasAuthenticationToken) {
      //    				CasAuthenticationToken cat = (CasAuthenticationToken) authentication;
      ////    				userDetailsVO.setLoginAcctNo(cat.getAssertion().getPrincipal().getName());
      //    			} else if (authentication instanceof CasAssertionAuthenticationToken) {
      //    				CasAssertionAuthenticationToken casat = (CasAssertionAuthenticationToken)
      // authentication;
      ////    				userDetailsVO.setLoginAcctNo(casat.getAssertion().getPrincipal().getName());
      //    			}
      //			}
    }

    if ("ssoFrame".equalsIgnoreCase(request.getParameter("type"))) { // /loginCheck
      RequestCache requestCache =
          ReflectUtil.getFieldValue(this, "requestCache", RequestCache.class);
      SavedRequest savedRequest = requestCache.getRequest(request, response);
      if (savedRequest == null) {
        if (!response.isCommitted()) {
          String targetUrl = determineTargetUrl(request, response);
          DefaultRedirectStrategy redirectStrategy =
              (DefaultRedirectStrategy) this.getRedirectStrategy();
          String redirectUrl =
              (String)
                  ReflectUtil.invokeMethod(
                      redirectStrategy,
                      "calculateRedirectUrl",
                      new Object[] {request.getContextPath(), targetUrl});
          redirectUrl = response.encodeRedirectURL(redirectUrl);

          HttpSession session = request.getSession(true);
          String ssoAuto = (String) session.getAttribute("_SECURITY_SSO_AUTO"); // 自动登录
          if (Boolean.parseBoolean(ssoAuto)) {
            session.removeAttribute("_SECURITY_SSO_AUTO");
            String callbackUrl = (String) session.getAttribute("_SECURITY_SSO_CALLBACK_URL");
            session.removeAttribute("_SECURITY_SSO_CALLBACK_URL");

            redirectStrategy.sendRedirect(
                request, response, StringUtil.defaultIfBlank(callbackUrl, redirectUrl));
          } else {
            redirectStrategy.sendRedirect(
                request, response, ssoFrameTargetUrl + "?targetUrl=" + redirectUrl);
          }
        }

        clearAuthenticationAttributes(request);
      } else {
        requestCache.removeRequest(request, response);
        clearAuthenticationAttributes(request);
        this.getRedirectStrategy()
            .sendRedirect(
                request,
                response,
                ssoFrameTargetUrl + "?targetUrl=" + savedRequest.getRedirectUrl());
      }
    } else if (isAjaxRequest(request)) {
      this.onAuthenticationSuccessForAjax(request, response, authentication);
    } else {
      super.onAuthenticationSuccess(request, response, authentication);
    }

    EapContext.publish("#login.success", authentication);
  }
  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws ServletException, IOException {

    HttpSession httpSession = request.getSession();
    httpSession.setAttribute(COCKPIT_USER_KEY, authentication.getPrincipal());
    Object principal = authentication.getPrincipal();

    if (principal instanceof CockpitUser) {
      CockpitUser cockpitUser = (CockpitUser) principal;
      Login login = new Login();
      login.setCockpitUser(cockpitUser);
      login.setLoginTime(new Date());
      login.setToken(UUID.randomUUID().toString().replace("-", ""));
      httpSession.setAttribute(LoginConstant.TOKEN_IN_SESSION, login.getToken());
      httpSession.setAttribute(LoginConstant.HANDLE_IN_SESSION, cockpitUser.getUsername());

      if (null != cockpitUser.getCockpitRoles()
          && cockpitUser.getCockpitRoles().contains(CockpitRole.ROLE_ADMIN)) {
        httpSession.setAttribute(LoginConstant.IS_ADMIN_IN_SESSION, true);
        logger.info("Admin [" + cockpitUser.getUsername() + "] logs in");
      } else {
        httpSession.setAttribute(LoginConstant.IS_ADMIN_IN_SESSION, false);
        logger.info("User: [" + cockpitUser.getUsername() + "] logs in");
      }

      loginMapper.insert(login);
      logger.info(
          "Account {Team: "
              + cockpitUser.getTeam().getName()
              + ", Member: "
              + cockpitUser.getUsername()
              + "} logs in");

      httpSession.removeAttribute(LoginConstant.LOGIN_SESSION_ERROR_KEY);

      Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());
      cookie.setPath("/");
      cookie.setSecure(false);
      response.addCookie(cookie);

      Object redirectURL = httpSession.getAttribute(LoginConstant.REDIRECT_URL_IN_SESSION);
      if (null != redirectURL && redirectURL.toString().trim().length() > 0) {
        String redirect = URLDecoder.decode(redirectURL.toString(), "UTF-8");
        StringBuilder stringBuilder = new StringBuilder(redirect);
        if (!redirect.contains("?")) {
          stringBuilder.append("?");
        } else {
          stringBuilder.append("&");
        }
        stringBuilder.append("token=").append(login.getToken());
        // remove redirect url in session.
        httpSession.removeAttribute(LoginConstant.REDIRECT_URL_IN_SESSION);

        response.sendRedirect(stringBuilder.toString());
        return;
      }

    } else {
      logger.error("Fatal error, principal should be a CockpitUser or sub-class instance");
    }

    super.onAuthenticationSuccess(request, response, authentication);
  }