Beispiel #1
0
  @Override
  public String execute() throws Exception {
    userid = -1;
    HttpSession httpSession = ServletActionContext.getRequest().getSession();
    Cookie[] cookies = ServletActionContext.getRequest().getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("userid")) {
        userid = Integer.parseInt(cookie.getValue());
      }
      if (cookie.getName().equals("useremail")) {
        useremail = cookie.getValue();
      }
      if (cookie.getName().equals("usernick")) {
        usernike = Base64Util.decodeToString(cookie.getValue());
      }
    }

    if (userid == -1 || useremail == null || usernike == null) {
      return "session";
    } else {
      System.out.println(userid);
      list = UserInforDao.selectLoginInfor(userid);
      for (int i = 0; i < list.size(); i++) {
        list.get(i).setHostname(Base64Util.decodeToString(list.get(i).getHostname()));
      }
      size = list.size();
    }

    return SUCCESS;
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    try {
      int randNumber = java.security.SecureRandom.getInstance("SHA1PRNG").nextInt(99);
      String rememberMeKey = Integer.toString(randNumber);

      String user = "******";
      String fullClassName = this.getClass().getName();
      String testCaseNumber =
          fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
      user += testCaseNumber;

      String cookieName = "rememberMe" + testCaseNumber;

      boolean foundUser = false;
      javax.servlet.http.Cookie[] cookies = request.getCookies();
      for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
        javax.servlet.http.Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
          if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
            foundUser = true;
          }
        }
      }

      if (foundUser) {
        response.getWriter().println("Welcome back: " + user + "<br/>");
      } else {
        javax.servlet.http.Cookie rememberMe =
            new javax.servlet.http.Cookie(cookieName, rememberMeKey);
        rememberMe.setSecure(true);
        request.getSession().setAttribute(cookieName, rememberMeKey);
        response.addCookie(rememberMe);
        response
            .getWriter()
            .println(
                user
                    + " has been remembered with cookie: "
                    + rememberMe.getName()
                    + " whose value is: "
                    + rememberMe.getValue()
                    + "<br/>");
      }

    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing SecureRandom.nextInt(int) - TestCase");
      throw new ServletException(e);
    }
    response
        .getWriter()
        .println("Weak Randomness Test java.security.SecureRandom.nextInt(int) executed");
  } // end doPost
Beispiel #3
0
  private void checkCookies(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();

    HttpSession session = request.getSession();
    String session_cookie_username;

    if (session.getAttribute("logged_in_user") == null) {
      session_cookie_username = "";
    } else {
      session_cookie_username = (String) session.getAttribute("logged_in_user");
    }

    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (!(cookie.getName().equals("logged_in_user") || cookie.getName().equals("JSESSIONID"))) {
          new AppSensorIntrusion(
              new AppSensorException(
                  "SE2", "User adding new cookies", "User added ned cookie " + cookie.getName()));
        } else if (cookie.getName().equals("logged_in_user")) {
          if (!session_cookie_username.equals(cookie.getValue())) {
            new AppSensorIntrusion(
                new AppSensorException(
                    "SE4",
                    "User changing logincookie",
                    "User changed username in logincookie from "
                        + session_cookie_username
                        + " to "
                        + cookie.getValue()));
            session.setAttribute("logged_in_user", cookie.getValue());
          }
        }
      }
    }
  }
  /** initialize cookie data */
  private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        boolean isFind = false;

        if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
          textEMail.setText(cookie.getValue());
          isFind = true;
        }

        if (isFind) break;
      }
      for (Cookie cookie : cookies) {
        boolean isFind = false;
        if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
          btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
          isFind = true;
        }

        if (isFind) break;
      }
      for (Cookie cookie : cookies) {
        boolean isFind = false;
        if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
          comboLanguage.setText(cookie.getValue());
          changeUILocale();
          isFind = true;
        }

        if (isFind) break;
      }
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see org.mockito.ArgumentMatcher#matches(java.lang.Object)
  */
 @Override
 public boolean matches(final Object argument) {
   if (argument instanceof Cookie) {
     final Cookie givenCookie = (Cookie) argument;
     if (givenCookie.getSecure() == expectedCookie.getSecure()) {
       if (givenCookie.getMaxAge() == expectedCookie.getMaxAge()) {
         if (givenCookie.getName().equals(expectedCookie.getName())) {
           if (givenCookie.getPath() == expectedCookie.getPath()
               || givenCookie.getPath().equals(expectedCookie.getPath())) {
             if (givenCookie.getValue().equals(expectedCookie.getValue())) {
               if (givenCookie.getDomain() == expectedCookie.getDomain()
                   || givenCookie.getDomain().equals(expectedCookie.getDomain())) {
                 return true;
               }
             }
           }
         }
       }
     }
     Assert.fail(
         "Expected \n["
             + ToStringBuilder.reflectionToString(expectedCookie)
             + "]\n but got \n["
             + ToStringBuilder.reflectionToString(argument)
             + "]");
   }
   return false;
 }
