예제 #1
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
  /**
   * Perform form authentication. Called from SecurityHandler.
   *
   * @return UserPrincipal if authenticated else null.
   */
  public Principal authenticate(
      UserRealm realm, String pathInContext, HttpRequest httpRequest, HttpResponse httpResponse)
      throws IOException {
    HttpServletRequest request = (ServletHttpRequest) httpRequest.getWrapper();
    HttpServletResponse response =
        httpResponse == null ? null : (HttpServletResponse) httpResponse.getWrapper();

    // Handle paths
    String uri = pathInContext;

    // Setup session
    HttpSession session = request.getSession(response != null);
    if (session == null) return null;

    // Handle a request for authentication.
    if (uri.substring(uri.lastIndexOf("/") + 1).startsWith(__J_SECURITY_CHECK)) {
      // Check the session object for login info.
      FormCredential form_cred = new FormCredential();
      form_cred.authenticate(
          realm,
          request.getParameter(__J_USERNAME),
          request.getParameter(__J_PASSWORD),
          httpRequest);

      String nuri = (String) session.getAttribute(__J_URI);
      if (nuri == null || nuri.length() == 0) {
        nuri = request.getContextPath();
        if (nuri.length() == 0) nuri = "/";
      }

      if (form_cred._userPrincipal != null) {
        // Authenticated OK
        if (log.isDebugEnabled()) log.debug("Form authentication OK for " + form_cred._jUserName);
        session.removeAttribute(__J_URI); // Remove popped return URI.
        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        httpRequest.setAuthUser(form_cred._jUserName);
        httpRequest.setUserPrincipal(form_cred._userPrincipal);
        session.setAttribute(__J_AUTHENTICATED, form_cred);

        // Sign-on to SSO mechanism
        if (realm instanceof SSORealm) {
          ((SSORealm) realm)
              .setSingleSignOn(
                  httpRequest,
                  httpResponse,
                  form_cred._userPrincipal,
                  new Password(form_cred._jPassword));
        }

        // Redirect to original request
        if (response != null) {
          response.setContentLength(0);
          response.sendRedirect(response.encodeRedirectURL(nuri));
        }
      } else if (response != null) {
        if (log.isDebugEnabled())
          log.debug("Form authentication FAILED for " + form_cred._jUserName);
        if (_formErrorPage != null) {
          response.setContentLength(0);
          response.sendRedirect(
              response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formErrorPage)));
        } else {
          response.sendError(HttpResponse.__403_Forbidden);
        }
      }

      // Security check is always false, only true after final redirection.
      return null;
    }

    // Check if the session is already authenticated.
    FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);

    if (form_cred != null) {
      // We have a form credential. Has it been distributed?
      if (form_cred._userPrincipal == null) {
        // This form_cred appears to have been distributed.  Need to reauth
        form_cred.authenticate(realm, httpRequest);

        // Sign-on to SSO mechanism
        if (form_cred._userPrincipal != null && realm instanceof SSORealm) {
          ((SSORealm) realm)
              .setSingleSignOn(
                  httpRequest,
                  httpResponse,
                  form_cred._userPrincipal,
                  new Password(form_cred._jPassword));
        }
      } else if (!realm.reauthenticate(form_cred._userPrincipal))
        // Else check that it is still authenticated.
        form_cred._userPrincipal = null;

      // If this credential is still authenticated
      if (form_cred._userPrincipal != null) {
        if (log.isDebugEnabled())
          log.debug("FORM Authenticated for " + form_cred._userPrincipal.getName());
        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        httpRequest.setAuthUser(form_cred._userPrincipal.getName());
        httpRequest.setUserPrincipal(form_cred._userPrincipal);
        return form_cred._userPrincipal;
      } else session.setAttribute(__J_AUTHENTICATED, null);
    } else if (realm instanceof SSORealm) {
      // Try a single sign on.
      Credential cred = ((SSORealm) realm).getSingleSignOn(httpRequest, httpResponse);

      if (httpRequest.hasUserPrincipal()) {
        form_cred = new FormCredential();
        form_cred._userPrincipal = request.getUserPrincipal();
        form_cred._jUserName = form_cred._userPrincipal.getName();
        if (cred != null) form_cred._jPassword = cred.toString();
        if (log.isDebugEnabled()) log.debug("SSO for " + form_cred._userPrincipal);

        httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
        session.setAttribute(__J_AUTHENTICATED, form_cred);
        return form_cred._userPrincipal;
      }
    }

    // Don't authenticate authform or errorpage
    if (isLoginOrErrorPage(pathInContext)) return SecurityConstraint.__NOBODY;

    // redirect to login page
    if (response != null) {
      if (httpRequest.getQuery() != null) uri += "?" + httpRequest.getQuery();
      session.setAttribute(
          __J_URI,
          request.getScheme()
              + "://"
              + request.getServerName()
              + ":"
              + request.getServerPort()
              + URI.addPaths(request.getContextPath(), uri));
      response.setContentLength(0);
      response.sendRedirect(
          response.encodeRedirectURL(URI.addPaths(request.getContextPath(), _formLoginPage)));
    }

    return null;
  }
