protected String buildRedirectUrlToLoginPage(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authException) {

    String loginForm = determineUrlToUseForThisRequest(request, response, authException);

    if (UrlUtils.isAbsoluteUrl(loginForm)) {
      return loginForm;
    }

    int serverPort = portResolver.getServerPort(request);
    String scheme = request.getScheme();

    RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();

    urlBuilder.setScheme(scheme);
    urlBuilder.setServerName(request.getServerName());
    urlBuilder.setPort(serverPort);
    urlBuilder.setContextPath(request.getContextPath());
    urlBuilder.setPathInfo(loginForm);

    if (forceHttps && "http".equals(scheme)) {
      Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));

      if (httpsPort != null) {
        // Overwrite scheme and port in the redirect URL
        urlBuilder.setScheme("https");
        urlBuilder.setPort(httpsPort.intValue());
      } else {
        logger.warn(
            "Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);
      }
    }

    return urlBuilder.getUrl();
  }
  /**
   * Builds a URL to redirect the supplied request to HTTPS. Used to redirect the current request to
   * HTTPS, before doing a forward to the login page.
   */
  protected String buildHttpsRedirectUrlForRequest(HttpServletRequest request)
      throws IOException, ServletException {

    int serverPort = portResolver.getServerPort(request);
    Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));

    if (httpsPort != null) {
      RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
      urlBuilder.setScheme("https");
      urlBuilder.setServerName(request.getServerName());
      urlBuilder.setPort(httpsPort.intValue());
      urlBuilder.setContextPath(request.getContextPath());
      urlBuilder.setServletPath(request.getServletPath());
      urlBuilder.setPathInfo(request.getPathInfo());
      urlBuilder.setQuery(request.getQueryString());

      return urlBuilder.getUrl();
    }

    // Fall through to server-side forward with warning message
    logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);

    return null;
  }