Beispiel #6
0
  public void json(RequestInfoHttp reqInfo, String content, List<Cookie> cookies)
      throws IOException {

    if (cookies.size() > 0) {
      HttpServletResponse res = reqInfo.getRes();

      Cookie[] exists = reqInfo.getReq().getCookies();

      for (Cookie ck : cookies) {
        Cookie found = null;
        for (Cookie eck : exists) {
          if (eck.getName().equals(ck.getName())) {
            found = eck;
            break;
          }
        }
        if (found == null) {
          res.addCookie(ck);
        } else {
          found.setValue(ck.getValue());
          found.setMaxAge(ck.getMaxAge());
          found.setPath(ck.getPath());
          res.addCookie(found);
        }
      }
    }

    json(reqInfo, content);
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("vector");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = param;
    if (param != null && param.length() > 1) {
      StringBuilder sbxyz87271 = new StringBuilder(param);
      bar = sbxyz87271.replace(param.length() - "Z".length(), param.length(), "Z").toString();
    }

    double value = new java.util.Random().nextDouble();
    String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front.

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextDouble() executed");
  }
  public String[] getSessionHTML(HttpSession session, HttpServletRequest request)
      throws ServletException, IOException {

    String user = null;
    String group = null;
    String userName = null;
    String groupname = null;
    String redirect = "";
    try {

      redirect = UserRecord;
      if (session.getAttribute("user") == null) {

        session.invalidate();
        request.getRequestDispatcher(redirect).include(request, response);
      } else {
        user = (String) session.getAttribute("user");
        group = (String) session.getAttribute("group");
      }
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("user")) sess[0] = cookie.getValue();
          if (cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
          if (cookie.getName().equals("group")) sess[1] = cookie.getValue();
          break;
        }
      }

    } catch (NullPointerException n) {
      n.printStackTrace();
    }
    return sess;
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("vector");
    if (param == null) param = "";

    String bar = doSomething(param);

    byte[] bytes = new byte[10];
    new java.util.Random().nextBytes(bytes);
    String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(bytes, true);

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (int i = 0; !foundUser && i < cookies.length; i++) {
        javax.servlet.http.Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
          if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
            foundUser = true;
          }
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextBytes() executed");
  } // end doPost
  /**
   * Adds a cookie to the response.
   *
   * @param response The servlet response.
   * @param cookie The cookie to be sent.
   */
  private void addCookie(HttpServletResponse response, Cookie cookie) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "Adding cookie: "
              + cookie.getDomain()
              + cookie.getPath()
              + " "
              + cookie.getName()
              + "="
              + cookie.getValue());
    }
    // We don't use the container's response.addCookie, since the HttpOnly cookie flag was
    // introduced only recently
    // in the servlet specification, and we're still using the older 2.4 specification as a minimal
    // requirement for
    // compatibility with as many containers as possible. Instead, we write the cookie manually as a
    // HTTP header.
    StringBuilder cookieValue = new StringBuilder(150);
    cookieValue.append(cookie.getName() + "=");
    if (StringUtils.isNotEmpty(cookie.getValue())) {
      cookieValue.append("\"" + cookie.getValue() + "\"");
    }
    cookieValue.append("; Version=1");
    if (cookie.getMaxAge() >= 0) {
      cookieValue.append("; Max-Age=" + cookie.getMaxAge());
      // IE is such a pain, it doesn't understand the modern, safer Max-Age
      cookieValue.append("; Expires=");
      if (cookie.getMaxAge() == 0) {
        cookieValue.append(COOKIE_EXPIRE_NOW);
      } else {
        cookieValue.append(
            COOKIE_EXPIRE_FORMAT.format(
                new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L)));
      }
    }
    if (StringUtils.isNotEmpty(cookie.getDomain())) {
      // IE needs toLowerCase for the domain name
      cookieValue.append("; Domain=" + cookie.getDomain().toLowerCase());
    }
    if (StringUtils.isNotEmpty(cookie.getPath())) {
      cookieValue.append("; Path=" + cookie.getPath());
    }
    // Protect cookies from being used from JavaScript, see http://www.owasp.org/index.php/HttpOnly
    cookieValue.append("; HttpOnly");

    // Session cookies should be discarded.
    // FIXME Safari 5 can't handle properly "Discard", as it really discards all the response header
    // data after the
    // first "Discard" encountered, so it will only see the first such cookie. Disabled for the
    // moment until Safari
    // gets fixed, or a better idea comes to mind.
    // Since we don't set a Max-Age, the rfc2109 behavior will kick in, and recognize this as a
    // session cookie.
    // if (cookie.getMaxAge() < 0) {
    // cookieValue.append("; Discard");
    // }
    response.addHeader("Set-Cookie", cookieValue.toString());
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    java.util.Map<String, String[]> map = request.getParameterMap();
    String param = "";
    if (!map.isEmpty()) {
      String[] values = map.get("vector");
      if (values != null) param = values[0];
    }

    String bar = new Test().doSomething(param);

    float rand = new java.util.Random().nextFloat();
    String rememberMeKey = Float.toString(rand).substring(2); // Trim off the 0. at the front.

    String user = "******";
    String fullClassName = this.getClass().getName();
    String testCaseNumber =
        fullClassName.substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
    user += testCaseNumber;

    String cookieName = "rememberMe" + testCaseNumber;

    boolean foundUser = false;
    javax.servlet.http.Cookie[] cookies = request.getCookies();
    for (int i = 0; cookies != null && ++i < cookies.length && !foundUser; ) {
      javax.servlet.http.Cookie cookie = cookies[i];
      if (cookieName.equals(cookie.getName())) {
        if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
          foundUser = true;
        }
      }
    }

    if (foundUser) {
      response.getWriter().println("Welcome back: " + user + "<br/>");
    } else {
      javax.servlet.http.Cookie rememberMe =
          new javax.servlet.http.Cookie(cookieName, rememberMeKey);
      rememberMe.setSecure(true);
      request.getSession().setAttribute(cookieName, rememberMeKey);
      response.addCookie(rememberMe);
      response
          .getWriter()
          .println(
              user
                  + " has been remembered with cookie: "
                  + rememberMe.getName()
                  + " whose value is: "
                  + rememberMe.getValue()
                  + "<br/>");
    }

    response.getWriter().println("Weak Randomness Test java.util.Random.nextFloat() executed");
  } // end doPost
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    String exitParam = req.getParameter("exit");
    String deleteParam = req.getParameter("delete");
    String settingsParam = req.getParameter("settings");

    if ("settings".equals(settingsParam)) {
      resp.sendRedirect("/profileSettings");
      return;
    }

    if ("exit".equals(exitParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/login");
    }

    if ("delete".equals(deleteParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      try {
        UserRepository.deleteUser((User) session.getAttribute("user_a"));
      } catch (SQLException e) {
        req.setAttribute("message", "Some problems with server");
        resp.sendRedirect("/profile");

        e.printStackTrace();
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/welcome");
    }
  }
 protected void updateCookie(HttpServletRequest request, HttpServletResponse response) {
   Cookie[] cookies = request.getCookies();
   for (Cookie cookie : cookies) {
     if (cookie.getName() != null && cookie.getName().equals("Token")) {
       Logger.getGlobal().info("Token cookie value is: " + cookie.getValue());
       if (userService.isUserSessionByToken(cookie.getValue())) {
         this.makeCookie(cookie.getValue(), response);
       }
     }
   }
 }
  protected boolean thisCookieIsJsonByName(String name) {
    cookies = Arrays.asList(GenericCookie.request.getCookies());

    if (cookies != null && !cookies.isEmpty()) {
      for (Cookie cookie : cookies) {
        if (cookie.getName() != null && cookie.getName().equals(name)) {
          return Util.isJson(cookie.getValue());
        }
      }
    }
    return false;
  }
  private String getClientHash(Cookie[] cookies) {
    for (int i = 0; i < cookies.length; i++) {
      Cookie cookie = cookies[i];
      System.out.println("cookieName = " + cookie.getName());

      if (cookie.getName().equals("fypUserHash")) {
        System.out.println("returning = " + cookie.getValue());
        return (cookie.getValue());
      }
    }
    return null;
  }
Beispiel #16
0
  public Cookie getCookie(String name) {
    if (cookies == null) {
      logger.debug("Getting COOOOOOOOKEIESS:....");
      cookies = new HashMap<String, Cookie>();
      for (Cookie cookie : getCookies()) {
        logger.debug("COOKIE {} = {}", cookie.getName(), cookie.getValue());
        cookies.put(cookie.getName(), cookie);
      }
    }

    logger.debug("COOKIES: " + cookies);

    return cookies.get(name);
  }
Beispiel #17
0
 void loadCookies() {
   Cookie[] cookies = VaadinService.getCurrentRequest().getCookies();
   for (Cookie cookie : cookies) {
     if ("userLogin".equals(cookie.getName()) && cookie.getValue().isEmpty() == false) {
       this.userLogin = cookie.getValue();
     } else if ("userPass".equals(cookie.getName()) && cookie.getValue().isEmpty() == false) {
       this.userPass = cookie.getValue();
     } else if ("userId".equals(cookie.getName()) && cookie.getValue().isEmpty() == false) {
       this.userId = Integer.parseInt(cookie.getValue());
     }
   }
   if (this.userId > 0 && this.userLogin.isEmpty() == false && this.userPass.isEmpty() == false) {
     this.logged = true;
   }
 }
  /**
   * Render page contents.
   *
   * @param writer
   * @param cookies
   */
  private void renderPage(PrintWriter writer, Cookie[] cookies) {
    List<String[]> events = parseEvents();
    List<String> cities = parseCities(events), categories = parseCategories(events);
    String city = null, category = null;

    // Write header.
    appendHeader(writer);

    // If cookies are List, show monthly events.
    if (cookies != null) {
      // Check if city and category cookie existed and update values.
      for (Cookie cookie : cookies) {
        // If city cookie existed, modify city value.
        String name = cookie.getName();
        if (name.equalsIgnoreCase(CITY_PARAMETER_COOKIE_NAME)) {
          city = cookie.getValue();
        } else if (name.equalsIgnoreCase(CATEGORY_PARAMETER_COOKIE_NAME)) {
          category = cookie.getValue();
        }
      }
    }

    // Show input form.
    showInputForm(writer, cities, categories, city, category);

    // Show event table.
    showEventTable(writer, events, city, category);

    // Write footer.
    appendFooter(writer);
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = new Test().doSomething(param);

    new java.io.File(new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), bar);
  } // end doPost
Beispiel #20
0
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    Cookie[] cookies = request.getCookies();

    int userID = -1;
    boolean newUser = false;

    // determine whether we've seen this user before
    if (cookies != null) {
      for (Cookie c : cookies) {
        if (c.getName().equals("userID")) {
          userID = Integer.parseInt(c.getValue());
          logger.log(Level.INFO, "Existing user: "******"userID", String.valueOf(userID));
      response.addCookie(c);
      logger.log(Level.INFO, "New user: "******"text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();

    String title = "Cookie Servlet";
    String bootstrapHeader =
        "<!DOCTYPE html>"
            + "<html lang=\"en\">\n"
            + "	<head>\n"
            + "		<title>"
            + title
            + "</title>\n"
            + "		<meta charset=\"utf-8\">\n"
            + "		<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
            + "		<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\">\n"
            + "		<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>\n"
            + "		<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script>\n"
            + "	</head>\n";

    String body =
        "	<body>\n"
            + "		<div class=\"container\">\n"
            + "			<p>Hello, "
            + (newUser ? "new" : "existing")
            + " user!</p>\n"
            + "		</div>\n"
            + "	</body>\n";

    String footer = "</html>";

    String page = bootstrapHeader + body + footer;
    out.println(page);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie c : cookies) {
        System.out.println("cookie domain :" + c.getDomain());
        System.out.println("cookie path :" + c.getPath());
        System.out.println("cookie comment :" + c.getComment());

        System.out.println("cookie maxAge :" + c.getMaxAge());
        System.out.println("cookie version :" + c.getVersion());
        System.out.println("cookie name :" + c.getName());
        System.out.println("cookie value:" + c.getValue());
      }
    } else {
      System.err.println("不存在cookie");
    }

    // 创建cookie
    Cookie cookie = new Cookie("myCookie", "mycookieServlet");

    // 将cookie信息通知浏览器
    response.addCookie(cookie);
  }
 /**
  * Returns the {@link AuthenticationToken} for the request.
  *
  * <p>It looks at the received HTTP cookies and extracts the value of the {@link
  * AuthenticatedURL#AUTH_COOKIE} if present. It verifies the signature and if correct it creates
  * the {@link AuthenticationToken} and returns it.
  *
  * <p>If this method returns <code>null</code> the filter will invoke the configured {@link
  * AuthenticationHandler} to perform user authentication.
  *
  * @param request request object.
  * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
  * @throws IOException thrown if an IO error occurred.
  * @throws AuthenticationException thrown if the token is invalid or if it has expired.
  */
 protected AuthenticationToken getToken(HttpServletRequest request)
     throws IOException, AuthenticationException {
   AuthenticationToken token = null;
   String tokenStr = null;
   Cookie[] cookies = request.getCookies();
   if (cookies != null) {
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
         tokenStr = cookie.getValue();
         try {
           tokenStr = signer.verifyAndExtract(tokenStr);
         } catch (SignerException ex) {
           throw new AuthenticationException(ex);
         }
         break;
       }
     }
   }
   if (tokenStr != null) {
     token = AuthenticationToken.parse(tokenStr);
     if (!token.getType().equals(authHandler.getType())) {
       throw new AuthenticationException("Invalid AuthenticationToken type");
     }
     if (token.isExpired()) {
       throw new AuthenticationException("AuthenticationToken expired");
     }
   }
   return token;
 }
 public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) {
   for (int i = 0; i < cookies.length; i++) {
     Cookie cookie = cookies[i];
     if (cookieName.equals(cookie.getName())) return (cookie.getValue());
   }
   return (defaultValue);
 }
 public boolean checkForUserCookie(HttpServletRequest request, HttpServletResponse response) {
   // TODO just grab cookieValue from ThreadLocal because HttpSessionServletFilter already got it
   // for us
   Cookie[] cookies = request.getCookies();
   String cookieValue = null;
   if (cookies != null) {
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals(LoginController.USER_COOKIE_NAME)) {
         cookieValue = cookie.getValue();
         if (cookieValue != null && !cookieValue.equals("")) {
           logger.debug("Attempting login with cookie value = " + cookieValue);
           UserData userData = securityService.loginWithCookie(cookieValue);
           if (userData != null) {
             LoginController.saveUserInHttpSession(request, userData);
             logger.debug("Logged in using cookie, returning true");
             return true;
           } else {
             LogoutController.clearCookie(response);
           }
         }
         break;
       }
     }
   }
   return false;
 }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Map<String, Object> session = invocation.getInvocationContext().getSession();
    User user = (User) session.get("user");

    HttpServletRequest request =
        (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);

    if (user != null) {
      return invocation.invoke();
    } else {
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember-me")) {
            Map<String, String> loginParameters =
                Splitter.on('&').withKeyValueSeparator('=').split(cookie.getValue());
            UserDao userDao = new UserDaoImpl();
            user = userDao.loginUser(loginParameters.get("email"), loginParameters.get("password"));
            if (!loginParameters.get("password").equals(user.getPassword())) {
              return "login";
            } else {
              session.put("user", user);
              request.setAttribute("rememberMe", "true");
              return invocation.invoke();
            }
          }
        }
      }
      return "login";
    }
  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = new Test().doSomething(param);

    String sql = "UPDATE USERS SET PASSWORD='******' WHERE USERNAME='******'";

    try {
      java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
      int count = statement.executeUpdate(sql, new int[] {1, 2});
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
  /**
   * Create a new {@link TimestampFormatter}.
   *
   * @param systemTimeFormat the system clock time format
   * @param elapsedTimeFormat the elapsed time format
   * @param request the current HTTP request
   * @param timeZoneId the currently configured time zone
   */
  TimestampFormatter(
      String systemTimeFormat,
      String elapsedTimeFormat,
      Optional<? extends HttpServletRequest> request,
      Optional<String> timeZoneId) {

    String cookieValue = null;
    if (request.isPresent()) {
      Cookie[] cookies = request.get().getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if ("jenkins-timestamper".equals(cookie.getName())) {
            cookieValue = cookie.getValue();
            break;
          }
        }
      }
    }

    if ("elapsed".equalsIgnoreCase(cookieValue)) {
      formatTimestamp = new ElapsedTimeFormatFunction(elapsedTimeFormat);
    } else if ("none".equalsIgnoreCase(cookieValue)) {
      formatTimestamp = new EmptyFormatFunction();
    } else {
      // "system", no cookie, or unrecognised cookie
      formatTimestamp = new SystemTimeFormatFunction(systemTimeFormat, timeZoneId);
    }
  }
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   Cookie[] cookies = request.getCookies();
   boolean localeAlreadySetupInCookie = false;
   if (null != cookies) {
     Cookie cookie = null;
     for (int i = 0; i < cookies.length; i++) {
       cookie = cookies[i];
       if ((null != cookie) && COOKIENAME_LOCALE.equals(cookie.getName())) {
         localeAlreadySetupInCookie = true;
         break;
       }
     }
   }
   if (!localeAlreadySetupInCookie) {
     // if locale not setup in cookie,means first-time to request.
     String acceptLanuage = request.getHeader("Accept-Language");
     if (null != acceptLanuage) {
       if (acceptLanuage.toLowerCase().indexOf("zh") >= 0) {
         localeResolver.setLocale(request, response, Locale.SIMPLIFIED_CHINESE);
       }
     }
   }
   return true;
 }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    javax.servlet.http.Cookie[] cookies = request.getCookies();

    String param = null;
    boolean foundit = false;
    if (cookies != null) {
      for (javax.servlet.http.Cookie cookie : cookies) {
        if (cookie.getName().equals("foo")) {
          param = cookie.getValue();
          foundit = true;
        }
      }
      if (!foundit) {
        // no cookie found in collection
        param = "";
      }
    } else {
      // no cookies
      param = "";
    }

    String bar = param;
    if (param.length() > 1) {
      bar = param.substring(0, param.length() - 1);
    }

    response.getWriter().write(bar);
  }
Beispiel #30
0
  // greetMe will use session to return last called name
  public String greetMe(String me) {
    LOG.info("Executing operation greetMe");
    LOG.info("Message received: " + me);
    MessageContext mc = context.getMessageContext();
    HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
    Cookie cookies[] = req.getCookies();
    String val = "";
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        val += ";" + cookie.getName() + "=" + cookie.getValue();
      }
    }

    HttpSession session = req.getSession();
    // Get a session property "counter" from context
    if (session == null) {
      throw new WebServiceException("No session in WebServiceContext");
    }
    String name = (String) session.getAttribute("name");
    if (name == null) {
      name = me;
      LOG.info("Starting the Session");
    }

    session.setAttribute("name", me);

    return "Hello " + name + val;
  }