예제 #3
0
 /**
  * Allows one to forward the following request and response using the request dispatcher.
  *
  * @param resource the resource to forward the request/response to.
  * @param request the http request to forward.
  * @param response the http response to forward.
  * @throws javax.servlet.ServletException
  * @throws java.io.IOException
  */
 protected void redirect(String resource, HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.sendRedirect(response.encodeRedirectURL(resource));
 }
예제 #4
0
  /**
   * Send a permanent redirect (HTTP status 301 "Moved Permanently") response with the given target
   * path.
   *
   * <p>The given target path may be relative or absolute. If it is relative, it will be resolved
   * against the request URL.
   *
   * @param targetPath the path to which the client is redirected.
   * @param req the HttpServletRequest
   * @param res the HttpServletResponse
   * @throws IOException if can't write the response.
   */
  public static void sendPermanentRedirect(
      String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // Absolute URL needed so resolve the target path against the request URL.
    URI uri;
    try {
      uri = new URI(req.getRequestURL().toString());
    } catch (URISyntaxException e) {
      log.error(
          "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e);
      log.info(
          "sendPermanentRedirect(): "
              + UsageLog.closingMessageForRequestContext(
                  HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }
    String absolutePath = uri.resolve(targetPath).toString();
    absolutePath = res.encodeRedirectURL(absolutePath);

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    res.addHeader("Location", absolutePath);

    String title = "Permanently Moved - 301";
    String body =
        new StringBuilder()
            .append("<p>")
            .append("The requested URL <")
            .append(req.getRequestURL())
            .append("> has been permanently moved (HTTP status code 301).")
            .append(" Instead, please use the following URL: <a href=\"")
            .append(absolutePath)
            .append("\">")
            .append(absolutePath)
            .append("</a>.")
            .append("</p>")
            .toString();
    String htmlResp =
        new StringBuilder()
            .append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag())
            .append("<head><title>")
            .append(title)
            .append("</title></head><body>")
            .append("<h1>")
            .append(title)
            .append("</h1>")
            .append(body)
            .append("</body></html>")
            .toString();

    log.info("sendPermanentRedirect(): redirect to " + absolutePath);
    log.info(
        "sendPermanentRedirect(): "
            + UsageLog.closingMessageForRequestContext(
                HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length()));

    // Write the catalog out.
    PrintWriter out = res.getWriter();
    res.setContentType("text/html");
    out.print(htmlResp);
    out.flush();
  }
  // The tck uses only get & post requests
  protected void processTCKReq(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.entering(LOG_CLASS, "servlet entry");

    PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request");
    PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response");
    PortletConfig portletConfig = (PortletConfig) request.getAttribute("javax.portlet.config");
    long svtTid = Thread.currentThread().getId();
    long reqTid = (Long) portletReq.getAttribute(THREADID_ATTR);

    PrintWriter writer = ((MimeResponse) portletResp).getWriter();

    JSR286DispatcherReqRespTestCaseDetails tcd = new JSR286DispatcherReqRespTestCaseDetails();

    // Create result objects for the tests

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_containsHeader */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.containsHeader must return false"     */
    TestResult tr0 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_CONTAINSHEADER);
    try {
      boolean ok = response.containsHeader("Accept");
      tr0.setTcSuccess(ok == false);
    } catch (Exception e) {
      tr0.appendTcDetail(e.toString());
    }
    tr0.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectURL1 */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeRedirectURL must return null"   */
    TestResult tr1 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL1);
    try {
      String isval = response.encodeRedirectURL("http://www.cnn.com/");
      CompareUtils.stringsEqual(isval, null, tr1);
    } catch (Exception e) {
      tr1.appendTcDetail(e.toString());
    }
    tr1.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeRedirectUrl */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeRedirectUrl must return null"   */
    TestResult tr2 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEREDIRECTURL);
    try {
      String isval = response.encodeRedirectUrl("http://www.cnn.com/");
      CompareUtils.stringsEqual(isval, null, tr2);
    } catch (Exception e) {
      tr2.appendTcDetail(e.toString());
    }
    tr2.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeURL1 */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeURL must provide the same       */
    /* functionality as ResourceResponse.encodeURL"                         */
    TestResult tr3 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL1);
    try {
      String turl = "http://www.apache.org/";
      String hval = (String) response.encodeURL(turl);
      String pval = (String) portletResp.encodeURL(turl);
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr3);
    } catch (Exception e) {
      tr3.appendTcDetail(e.toString());
    }
    tr3.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_encodeUrl */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.encodeUrl must provide the same       */
    /* functionality as ResourceResponse.encodeURL"                         */
    TestResult tr4 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ENCODEURL);
    try {
      String turl = "http://www.apache.org/";
      String hval = (String) response.encodeUrl(turl);
      String pval = (String) portletResp.encodeURL(turl);
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr4);
    } catch (Exception e) {
      tr4.appendTcDetail(e.toString());
    }
    tr4.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getBufferSize */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getBufferSize must provide the same   */
    /* functionality as ResourceResponse.getBufferSize"                     */
    TestResult tr5 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETBUFFERSIZE);
    try {
      int hval = response.getBufferSize();
      int pval = ((ResourceResponse) portletResp).getBufferSize();
      String str =
          "Value "
              + hval
              + " from "
              + "HttpServletResponse"
              + " does not equal value "
              + pval
              + " + ResourceResponse";
      if (hval != pval) {
        tr5.appendTcDetail(str);
      }
      tr5.setTcSuccess(hval == pval);
    } catch (Exception e) {
      tr5.appendTcDetail(e.toString());
    }
    tr5.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getCharacterEncoding */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getCharacterEncoding must provide     */
    /* the same functionality as ResourceResponse.getCharacterEncoding"     */
    TestResult tr6 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCHARACTERENCODING);
    try {
      String hval = response.getCharacterEncoding();
      String pval = ((ResourceResponse) portletResp).getCharacterEncoding();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr6);
    } catch (Exception e) {
      tr6.appendTcDetail(e.toString());
    }
    tr6.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getContentType */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getContentType must provide the       */
    /* same functionality as ResourceResponse.getContentType"               */
    TestResult tr7 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETCONTENTTYPE);
    try {
      String hval = response.getContentType();
      String pval = ((ResourceResponse) portletResp).getContentType();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr7);
    } catch (Exception e) {
      tr7.appendTcDetail(e.toString());
    }
    tr7.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_getLocale */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.getLocale must provide the same       */
    /* functionality as ResourceResponse.getLocale"                         */
    TestResult tr8 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_GETLOCALE);
    try {
      Locale hl = response.getLocale();
      Locale pl = ((MimeResponse) portletResp).getLocale();
      String hval = hl.getDisplayName();
      String pval = pl.getDisplayName();
      CompareUtils.stringsEqual("HttpServletResponse", hval, "ResourceResponse", pval, tr8);
    } catch (Exception e) {
      tr8.appendTcDetail(e.toString());
    }
    tr8.writeTo(writer);

    /* TestCase: V2DispatcherReqRespTests4_SPEC2_19_IncludeServletResourceResponse_isCommitted */
    /* Details: "In a target servlet of a include in the Resource phase,    */
    /* the method HttpServletResponse.isCommitted must provide the same     */
    /* functionality as ResourceResponse.isCommitted"                       */
    TestResult tr9 =
        tcd.getTestResultFailed(
            V2DISPATCHERREQRESPTESTS4_SPEC2_19_INCLUDESERVLETRESOURCERESPONSE_ISCOMMITTED);
    try {
      boolean hval = response.isCommitted();
      boolean pval = ((ResourceResponse) portletResp).isCommitted();
      String str =
          "Value "
              + hval
              + " from "
              + "HttpServletResponse"
              + " does not equal value "
              + pval
              + " + ResourceResponse";
      if (hval != pval) {
        tr9.appendTcDetail(str);
      }
      tr9.setTcSuccess(hval == pval);
    } catch (Exception e) {
      tr9.appendTcDetail(e.toString());
    }
    tr9.writeTo(writer);
  }
 private void sendRedirect(HttpServletResponse resp, String page)
     throws ServletException, IOException {
   resp.sendRedirect(resp.encodeRedirectURL(page));
 }