List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:com.bilko.controller.BlogController.java
private void initRoutes() throws IOException { get("/", new FreemarkerBasedRoute("blog_template.ftl") { @Override// w w w .ja v a2s. c o m public void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request)); final List<Document> posts = blogPostDao.findByDateDescending(10); final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); if (isNotBlank(username)) { root.put("username", username); } root.put("myposts", posts); template.process(root, writer); } }); get("/welcome", new FreemarkerBasedRoute("welcome.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request)); if (isBlank(username)) { System.out.println("welcome() CAN'T IDENTIFY THE USER, REDIRECTING TO signup"); response.redirect("/signup"); } else { final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("username", username); template.process(root, writer); } } }); get("/signup", new FreemarkerBasedRoute("signup.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); post("/signup", new FreemarkerBasedRoute("signup.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String email = request.queryParams("email"); final String username = request.queryParams("username"); final String password = request.queryParams("password"); final String verify = request.queryParams("verify"); final HashMap<String, String> root = new HashMap<String, String>() { { put("username", escapeHtml4(username)); put("email", escapeHtml4(email)); } }; if (validateSignup(username, password, verify, email, root)) { System.out.println("SIGNUP: CREATING USER WITH: " + username + " " + password); if (!userDao.addUser(username, password, email)) { root.put("username_error", "USERNAME ALREADY IN USE, PLEASE CHOOSE ANOTHER"); template.process(root, writer); } else { final String sessionId = sessionDao.startSession(username); System.out.println("SESSION ID IS: " + sessionId); response.raw().addCookie(new Cookie("session", sessionId)); response.redirect("/welcome"); } } else { System.out.println("USER REGISTRATION DIDN'T VALIDATE"); template.process(root, writer); } } }); get("/login", new FreemarkerBasedRoute("login.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); post("/login", new FreemarkerBasedRoute("login.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String username = request.queryParams("username"); final String password = request.queryParams("password"); final Document user = userDao.validateLogin(username, password); System.out.println("LOGIN: USER SUBMITTED: " + username + " " + password); if (user != null) { final String sessionId = sessionDao.startSession(user.get("_id").toString()); if (sessionId == null) { response.redirect("/internal_error"); } else { response.raw().addCookie(new Cookie("session", sessionId)); response.redirect("/welcome"); } } else { final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("username", escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); get("/newpost", new FreemarkerBasedRoute("newpost_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request)); if (isBlank(username)) { response.redirect("/login"); } else { SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("username", username); template.process(root, writer); } } }); post("/newpost", new FreemarkerBasedRoute("newpost_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String title = escapeHtml4(request.queryParams("subject")); final String post = escapeHtml4(request.queryParams("body")); final String tags = escapeHtml4(request.queryParams("tags")); final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request)); if (isBlank(username)) { response.redirect("/login"); } else if (isBlank(title) || isBlank(post)) { HashMap<String, String> root = new HashMap<String, String>() { { put("errors", "post must contain a title and blog entry."); put("subject", title); put("username", username); put("tags", tags); put("body", post); } }; template.process(root, writer); } else { final String permalink = blogPostDao.addPost(title, post.replaceAll("\\r?\\n", "<p>"), extractTags(tags), username); response.redirect("/post/" + permalink); } } }); get("/post/:permalink", new FreemarkerBasedRoute("entry_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String permalink = request.params(":permalink"); System.out.println("/post: GET " + permalink); final Document post = blogPostDao.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else { final SimpleHash comment = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); comment.put("name", ""); comment.put("email", ""); comment.put("body", ""); final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("post", post); root.put("comments", comment); template.process(root, writer); } } }); post("/newcomment", new FreemarkerBasedRoute("entry_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String name = escapeHtml4(request.queryParams("commentName")); final String email = escapeHtml4(request.queryParams("commentEmail")); final String body = escapeHtml4(request.queryParams("commentBody")); final String permalink = request.queryParams("permalink"); final Document post = blogPostDao.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else if (isBlank(name) || isBlank(body)) { final SimpleHash comment = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); comment.put("name", name); comment.put("email", email); comment.put("body", body); final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("comments", comment); root.put("post", post); root.put("errors", "POST MUST CONTAIN YOUR NAME AND AN ACTUAL COMMENT"); template.process(root, writer); } else { blogPostDao.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); } } }); get("/tag/:thetag", new FreemarkerBasedRoute("blog_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String username = sessionDao.findUserNameBySessionId(getSessionCookie(request)); final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); final String tag = escapeHtml4(request.params(":thetag")); final List<Document> posts = blogPostDao.findByTagDateDescending(tag); if (isNotBlank(username)) { root.put("username", username); } root.put("myposts", posts); template.process(root, writer); } }); get("/logout", new FreemarkerBasedRoute("signup.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final String sessionId = getSessionCookie(request); if (sessionId == null) { response.redirect("/login"); } else { sessionDao.endSession(sessionId); final Cookie cookie = getSessionCookieActual(request); if (cookie != null) { cookie.setMaxAge(0); response.raw().addCookie(cookie); response.redirect("/login"); } } } }); get("/post_not_found", new FreemarkerBasedRoute("post_not_found.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { template.process(new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())), writer); } }); get("/internal_error", new FreemarkerBasedRoute("error_template.ftl") { @Override protected void doHandle(final Request request, final Response response, final Writer writer) throws IOException, TemplateException { final SimpleHash root = new SimpleHash(new DefaultObjectWrapper(Configuration.getVersion())); root.put("error", "SYSTEM HAS ENCOUNTERED AN ERROR"); template.process(root, writer); } }); }
From source file:net.longfalcon.web.BaseController.java
protected void setCookies(User user, HttpServletResponse httpServletResponse) { long userId = user.getId(); String idh = EncodingUtil.sha1Hash(user.getUserseed() + String.valueOf(userId)); Cookie uidCookie = new Cookie("uid", String.valueOf(userId)); uidCookie.setMaxAge(2592000);/* w w w . ja va 2 s . com*/ Cookie idhCookie = new Cookie("idh", idh); idhCookie.setMaxAge(2592000); httpServletResponse.addCookie(uidCookie); httpServletResponse.addCookie(idhCookie); }
From source file:com.vmware.identity.SharedUtils.java
public static HttpServletRequest buildMockRequestObject(SignableSAMLObject samlObject, String relayStateParameter, String sigAlg, String signature, StringBuffer sbRequestUrl, String authorization, String sessionId, int tenantId) throws MarshallingException, IOException { Cookie[] expectedCookies = new Cookie[] {}; String tenant = ServerConfig.getTenant(tenantId); if (sessionId != null) { expectedCookies = new Cookie[] { new Cookie(Shared.getTenantSessionCookieName(tenant), sessionId) }; }//from w w w . ja v a2s.co m // build mock request object HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getCookies()).andReturn(expectedCookies).anyTimes(); if (samlObject instanceof LogoutResponse) { expect(request.getParameter(Shared.SAML_RESPONSE_PARAMETER)) .andReturn(SharedUtils.encodeRequest(samlObject)).anyTimes(); expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)).andReturn(null).anyTimes(); } else { expect(request.getHeader(Shared.IWA_AUTH_REQUEST_HEADER)).andReturn(null).anyTimes(); expect(request.getParameter(Shared.SAML_REQUEST_PARAMETER)) .andReturn(SharedUtils.encodeRequest(samlObject)).anyTimes(); expect(request.getParameter(Shared.SAML_RESPONSE_PARAMETER)).andReturn(null).anyTimes(); } expect(request.getParameter(Shared.RELAY_STATE_PARAMETER)).andReturn(relayStateParameter).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_ALGORITHM_PARAMETER)).andReturn(sigAlg).anyTimes(); expect(request.getParameter(Shared.SIGNATURE_PARAMETER)).andReturn(signature).anyTimes(); expect(request.getRequestURL()).andReturn(sbRequestUrl).anyTimes(); expect(request.getParameter(Shared.REQUEST_AUTH_PARAM)).andReturn(authorization).anyTimes(); String queryString = Shared.SAML_REQUEST_PARAMETER + "=" + SharedUtils.encodeRequest(samlObject); if (relayStateParameter != null) { queryString = queryString + "&" + Shared.RELAY_STATE_PARAMETER + "=" + relayStateParameter; } if (sigAlg != null) { queryString = queryString + "&" + Shared.SIGNATURE_ALGORITHM_PARAMETER + "=" + sigAlg; } if (signature != null) { queryString = queryString + "&" + Shared.SIGNATURE_PARAMETER + "=" + signature; } expect(request.getQueryString()).andReturn(queryString).anyTimes(); replay(request); return request; }
From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java
@Override public void destroySessions(final HttpServletRequest request, final HttpServletResponse response) { final String portalSessionId = this.getPortalSessionId(request); if (portalSessionId != null) { final SessionBucket sessionBucket = this.sessionBucketCache.remove(portalSessionId); sessionBucket.destroy();// w w w.java 2 s . c om final Cookie portalSessionCookie = new Cookie(IPortal.PORTAL_SESSION_ID_COOKIE_NAME, "SESSION_DESTROYED"); portalSessionCookie.setPath("/"); response.addCookie(portalSessionCookie); this.generatedSessionIds.remove(portalSessionId); } }
From source file:cn.org.once.cstack.config.SecurityConfiguration.java
/** * Filter CRSF to add XSFR-TOKEN between exchange * * @return/*from w w w . jav a 2 s . co m*/ */ private Filter csrfHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie("XSRF-TOKEN", token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; }
From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java
public XWikiUser checkAuth(XWikiContext context) throws XWikiException { Cookie cookie;/*from w ww.java 2 s .c om*/ LOG.debug("checkAuth"); LOG.debug("Action: " + context.getAction()); if (context.getAction().startsWith("logout")) { cookie = getCookie("XWIKINTLMAUTHINFO", context); if (cookie != null) { cookie.setMaxAge(0); context.getResponse().addCookie(cookie); } return null; } Principal principal = null; Cookie[] cookies = context.getRequest().getCookies(); if (cookies != null) { for (Cookie c : cookies) { LOG.debug("CookieList: " + c.getName() + " => " + c.getValue()); } } cookie = getCookie("XWIKINTLMAUTHINFO", context); if (cookie != null) { LOG.debug("Found Cookie"); String uname = decryptText(cookie.getValue(), context); if (uname != null) { principal = new SimplePrincipal(uname); } } String msg = context.getRequest().getHeader("Authorization"); if (msg != null) { LOG.debug("Found NTLM Auth Cookie, this could be an IE6 bug (#831167)"); if (msg.startsWith("NTLM ")) { LOG.debug("Removing principal because of NTLM header"); principal = null; } } XWikiUser user; // Authenticate if (principal == null) { principal = authenticate(null, null, context); if (principal == null) { LOG.debug("Can't get principal"); return null; } LOG.debug("Saving auth cookie"); String encuname = encryptText(principal.getName().contains(":") ? principal.getName() : context.getDatabase() + ":" + principal.getName(), context); Cookie usernameCookie = new Cookie("XWIKINTLMAUTHINFO", encuname); usernameCookie.setMaxAge(-1); usernameCookie.setPath("/"); context.getResponse().addCookie(usernameCookie); user = new XWikiUser(principal.getName()); } else { user = new XWikiUser(principal.getName().startsWith(context.getDatabase()) ? principal.getName().substring(context.getDatabase().length() + 1) : principal.getName()); } LOG.debug("XWikiUser=" + user); return user; }
From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME); logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr()); if (httpReq.getSession(false) == null) { chain.doFilter(request, response); return;// w ww .jav a2 s. com } logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list " + exclList.getExclusionMap()); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } // Check the user session for the salt cache, if none is present we // create one Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME); if (csrfPreventionSaltCache == null) { if (tokenTimeout == -1) { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build(); } else { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build(); } httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache); String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom()); httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt); } // Generate the salt and store it in the users cache String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom()); String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME); SecurityInfo si = new SecurityInfo(saltNameAttr, salt); if (SecurityTokenFilter.checkReferer) { String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer")); logger.debug("doFilter: refHeader=" + refHeader); if (StringUtils.isNotBlank(refHeader)) { try { URL refUrl = new URL(refHeader); refHeader = refUrl.getHost(); } catch (MalformedURLException mex) { logger.debug("doFilter: parsing referer header failed", mex); } } si.setRefererHost(refHeader); } logger.debug("doFilter: si=" + si.toString()); csrfPreventionSaltCache.put(si, si); // Add the salt to the current request so it can be used // by the page rendered in this request httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si); // set CSRF cookie HttpSession session = httpReq.getSession(false); if (session != null && StringUtils.isNotBlank(csrfCookieName)) { if (logger.isDebugEnabled()) { Cookie[] cookies = httpReq.getCookies(); // boolean cookiePresent = false; for (Cookie c : cookies) { String name = c.getName(); logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value=" + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly=" + c.isHttpOnly()); // if (csrfCookieName.equals(name)) { // cookiePresent = true; // break; // } } } // if (!cookiePresent) { byte[] hashSalt = new byte[32]; SecureRandom sr = new SecureRandom(); sr.nextBytes(hashSalt); String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr); Cookie c = new Cookie(csrfCookieName, csrfHash); c.setMaxAge(1800); c.setSecure(false); c.setPath(httpReq.getContextPath()); c.setHttpOnly(false); httpRes.addCookie(c); // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM, // hashStr); // } } chain.doFilter(request, response); }
From source file:com.haulmont.idp.controllers.IdpController.java
@GetMapping(value = "/logout") public String logout(@RequestParam(value = "sp", defaultValue = "") String serviceProviderUrl, @RequestParam(value = "response_type", defaultValue = "server-ticket") String responseType, @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie, HttpServletResponse response) {/*from w ww .jav a 2 s . c o m*/ if (!Strings.isNullOrEmpty(serviceProviderUrl) && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) { log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl); serviceProviderUrl = null; } if (Strings.isNullOrEmpty(serviceProviderUrl)) { if (!idpConfig.getServiceProviderUrls().isEmpty()) { serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0); } else { log.error("IDP property cuba.idp.serviceProviderUrls is not set"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); return null; } } if (!Strings.isNullOrEmpty(idpSessionCookie)) { boolean loggedOut = idpService.logout(idpSessionCookie); if (loggedOut) { log.info("Logged out IDP session {}", idpSessionCookie); logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie); } } // remove auth cookie Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, ""); cookie.setMaxAge(0); response.addCookie(cookie); if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) { return "redirect:login.html" + "?response_type=" + ResponseType.CLIENT_TICKET.getCode() + "&sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl); } return "redirect:login.html?sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl); }
From source file:com.hypersocket.session.json.SessionUtils.java
public void setLocale(HttpServletRequest request, HttpServletResponse response, String locale) { request.getSession().setAttribute(USER_LOCALE, locale); Cookie cookie = new Cookie(HYPERSOCKET_LOCALE, locale); cookie.setMaxAge(Integer.MAX_VALUE); cookie.setPath("/"); cookie.setSecure(request.getProtocol().equalsIgnoreCase("https")); cookie.setDomain(request.getServerName()); response.addCookie(cookie);//w w w.j a v a 2s . c o m }
From source file:com.persistent.cloudninja.controller.TenantTaskListController.java
@RequestMapping(value = "/logout.htm") public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) throws CloudNinjaException { if (cookie != null) { cookie = null;// ww w. j a v a 2s .c om Cookie c = new Cookie("CLOUDNINJAAUTH", null); c.setPath("/"); response.addCookie(c); response.setHeader("Cache-Control", "no-cache,no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", -1); } if (request.getAttribute("cookieNameAttr") != null) { request.setAttribute("cookieNameAttr", null); } return new ModelAndView("logoutsuccess"); }