List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:com.netpace.vzdn.webapp.vzdninterceptors.SecurityInterceptor.java
public String getUserNameFromCookie(HttpServletRequest request, HttpServletResponse response) { try {//from w ww .j ava 2s . c o m SSOTokenManager stm = SSOTokenManager.getInstance(); Cookie[] requestCookies = request.getCookies(); String userName = ""; for (int i = 0; i < requestCookies.length; i++) { Cookie cookie = requestCookies[i]; if (cookie.getName().equals(VzdnConstants.OPENSSO_COOKIE)) { SSOToken st = stm.createSSOToken(request); userName = st.getPrincipal().getName(); userName = userName.substring(userName.indexOf("=") + 1, userName.indexOf(",")).toLowerCase(); System.out.println("got the cookie user name : " + userName); Cookie ssoCookie = new Cookie("loggedInUserInfo", userName); response.addCookie(ssoCookie); break; } } return userName; } catch (Exception ex) { log.error("Some issue in SecurityInterceptor while reading user info from cookie" + ex.getMessage()); ex.printStackTrace(); return null; } }
From source file:com.wavemaker.spinup.web.SpinupController.java
/** * Postback method from the login form. Will either re-direct back to the form (in the case of errors) or redirect * to start the spinup process./*w ww. j a v a 2s .com*/ * * @param credentials User credentials * @param bindingResult the binding result from the form * @param request the HTTP request * @param response the HTTP response * @return the response (either a redirect to the form or a redirect to the spinup process) */ @RequestMapping(value = "/login", method = RequestMethod.POST) public ModelAndView processLogin(@Valid LoginCredentialsBean credentials, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) { Assert.state(isAjaxRequest(request), "Unable to handle non AJAX post"); // If we have binding errors, re-render the page if (bindingResult.hasErrors()) { return new ModelAndView(); } try { // Login, add the cookie and redirect to start the spinup process this.logger.debug("Starting WaveMaker spinup"); SharedSecret secret = getSecret(request); TransportToken transportToken = this.spinupService.login(secret, credentials); this.logger.debug("Login complete"); String url = performSpinup(credentials, secret, transportToken, response); this.logger.debug("Perform spinup complete"); Cookie cookie = new Cookie(COOKIE_NAME, transportToken.encode()); cookie.setMaxAge(COOKIE_MAX_AGE); cookie.setDomain(this.spinupService.getDomain()); response.addCookie(cookie); response.setHeader("X-Ajax-Redirect", url); response.setStatus(HttpStatus.NO_CONTENT.value()); this.logger.debug("Wavemake spinup complete"); return null; } catch (InvalidLoginCredentialsException e) { // On invalid login redirect with a message in flash scope return new ModelAndView().addObject("message", "Unable to login, please check your credentials"); } }
From source file:net.prasenjit.auth.config.CustomAjaxAwareHandler.java
/** {@inheritDoc} */ @Override//from w ww. j a v a2 s .co m public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { request.setAttribute("javax.servlet.error.status_code", HttpServletResponse.SC_FORBIDDEN); request.setAttribute("org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.ERROR", accessDeniedException); if (accessDeniedException instanceof CsrfException && !response.isCommitted()) { // Remove the session cookie so that client knows it's time to obtain a new CSRF token String pCookieName = "CSRF-TOKEN"; Cookie cookie = new Cookie(pCookieName, ""); cookie.setMaxAge(0); cookie.setHttpOnly(false); cookie.setPath("/"); response.addCookie(cookie); } delegatedAccessDeniedHandler.handle(request, response, accessDeniedException); }
From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java
private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response, AuthnProcessorData data, SPEP spep) throws AuthenticationException { try {// w ww . j a v a 2s. c om String remoteAddress = request.getRemoteAddr(); this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress); String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response, data, spep); PrintStream out = new PrintStream(response.getOutputStream()); /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */ Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled"); autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT autoSubmit.setPath("/"); response.addCookie(autoSubmit); response.setStatus(HttpServletResponse.SC_OK); response.setHeader("Content-Type", "text/html"); out.print(document); out.close(); this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress); } catch (IOException e) { throw new AuthenticationException("Unable to send response due to an I/O error.", e); } }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { if (!isStarted()) return;//from w w w .j av a 2s . c o m // Only handle GET, HEAD and POST if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod()) && !HttpRequest.__POST.equals(request.getMethod())) return; log.debug("Dump"); response.setField(HttpFields.__ContentType, HttpFields.__TextHtml); OutputStream out = response.getOutputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(2048); Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1); writer.write("<HTML><H1>Dump HttpHandler</H1>"); writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath() + "\npathInContext=" + pathInContext + "\n</PRE>\n"); writer.write("<H3>Header:</H3><PRE>"); writer.write(request.toString()); writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>"); Set names = request.getParameterNames(); Iterator iter = names.iterator(); while (iter.hasNext()) { String name = iter.next().toString(); List values = request.getParameterValues(name); if (values == null || values.size() == 0) { writer.write(name); writer.write("=\n"); } else if (values.size() == 1) { writer.write(name); writer.write("="); writer.write((String) values.get(0)); writer.write("\n"); } else { for (int i = 0; i < values.size(); i++) { writer.write(name); writer.write("[" + i + "]="); writer.write((String) values.get(i)); writer.write("\n"); } } } String cookie_name = request.getParameter("CookieName"); if (cookie_name != null && cookie_name.trim().length() > 0) { String cookie_action = request.getParameter("Button"); try { Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal")); if ("Clear Cookie".equals(cookie_action)) cookie.setMaxAge(0); response.addSetCookie(cookie); } catch (IllegalArgumentException e) { writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>"); writer.write(e.toString()); LogSupport.ignore(log, e); } } writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>"); Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (int c = 0; c < cookies.length; c++) { Cookie cookie = cookies[c]; writer.write(cookie.getName()); writer.write("="); writer.write(cookie.getValue()); writer.write("\n"); } } writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>"); Enumeration attributes = request.getAttributeNames(); if (attributes != null && attributes.hasMoreElements()) { while (attributes.hasMoreElements()) { String attr = attributes.nextElement().toString(); writer.write(attr); writer.write("="); writer.write(request.getAttribute(attr).toString()); writer.write("\n"); } } writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>"); byte[] content = new byte[4096]; int len; try { InputStream in = request.getInputStream(); while ((len = in.read(content)) >= 0) writer.write(new String(content, 0, len)); } catch (IOException e) { LogSupport.ignore(log, e); writer.write(e.toString()); } // You wouldn't normally set a trailer like this, but // we don't want to commit the output to force trailers as // it makes test harness messy request.getAcceptableTransferCodings(); // commit now writer.flush(); response.setIntField(HttpFields.__ContentLength, buf.size() + 1000); buf.writeTo(out); out.flush(); // Now add the response buf.reset(); writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>"); writer.write(response.toString()); writer.write("</PRE></HTML>"); writer.flush(); for (int pad = 998 - buf.size(); pad-- > 0;) writer.write(" "); writer.write("\015\012"); writer.flush(); buf.writeTo(out); request.setHandled(true); }
From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { Map requestMap = HttpServletHelper.getInstance().createRequestMap(request); Map session = HttpServletHelper.getInstance().createSessionMap(request); Map application = HttpServletHelper.getInstance().createApplicationMap(request); ModelAndView returnedMv;/* w ww . j a va2 s . c om*/ if (controller instanceof CancelableController && ((CancelableController) controller).isCancel(requestMap)) { returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application, command, errors); } else { returnedMv = controller.handleRequest(command, requestMap, session, application, errors); } boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false); if (errors.hasErrors()) { logger.debug("Form submission errors: " + errors.getErrorCount()); HttpServletHelper.getInstance().reloadApplicationMap(request, application); HttpServletHelper.getInstance().reloadSessionMap(request, session); HttpServletHelper.getInstance().reloadRequestMap(request, requestMap); if (saveCookies) { Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes"); cookie.setMaxAge(30); cookie.setPath("/"); response.addCookie(cookie); } return showForm(request, response, errors); } if (returnedMv.getViewName() != null) { // should get from mappings String mappedView = (String) screenMappings.get(returnedMv.getViewName()); if (mappedView == null) { mappedView = returnedMv.getViewName(); } //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView); returnedMv = new ModelAndView(mappedView, returnedMv.getModel()); } //We have a successful save coming back, so we set/append to a cookie String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS); if (savedForm != null && saveCookies) { Cookie cookie = null; if (request.getCookies() != null) { for (Cookie c : request.getCookies()) { if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) { String[] forms = c.getValue().split(","); StringBuilder value = new StringBuilder(); boolean alreadyIncluded = false; for (String form : forms) { if (form.equals(savedForm)) { alreadyIncluded = true; } value.append(",").append(form); } if (!alreadyIncluded) { value.append(",").append(savedForm); } cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1)); } } } if (cookie == null) { cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm); } cookie.setMaxAge(2000000); cookie.setPath("/"); response.addCookie(cookie); } HttpServletHelper.getInstance().reloadApplicationMap(request, application); HttpServletHelper.getInstance().reloadSessionMap(request, session); HttpServletHelper.getInstance().reloadRequestMap(request, requestMap); return returnedMv; }
From source file:com.basicservice.controller.AdminController.java
private void prepareContext(Map map, HttpServletResponse response) { Map constants = service.getConstants(); String csrf_token = "<secret changing key>"; // use SecureRandom to generate a random token Locale locale = LocaleContextHolder.getLocale(); map.put("locale", locale.getLanguage()); map.put("constants", constants); if (response != null) { map.put("csrf_token", csrf_token); Cookie cookie = new Cookie(Constants.CSRF_COOKIE_NAME, csrf_token); cookie.setPath("/"); cookie.setMaxAge(-1);// w w w . ja v a 2 s. c om response.addCookie(cookie); } }
From source file:com.swdouglass.joid.consumer.OpenIdFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // basically just check for openId parameters HttpServletRequest request = (HttpServletRequest) servletRequest; if (servletRequest.getParameter(OPENID_ATTRIBUTE) != null && !ignored(request)) { try {//from w ww .ja va2 s . c o m @SuppressWarnings("unchecked") AuthenticationResult result = joid .authenticate(convertToStringValueMap(servletRequest.getParameterMap())); String identity = result.getIdentity(); if (identity != null) { HttpServletRequest req = (HttpServletRequest) servletRequest; req.getSession(true).setAttribute(OpenIdFilter.OPENID_ATTRIBUTE, identity); HttpServletResponse resp = (HttpServletResponse) servletResponse; // could check this before setting Cookie cookie = new Cookie(OPENID_ATTRIBUTE, identity); if (cookieDomain != null) { cookie.setDomain(cookieDomain); } if (cookieMaxAge != null) { cookie.setMaxAge(cookieMaxAge); } resp.addCookie(cookie); // redirect to get rid of the long url resp.sendRedirect(result.getResponse().getReturnTo()); return; } } catch (AuthenticationException e) { e.printStackTrace(); log.info("auth failed: " + e.getMessage()); // should this be handled differently? } catch (Exception e) { e.printStackTrace(); } } filterChain.doFilter(servletRequest, servletResponse); }
From source file:com.balero.controllers.LoginController.java
/** * Process user credentials/* ww w . j av a2 s .c om*/ * and sets the' magic' cookie * * @param baleroAdmin Magic credentials * @param response HTTP headers * @param request HTTP headers * @param redirectAttributes Pass to message center * @return View */ @RequestMapping(method = RequestMethod.POST) public String login(@CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin, HttpServletResponse response, HttpServletRequest request, RedirectAttributes redirectAttributes) { // Inputs String inputUsername = request.getParameter("inputUsername"); String inputPassword = request.getParameter("inputPassword"); // Debug logger.debug("param user: " + request.getParameter("inputUsername")); logger.debug("param pwd: " + request.getParameter("inputPassword")); logger.debug("cookie: " + baleroAdmin); // Init 'Users' List<Users> users; // Case switch (inputUsername) { // Admin case "admin": users = UsersDAO.administrator(); break; // Users default: users = UsersDAO.user(); } // Catch unregistered user try { if (users.isEmpty()) { throw new Exception("User do not exists!."); } } catch (Exception e) { redirectAttributes.addFlashAttribute("message", e.getMessage()); return "redirect:/"; } for (Users obj : users) { // Remote username = obj.getUsername(); password = obj.getPassword(); // Find register if (username.equals(inputUsername)) { if (password.equals(inputPassword)) { // create cookie and set it in response Cookie cookie = new Cookie("baleroAdmin", inputUsername + ":" + inputPassword); response.addCookie(cookie); logger.debug("Cookie Value: " + baleroAdmin); } else { redirectAttributes.addFlashAttribute("message", "Login failed! Wrong password."); } } } return "redirect:/"; }
From source file:com.pureinfo.tgirls.servlet.TestServlet.java
private void addCookie(User _loginUser, HttpServletRequest _request, HttpServletResponse _response) throws UnsupportedEncodingException { Cookie name = new Cookie(CookieUtils.NAME, URLEncoder.encode(_loginUser.getName(), "utf-8")); Cookie nickName = new Cookie(CookieUtils.NICK_NAME, URLEncoder.encode(_loginUser.getNickname(), "utf-8")); Cookie taobaoId = new Cookie(CookieUtils.TAOBAO_ID, URLEncoder.encode(_loginUser.getTaobaoID(), "utf-8")); Cookie img = new Cookie(CookieUtils.HEAD_IMG, URLEncoder.encode(_loginUser.getHeadImg(), "utf-8")); //Cookie topsession = new Cookie(CookieUtils.TOP_SESSION_ID, _request.getParameter(APPConstants.REQ_PARAMETER_SESSION)); //name.setPath("/"); //nickName.setPath(_request.getContextPath()); _response.addCookie(name);// ww w . j a v a2 s. c o m _response.addCookie(nickName); _response.addCookie(taobaoId); _response.addCookie(img); }