List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:hudson.security.SecurityRealm.java
/** * Handles the logout processing.//from www.j a v a 2s . c o m * * <p> * The default implementation erases the session and do a few other clean up, then * redirect the user to the URL specified by {@link #getPostLogOutUrl(StaplerRequest, Authentication)}. * * @since 1.314 */ public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { HttpSession session = req.getSession(false); if (session != null) session.invalidate(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.clearContext(); // reset remember-me cookie Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, ""); cookie.setMaxAge(0); cookie.setSecure(req.isSecure()); cookie.setHttpOnly(true); cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/"); rsp.addCookie(cookie); rsp.sendRedirect2(getPostLogOutUrl(req, auth)); }
From source file:com.sjc.cc.login.action.LoginAction.java
/** * CookieID//from ww w. j av a 2 s .c o m * * @param userId */ private void setCloudUserIdCookie(Long userId) { HttpServletResponse response = ServletActionContext.getResponse(); Cookie loginInfo = new Cookie(COOKIE_CC_USER_ID, userId + ""); loginInfo.setMaxAge(-1); if (logger.isDebugEnabled()) { logger.debug("The Cookie Cloud is :" + loginInfo + "," + loginInfo.getValue()); } response.addCookie(loginInfo); }
From source file:com.netspective.sparx.form.DialogContext.java
public void persistValuesToBrowser() { // clear the current cookie values -- the fieldStates.persistValues() will make calls to setClientPersistentValue() to set them cookieValues = new HashMap(); fieldStates.persistValues();// w ww . ja v a2 s .c o m if (cookieValues == null) return; StringBuffer cookieValue = new StringBuffer(); for (Iterator i = cookieValues.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); if (cookieValue.length() > 0) cookieValue.append("&"); cookieValue.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString())); } Cookie cookie = new Cookie(getDialog().getCookieName(), cookieValue.toString()); cookie.setMaxAge(60 * 60 * 24 * 365); // 1 year getHttpResponse().addCookie(cookie); }
From source file:com.salesmanager.checkout.flow.ComitOrderAction.java
/** * Process Payment Save Order entity//from ww w. j a v a2 s . com * * @return */ public String comitOrder() { // Get all entities Order order = SessionUtil.getOrder(getServletRequest()); MerchantStore store = SessionUtil.getMerchantStore(getServletRequest()); PaymentMethod payment = SessionUtil.getPaymentMethod(getServletRequest()); ShippingInformation shippingInformation = SessionUtil.getShippingInformation(getServletRequest()); Customer customer = SessionUtil.getCustomer(getServletRequest()); if (super.getServletRequest().getSession().getAttribute("TRANSACTIONCOMITED") != null) { addActionError(getText("error.transaction.duplicate", new String[] { String.valueOf(order.getOrderId()), store.getStoreemailaddress() })); return "GENERICERROR"; } OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService); try { SystemService sservice = (SystemService) ServiceFactory.getService(ServiceFactory.SystemService); long nextOrderId = sservice.getNextOrderIdSequence(); order.setOrderId(nextOrderId); OrderTotalSummary summary = SessionUtil.getOrderTotalSummary(getServletRequest()); Shipping shipping = null; if (shippingInformation != null) { shipping = new Shipping(); shipping.setHandlingCost(shippingInformation.getHandlingCost()); shipping.setShippingCost(shippingInformation.getShippingOptionSelected().getOptionPrice()); shipping.setShippingModule(shippingInformation.getShippingOptionSelected().getModule()); shipping.setShippingDescription(shippingInformation.getShippingOptionSelected().getDescription()); } Map orderProducts = SessionUtil.getOrderProducts(getServletRequest()); Set s = new HashSet(); for (Object o : orderProducts.values()) { OrderProduct op = (OrderProduct) o; s.add(op); } order.setOrderProducts(s); // ajust order object order.setCustomerEmailAddress(customer.getCustomerEmailAddress()); String comments = null; if (this.getOrderHistory() != null) { comments = this.getOrderHistory().getComments(); } // Order, PaymentMethod, ProcessorContext context = new ProcessorContext(); Collection files = oservice.getOrderProductDownloads(order.getOrderId()); if (files != null && files.size() > 0) { context.addObject("files", files); } context.addObject("Order", order); context.addObject("Customer", customer); context.addObject("MerchantStore", store); context.addObject("PaymentMethod", payment); context.addObject("Shipping", shipping); context.addObject("Locale", super.getLocale()); context.addObject("OrderTotalSummary", summary); context.addObject("comments", comments); context.addObject("products", orderProducts.values()); WorkflowProcessor wp = (WorkflowProcessor) SpringUtil.getBean("orderWorkflow"); wp.doWorkflow(context); // set an indicator in HTTPSession to prevent duplicates super.getServletRequest().getSession().setAttribute("TRANSACTIONCOMITED", "true"); if (!StringUtils.isBlank(comments)) { SessionUtil.setOrderStatusHistory(this.getOrderHistory(), getServletRequest()); } } catch (Exception e) { if (e instanceof TransactionException) { super.addErrorMessage("error.payment.paymenterror"); return "PAYMENTERROR"; } if (e instanceof OrderException) { try { oservice.sendOrderProblemEmail(order.getMerchantId(), order, customer, store); } catch (Exception ee) { log.error(ee); } } addActionError(getText("message.error.comitorder.error", new String[] { String.valueOf(order.getOrderId()), store.getStoreemailaddress() })); log.error(e); return "GENERICERROR"; } //cleanup //delete shopping cart cookie Cookie c = new Cookie(CatalogConstants.CART_COOKIE_NAME, ""); c.setMaxAge(0); super.getServletResponse().addCookie(c); return SUCCESS; }
From source file:contestWebsite.MainPage.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates"); ve.init();//from ww w . j a v a2 s. c o m VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (loggedIn && !userCookie.isAdmin()) { Entity contestInfo = infoAndCookie.x; String endDateStr = (String) contestInfo.getProperty("editEndDate"); String startDateStr = (String) contestInfo.getProperty("editStartDate"); Date endDate = new Date(); Date startDate = new Date(); try { endDate = new SimpleDateFormat("MM/dd/yyyy").parse(endDateStr); startDate = new SimpleDateFormat("MM/dd/yyyy").parse(startDateStr); } catch (ParseException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format"); } if (new Date().after(endDate) || new Date().before(startDate)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Registration editing deadline passed."); } else { Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id"))); Entity registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0); String studentData = req.getParameter("studentData"); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) infoAndCookie.x.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); registration.setProperty("studentData", new Text(studentData)); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } resp.sendRedirect("/?updated=1"); } } else if (loggedIn && userCookie.isAdmin()) { String username = req.getParameter("email").toLowerCase(); Query query = new Query("user") .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, username)); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() >= 1) { Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { query = new Query("authToken").setKeysOnly(); Filter tokenFilter = new FilterPredicate("token", FilterOperator.EQUAL, URLDecoder.decode(userCookie.getValue(), "UTF-8")); Filter expiredFilter = new FilterPredicate("expires", FilterOperator.LESS_THAN, new Date()); query.setFilter(CompositeFilterOperator.or(tokenFilter, expiredFilter)); datastore.delete( datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0).getKey()); userCookie.setMaxAge(0); userCookie.setValue(""); resp.addCookie(userCookie); SecureRandom random = new SecureRandom(); String authToken = new BigInteger(130, random).toString(32); Entity token = new Entity("authToken"); token.setProperty("user-id", username); token.setProperty("token", authToken); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 60); token.setProperty("expires", new Date(calendar.getTimeInMillis())); Cookie cookie = new Cookie("authToken", authToken); cookie.setValue(authToken); resp.addCookie(cookie); datastore.put(token); datastore.put(user); resp.sendRedirect("/"); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } else { resp.sendRedirect("/?error=1"); } } else { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation"); } }
From source file:com.vmware.identity.openidconnect.server.AuthenticationRequestProcessor.java
private Cookie loggedInSessionCookie(SessionID sessionId) { Cookie cookie = new Cookie(SessionManager.getSessionCookieName(this.tenant), sessionId.getValue()); cookie.setPath("/openidconnect"); cookie.setSecure(true);/* w w w . ja v a2 s. c o m*/ cookie.setHttpOnly(true); return cookie; }
From source file:com.funambol.transport.http.server.Sync4jServlet.java
/** * Processes the request/*from w w w . ja va 2 s. c om*/ * @param httpRequest the request * @param httpResponse the response * @throws javax.servlet.ServletException if an error occurs * @throws java.io.IOException if an error occurs */ @Override public void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException { if (log.isInfoEnabled()) { log.info("Handling incoming request"); } String requestURL = getRequestURL(httpRequest); String sessionId = getSessionId(httpRequest); String requestedSessionId = httpRequest.getRequestedSessionId(); if (log.isInfoEnabled()) { log.info("Request URL: " + requestURL); log.info("Requested sessionId: " + requestedSessionId); } if (log.isTraceEnabled()) { showHeaders(httpRequest); } httpResponse.setHeader(HEADER_X_FUNAMBOL_DS_SERVER, getServerHeader()); if (httpRequest.getSession().isNew()) { httpRequest.getSession().setMaxInactiveInterval(sessionTimeout); if (requestedSessionId != null && !requestedSessionId.equals("")) { if (!sessionId.equalsIgnoreCase(requestedSessionId)) { // // The client requires a session that maybe is already expired... // returing a 408 // if (log.isInfoEnabled()) { log.info("Session '" + requestedSessionId + "' not found"); } httpResponse.setStatus(HttpServletResponse.SC_REQUEST_TIMEOUT); return; } } } long requestTime = System.currentTimeMillis(); // // Setting the header 'Set-Cookie' in order to avoid the session tracking // using cookies. // // The web container adds a cookie JSESSIONID in order to // track the session, and to do that, it adds (transparently) in the response // header: // Set-Cookie: JSESSIONID=xxxxxxxxxx // In order not to use the cookie, the header "Set-Cookie" is set to an empty value // In this way, the session tracking is based on the jsessionid parameter // specified in the url (url rewriting). // The cookie is dangerous because a client could use: // http://xxxxxx:yyy/funambol/ds // but with a jsessionid specified as cookie. In this way, the server // search a previous session with the same id. And if a previous session // was interrupted and not expired, the server reuses this one and this // can cause an exception because the client sends the msg 1 and maybe // the previous session was in the mapping state. // // Unfortunatelly on Nokia S60 3Ed feature pack 1, the JAM is not able to // handle the response from the server if it contains an empty header Set-Cookie. // This means that to make the JAM working, we must avoid: // httpResponse.setHeader("Set-Cookie", ""); // and add a dummy cookie. // In order to do this in a generic way, we avoid empty Set-Cookie if in // the request is specified x-funambol-force-cookies header with value // 1 or yes or true // String x_funambol_force_cookies = httpRequest.getHeader(HEADER_X_FUNAMBOL_FORCE_COOKIES); if (!getBooleanValue(x_funambol_force_cookies)) { httpResponse.setHeader("Set-Cookie", ""); } else { // // Setting a dummy cookie // Cookie cookie = new Cookie("funambol-dummy-cookie", ""); httpResponse.addCookie(cookie); } final String contentType = httpRequest.getContentType().split(";")[0]; final String contentEncoding = (String) httpRequest.getHeader(HEADER_CONTENT_ENCODING); final String sizeThreshold = (String) httpRequest.getHeader(HEADER_SIZE_THRESHOLD); String acceptEncoding = (String) httpRequest.getHeader(HEADER_ACCEPT_ENCODING); if (!enableCompression) { // // In this way it's like the client doesn't support any encoding // if (acceptEncoding != null && acceptEncoding.length() != 0) { if (log.isTraceEnabled()) { log.trace("Forcing no compression (enable-compression is set to false)"); } acceptEncoding = null; } } Map params = getRequestParameters(httpRequest); Map headers = getRequestHeaders(httpRequest); byte[] requestData = null; try { requestData = getRequestContent(httpRequest, contentEncoding, requestTime, sessionId); if (requestData == null || requestData.length == 0) { handleError(httpRequest, httpResponse, "Received empty content. Returning a BAD REQUEST code to the client.", null); return; } } catch (Exception e) { handleError(httpRequest, httpResponse, "Error reading the request", e); return; } // // If the session id is not specified in the URL, a new remote object // will be created. Otherwise the session id specifies which remote // object shall handles the request. // SyncHolder holder = null; try { holder = createHolder(httpRequest.getSession()); } catch (Exception e) { handleError(httpRequest, httpResponse, "Error creating SyncBean", e); return; } String remoteAddress = httpRequest.getRemoteAddr(); // // We put the remote address in the header map so that we can pass it to // the adapted. // headers.put(HEADER_X_FUNAMBOL_CLIENT_REMOTE_ADDRESS, remoteAddress); SyncResponse resp = null; try { if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_WBXML.equals(contentType)) { resp = holder.processWBXMLMessage(requestURL, requestData, params, headers); } else if (com.funambol.framework.core.Constants.MIMETYPE_SYNCMLDS_XML.equals(contentType)) { resp = holder.processXMLMessage(requestURL, requestData, params, headers); } else { throw new ProtocolException("Mime type " + contentType + " not supported or unknown"); } } catch (Exception e) { log.error("Error processing the request", e); Throwable cause = e.getCause(); if ((cause != null) && ((cause instanceof ProtocolException) || (cause instanceof Sync4jException))) { handleError(httpRequest, httpResponse, "Protocol error", cause); return; } else { throw new ServletException(e); } } httpResponse.setContentType(contentType); setResponseContent(httpResponse, acceptEncoding, sizeThreshold, resp, requestTime, sessionId); if (log.isInfoEnabled()) { log.info("Request processed."); } // // If the message completed the SyncML communication, the session // must be closed and discarded. // if (resp.isCompleted()) { httpRequest.setAttribute(ATTRIBUTE_LAST_REQUEST, "true"); closeSession(httpRequest.getSession()); } }
From source file:com.activecq.experiments.redis.impl.RedisSessionUtilImpl.java
@Override public Cookie createSessionCookie() { final Cookie cookie = new Cookie(this.getSessionCookieName(), java.util.UUID.randomUUID().toString()); cookie.setPath("/"); cookie.setSecure(this.secureCookie); // Expire with browser session cookie.setMaxAge(-1);//from w w w . j a v a 2s . c o m return cookie; }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private RPSession processRequestInfo(HttpServletRequest request, HttpServletResponse response, boolean canLogin) { RPSession session = new RPSession(); session.isAdmin = false;/*from w w w .j a va 2 s .com*/ session.adminRole = false; session.isUWLogin = false; session.isProxy = false; String reloginPath = null; log.info("RP new session =============== path=" + request.getPathInfo()); session.isMobile = false; Device currentDevice = DeviceUtils.getCurrentDevice(request); if (currentDevice != null) session.isMobile = currentDevice.isMobile(); log.debug("mobile? " + session.isMobile); // see if logged in (browser has login cookie; cert user has cert) int resetAdmin = 1; // on expired or no cookie, reset the 'admin role cookei' Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(loginCookie)) { log.debug("got cookie " + cookies[i].getName()); String cookieStr = RPCrypt.decode(cookies[i].getValue()); if (cookieStr == null) continue; String[] cookieData = cookieStr.split(";"); if (cookieData.length == 5) { if (cookieData[3].charAt(0) == '2') session.authn2 = true; log.debug("login time = " + cookieData[4]); long cSec = new Long(cookieData[4]); long nSec = new Date().getTime() / 1000; if (cookieData[1].indexOf("@") < 0) session.isUWLogin = true; // klugey way to know UW people session.timeLeft = (cSec + standardLoginSec) - nSec; if (session.timeLeft > 0) { if ((nSec > (cSec + secureLoginSec)) && session.authn2) { log.debug("secure expired"); session.authn2 = false; resetAdmin = 2; } // cookie OK session.remoteUser = cookieData[1]; session.xsrfCode = cookieData[2]; log.debug("login for " + session.remoteUser); if (session.authn2) log.debug("secure login"); if (adminGroup.isMember(session.remoteUser)) { log.debug("is admin"); session.isAdmin = true; } if (resetAdmin == 1) resetAdmin = 0; } else { log.debug("cookie expired for " + cookieData[1]); // remember where they logged in last if (session.isUWLogin) reloginPath = browserRootPath + request.getServletPath() + standardLoginPath; else if (cookieData[1].indexOf("gmail.com") > 0) reloginPath = browserRootPath + request.getServletPath() + googleLoginPath; // let others choose } } } else if (cookies[i].getName().equals(roleCookie) && cookies[i].getValue().equals("a")) { log.debug("got role=admin cookie"); session.adminRole = true; } } } if (resetAdmin > 0) { log.debug("clearing expired admn request"); session.adminRole = false; Cookie c = new Cookie(roleCookie, "x"); c.setSecure(true); c.setPath("/"); response.addCookie(c); } if (session.remoteUser != null) { // ok, is a logged in browser session.viewType = "browser"; session.isBrowser = true; session.rootPath = browserRootPath; } else { // maybe is cert client // use the CN portion of the DN as the client userid X509Certificate[] certs = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if (certs != null) { session.viewType = "xml"; session.isBrowser = false; session.rootPath = certRootPath; X509Certificate cert = certs[0]; String dn = cert.getSubjectX500Principal().getName(); session.remoteUser = dn.replaceAll(".*CN=", "").replaceAll(",.*", ""); log.info(".. remote user by cert, dn=" + dn + ", cn=" + session.remoteUser); session.altNames = new Vector(); try { Collection altNames = cert.getSubjectAlternativeNames(); if (altNames != null) { for (Iterator i = altNames.iterator(); i.hasNext();) { List item = (List) i.next(); Integer type = (Integer) item.get(0); if (type.intValue() == 2) { String altName = (String) item.get(1); log.info(".. adding altname " + altName); session.altNames.add(altName); } } } else session.altNames.add(session.remoteUser); // rules say cn meaningful only when altnames not present } catch (CertificateParsingException e) { log.info(".. altname parse failed: " + e); } } } /* send missing remoteUser to login */ if (session.remoteUser == null) { if (canLogin) { if (reloginPath != null) { log.debug("no user yet: relogin at " + reloginPath); try { response.sendRedirect(reloginPath); } catch (IOException e) { log.error("redirect: " + e); } } log.debug("no user yet: send to choose"); session.mv = loginChooserMV(session, request, response); return session; } return null; } // only admins can get admin role if (!session.isAdmin) session.adminRole = false; if (session.adminRole && !session.authn2) { // admin needs 2f log.debug("need secure login for admin role"); sendToLogin(request, response, secureLoginPath); } session.servletPath = request.getServletPath(); session.remoteAddr = request.getRemoteAddr(); // etag headers session.ifMatch = getLongHeader(request, "If-Match"); session.ifNoneMatch = getLongHeader(request, "If-None-Match"); log.info("tags: match=" + session.ifMatch + ", nonematch=" + session.ifNoneMatch); log.info("user: " + session.remoteUser); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max_age=1"); response.setHeader("X-UA-Compatible", "IE=7"); log.info("user: " + session.remoteUser); if (session.viewType.equals("browser") && session.isMobile) session.viewType = "mobile"; return session; }
From source file:com.vmware.identity.openidconnect.server.LoginTest.java
@Test public void testLoginStringWithSessionCookieNonMatching() throws Exception { // if request has both a loginString and session cookie, then if the session cookie does not match, process the loginString String loginString = passwordLoginString(); Cookie nonMatchingsessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID + "_nonmatching"); Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, nonMatchingsessionCookie); ModelAndView modelView = result.getLeft(); MockHttpServletResponse response = result.getRight(); Assert.assertNull("modelView", modelView); validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, true, STATE, NONCE); }