/* * (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; }
/** * 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); }
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 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; }
/** 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; } } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 登录界面login.jsp进入前判断是否已经登陆,是则直接跳转 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Cookie cookies[] = req.getCookies(); Cookie login = null; Cookie user = null; Cookie admin = null; // 1)判断cookie为空。2)cookie存在,但没有"loginName"。 // 3)cookie存在,但有"loginName",但loginName为null或0。 if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("LoginName")) { login = cookies[i]; } else if (cookies[i].getName().equals("superUser")) { user = cookies[i]; } else if (cookies[i].getName().equals("adminRight")) { admin = cookies[i]; } } } if (login != null && !login.getValue().equals("")) { if (admin != null && !admin.getValue().equals("")) { res.sendRedirect("/Login_Servlet/administrator/login/success.jsp"); } else if (user != null && !user.getValue().equals("")) { res.sendRedirect("/Login_Servlet/user/login/success.jsp"); } } else { chain.doFilter(request, response); } }
/** * 解压缩Cookie * * @param cookie Cookie * @throws IOException */ public static final void unCompressCookie(Cookie cookie) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (StringUtils.isEmpty(cookie.getValue())) { return; } byte[] compress = new BASE64Decoder().decodeBuffer(cookie.getValue()); InflaterInputStream iis = new InflaterInputStream(new ByteArrayInputStream(compress)); try { byte[] b = new byte[1024]; int count; while ((count = iis.read(b)) >= 0) { bos.write(b, 0, count); } iis.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (ObjectUtils.isNotNull(iis)) { try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } if (ObjectUtils.isNotNull(bos)) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
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()); } } } } }
@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"); }
@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
@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()); }
@Test public void testTrackClusterNewUser() throws Exception { // activate String serverId = getServerId(); Capture<String> serverIdCapture = new Capture<String>(); Capture<ClusterServerImpl> clusterServerCapture = new Capture<ClusterServerImpl>(); expect(serverTrackingCache.list()).andReturn(new ArrayList<Object>()).times(2); expect(serverTrackingCache.put(capture(serverIdCapture), capture(clusterServerCapture))) .andReturn(new Object()); // trackClusterUser HttpServletRequest request = createMock(HttpServletRequest.class); HttpServletResponse response = createMock(HttpServletResponse.class); Cookie cookieA = new Cookie("something", "someValue"); Cookie cookieB = new Cookie("somethingElse", "someOtherValue"); Cookie[] cookies = new Cookie[] {cookieA, cookieB}; expect(request.getCookies()).andReturn(cookies); expect(request.getRemoteUser()).andReturn("userid"); expect(response.isCommitted()).andReturn(false); Capture<Cookie> captureCookie = new Capture<Cookie>(); response.addCookie(capture(captureCookie)); expectLastCall(); response.addHeader("Cache-Control", "no-cache=\"set-cookie\" "); expectLastCall(); response.addDateHeader("Expires", 0); expectLastCall(); // deactivate serverTrackingCache.remove(serverId); replay(); clusterTrackingServiceImpl.activate(componentContext); clusterTrackingServiceImpl.trackClusterUser(request, response); clusterTrackingServiceImpl.deactivate(componentContext); assertTrue(serverIdCapture.hasCaptured()); assertEquals(serverId, serverIdCapture.getValue()); assertTrue(clusterServerCapture.hasCaptured()); ClusterServerImpl clusterServerImpl = clusterServerCapture.getValue(); assertEquals(serverId, clusterServerImpl.getServerId()); assertTrue(System.currentTimeMillis() >= clusterServerImpl.getLastModified()); // check the cookie assertTrue(captureCookie.hasCaptured()); Cookie cookie = captureCookie.getValue(); assertEquals("SAKAI-TRACKING", cookie.getName()); assertEquals("/", cookie.getPath()); assertEquals(-1, cookie.getMaxAge()); assertNotNull(cookie.getValue()); assertTrue(cookie.getValue().startsWith(serverId)); verify(); }
@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
/** * 从cookie中获取用户id * * @param request * @return */ protected String getSessionOperatorId(HttpServletRequest request) { String objId = null; Cookie cookie = CookieUtil.getInstance().getCookie(request, StaticSession.COOKIE_USERID); if (null != cookie && cookie.getValue() != null) { String cookieValue = cookie.getValue(); String[] values = cookieValue.split("_"); objId = DesUtil.getInstance().decryptStr(values[0]); } return objId; }
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); } } } }
private String getToken(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(false); if (!this.cookieLinksEnabled) { if (session == null) { return null; } return (String) session.getAttribute(SECURITY_TOKEN_SESSION_ATTR); } if (session != null) { final String tokenFromSession = (String) session.getAttribute(SECURITY_TOKEN_SESSION_ATTR); if (tokenFromSession != null) { Principal principal = this.tokenManager.getPrincipal(tokenFromSession); if (principal != null) { return tokenFromSession; } } } if (request.getCookies() != null && !request.isSecure()) { Cookie c = getCookie(request, VRTXLINK_COOKIE); if (logger.isDebugEnabled()) { logger.debug("Cookie: " + VRTXLINK_COOKIE + ": " + c); } if (c != null) { UUID id; try { id = UUID.fromString(c.getValue()); } catch (Throwable t) { if (logger.isDebugEnabled()) { logger.debug("Invalid UUID cookie value: " + c.getValue(), t); } return null; } String token = this.cookieLinkStore.getToken(request, id); if (token == null) { if (logger.isDebugEnabled()) { logger.debug("No token found from cookie " + VRTXLINK_COOKIE + ", deleting cookie"); } c = new Cookie(VRTXLINK_COOKIE, c.getValue()); c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } else { if (logger.isDebugEnabled()) { logger.debug("Found token " + token + " from cookie " + VRTXLINK_COOKIE); } session = request.getSession(true); session.setAttribute(SECURITY_TOKEN_SESSION_ATTR, token); return token; } } } return null; }
/** * Checks user credentials / automatic login. * * @param userSession The UserSession instance associated to the user's session * @return <code>true</code> if auto login was enabled and the user was sucessfuly logged in. * @throws DatabaseException */ protected boolean checkAutoLogin(UserSession userSession) { LOG.trace("checkAutoLogin"); String cookieName = SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA); Cookie cookie = this.getCookieTemplate(cookieName); Cookie hashCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH)); Cookie autoLoginCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN)); if (hashCookie != null && cookie != null && !cookie.getValue().equals(SystemGlobals.getValue(ConfigKeys.ANONYMOUS_USER_ID)) && autoLoginCookie != null && "1".equals(autoLoginCookie.getValue())) { String uid = cookie.getValue(); String uidHash = hashCookie.getValue(); // Load the user-specific security hash from the database try { UserDAO userDao = DataAccessDriver.getInstance().newUserDAO(); String userHash = userDao.getUserAuthHash(Integer.parseInt(uid)); if (userHash == null || userHash.trim().length() == 0) { return false; } String securityHash = MD5.crypt(userHash); if (securityHash.equals(uidHash)) { int userId = Integer.parseInt(uid); userSession.setUserId(userId); User user = userDao.selectById(userId); if (user == null || user.getId() != userId || user.isDeleted()) { userSession.makeAnonymous(); return false; } this.configureUserSession(userSession, user); return true; } } catch (Exception e) { throw new DatabaseException(e); } userSession.makeAnonymous(); } 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; }
private static HttpServletRequest processGenderCookie(HttpServletRequest request, Cookie cookie) { try { if (URLDecoder.decode(cookie.getValue(), "UTF-8").equalsIgnoreCase("agender")) { request.setAttribute("colors", NEUTRAL); } else { int gender = Integer.parseInt(URLDecoder.decode(cookie.getValue(), "UTF-8")); request.setAttribute( "colors", new ColorPalette(ColorBlender.blendPalette(BOY, GIRL, gender))); } } catch (NumberFormatException | UnsupportedEncodingException ex) { } return request; }
@RequestMapping(value = "/vote.jspx", method = RequestMethod.POST) public String submit( Integer voteId, Integer[] subIds, String[] reply, HttpServletRequest request, HttpServletResponse response, ModelMap model) { CmsSite site = CmsUtils.getSite(request); CmsUser user = CmsUtils.getUser(request); String ip = RequestUtils.getIpAddr(request); String cookieName = VOTE_COOKIE_PREFIX + voteId; Cookie cookie = CookieUtils.getCookie(request, cookieName); String cookieValue; if (cookie != null && !StringUtils.isBlank(cookie.getValue())) { cookieValue = cookie.getValue(); } else { cookieValue = null; } List<Integer[]> itemIds = getItemIdsParam(request, subIds); Integer[] subTxtIds = null; if (reply != null && reply.length > 0) { subTxtIds = new Integer[reply.length]; List<Integer> subTxtIdList = new ArrayList<Integer>(); for (int i = 0; i < itemIds.size(); i++) { if (itemIds.get(i) == null) { subTxtIdList.add(subIds[i]); } } // 投票文本选项和题目id数组对应相同大小 subTxtIds = (Integer[]) subTxtIdList.toArray(subTxtIds); } if (!validateSubmit(voteId, subIds, itemIds, user, ip, cookieValue, model)) { if (cookieValue == null) { // 随机cookie cookieValue = StringUtils.remove(UUID.randomUUID().toString(), "-"); // 写cookie CookieUtils.addCookie(request, response, cookieName, cookieValue, Integer.MAX_VALUE, null); } CmsVoteTopic vote = cmsVoteTopicMng.vote(voteId, subTxtIds, itemIds, reply, user, ip, cookieValue); model.addAttribute("status", 0); model.addAttribute("vote", vote); log.info("vote CmsVote id={}, name={}", vote.getId(), vote.getTitle()); } FrontUtils.frontData(request, model, site); return FrontUtils.getTplPath(request, site.getSolutionPath(), TPLDIR_SPECIAL, VOTE_RESULT); }
@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
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); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); Cookie requestCountCookie = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if ("requestCount".equals(cookies[i].getName())) { requestCountCookie = cookies[i]; break; } } } int count = 1; if (requestCountCookie == null) { requestCountCookie = new Cookie("requestCount", count + ""); } else { count = Integer.parseInt(requestCountCookie.getValue()); count++; } requestCountCookie.setValue(count + ""); requestCountCookie.setMaxAge(9999999); response.addCookie(requestCountCookie); PrintWriter out = response.getWriter(); out.println("<h1>Request Count : " + count + "</h1>"); }
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; }
/** * 检查验证码是否正确 * * @param req * @return */ public boolean validate(HttpServletRequest req) { Cookie cke = RequestUtils.getCookie(req, COOKIE_NAME); if (cke == null || StringUtils.isNotBlank(cke.getValue())) { return false; } String value = cke.getValue(); String code1 = null; try { code1 = CryptUtils.decrypt(value, key); } catch (Exception e) { return false; } String code2 = req.getParameter("verifyCode"); return StringUtils.equalsIgnoreCase(code1, code2); }
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); }
@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); }
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; }