List of usage examples for javax.servlet.http Cookie getValue
public String getValue()
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;/*from w w w . ja va2s . c o m*/ 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.sg.rest.filters.LoggerFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { LOGGER.error(NON_HTTP_REQUEST + System.lineSeparator() + request.getInputStream().toString()); throw new RuntimeException(EXPECTING_AN_HTTP_REQUEST); }/*w ww .j av a 2 s . com*/ HttpServletRequest httpRequest = (HttpServletRequest) request; StringBuilder sb = new StringBuilder(); //General header sb.append(System.lineSeparator()); sb.append(INCOMING_REQUEST); //Request url sb.append(System.lineSeparator()); sb.append(REQUEST_URL); sb.append(httpRequest.getRequestURL()); //Method sb.append(System.lineSeparator()); sb.append(METHOD); sb.append(httpRequest.getMethod()); //Parameters if (httpRequest.getParameterNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(PARAMETERS); Enumeration enParams = httpRequest.getParameterNames(); while (enParams.hasMoreElements()) { sb.append(System.lineSeparator()); String paramName = (String) enParams.nextElement(); sb.append(paramName); sb.append(" : "); sb.append(httpRequest.getParameter(paramName)); } } //Attributes if (httpRequest.getAttributeNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(ATTRIBUTES); Enumeration enAttribs = httpRequest.getAttributeNames(); while (enAttribs.hasMoreElements()) { sb.append(System.lineSeparator()); String attribName = (String) enAttribs.nextElement(); sb.append(attribName); sb.append(" : "); sb.append(httpRequest.getAttribute(attribName)); } } //Headers if (httpRequest.getHeaderNames().hasMoreElements()) { sb.append(System.lineSeparator()); sb.append(HEADERS); Enumeration enHeaders = httpRequest.getHeaderNames(); while (enHeaders.hasMoreElements()) { sb.append(System.lineSeparator()); String headerName = (String) enHeaders.nextElement(); sb.append(headerName); sb.append(" : "); sb.append(httpRequest.getHeader(headerName)); } } //AuthType if (httpRequest.getAuthType() != null && !httpRequest.getAuthType().isEmpty()) { sb.append(System.lineSeparator()); sb.append(AUTH_TYPE); sb.append(httpRequest.getAuthType()); } //Cookies if (httpRequest.getCookies() != null && httpRequest.getCookies().length > 0) { sb.append(System.lineSeparator()); sb.append(COOKIES); for (Cookie cookie : httpRequest.getCookies()) { sb.append(System.lineSeparator()); sb.append(cookie.getName()); sb.append(" : "); sb.append(cookie.getValue()); } } //RemoteAddr if (httpRequest.getRemoteAddr() != null && !httpRequest.getRemoteAddr().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_ADDR); sb.append(httpRequest.getRemoteAddr()); } //RemoteHost if (httpRequest.getRemoteHost() != null && !httpRequest.getRemoteHost().isEmpty()) { sb.append(System.lineSeparator()); sb.append(REMOTE_HOST); sb.append(httpRequest.getRemoteHost()); } //User principal if (httpRequest.getUserPrincipal() != null) { if (httpRequest.getUserPrincipal().getName() != null && !httpRequest.getUserPrincipal().getName().isEmpty()) { sb.append(System.lineSeparator()); sb.append(PRINCIPAL); sb.append(httpRequest.getUserPrincipal().getName()); } } //Body ResettableStreamHttpServletRequest wrappedRequest = new ResettableStreamHttpServletRequest( (HttpServletRequest) request); String body = IOUtils.toString(wrappedRequest.getReader()); if (body != null && !body.isEmpty()) { sb.append(System.lineSeparator()); sb.append(BODY); sb.append(System.lineSeparator()); sb.append(body); } wrappedRequest.resetInputStream(); LOGGER.info(sb.toString()); chain.doFilter(wrappedRequest, response); }
From source file:eu.eidas.node.AbstractNodeServlet.java
/** * Sets HTTPOnly Header on the session to prevent cookies from being accessed through * client-side script./* w ww . jav a 2s. c o m*/ * * @param renewSession indicates that the session cookie will be renewed */ protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request, HttpServletResponse response) { if (request != null && request.getSession(false) != null) { // Renewing the session if necessary String currentSession = null; String messageLog = null; if (renewSession) { currentSession = sessionIdRegenerationInWebApp(request); messageLog = "http session Renewed : {}"; } else { currentSession = request.getSession().getId(); messageLog = "http session obtained from request : {}"; } MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession); getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession); // changing session cookie to http only cookie if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) { //Session Id requested by the client, obtained from the cookie final String requestedSessionId = request.getRequestedSessionId(); for (Cookie cookie : request.getCookies()) { getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]", cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue()); if (currentSession.equals(requestedSessionId)) { // Removes old version boolean isSecure = request.isSecure(); getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}", cookie.toString()); getLogger().debug("Is using SSL?", isSecure); //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header // //NOSONAR cookie.setMaxAge(0); //NOSONAR cookie.setPath(getServletContext().getContextPath()); //NOSONAR cookie.setDomain(request.getServerName()); //NOSONAR cookie.setSecure(isSecure); //NOSONAR cookie.setHttpOnly(true); //NOSONAR response.addCookie(cookie); // Create new one httpOnly StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName()) .append(EIDASValues.EQUAL.toString()).append(cookie.getValue()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString()) .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString()) .append(" ").append(EIDASValues.PATH.toString()) .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString()) .append(isSecure ? EIDASValues.SECURE.toString() : ""); response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString()); } } } //cookie _csrf // request.setAttribute("_csrf_header", "X-CSRF-TOKEN"); // UUID idOne = UUID.randomUUID(); // LOG.info("generate csrf id="+idOne); // request.setAttribute("_csrf", idOne); response.setHeader("_csrf_header", "X-CSRF-TOKEN"); UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo); Cookie gato = new Cookie("_csrf", idOne.toString()); response.addCookie(gato); response.setHeader("X-CSRF-TOKEN", idTwo.toString()); } else { getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !"); } }
From source file:org.iwethey.forums.web.HeaderInterceptor.java
/** * Load the request attributes with the User object (if authenticated) * and start time for the page for audit purposes. * <p>/*from w ww.jav a 2 s . c o m*/ * @param request The servlet request object. * @param response The servlet response object. * @param handler The request handler processing this request. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Date now = new Date(); request.setAttribute("now", now); long start = now.getTime(); request.setAttribute("start", new Long(start)); Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE); User user = null; if (id == null) { user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE); if (user == null) { user = new User("Anonymous"); WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user); } } else { user = mUserManager.getUserById(id.intValue()); user.setLastPresent(new Date()); mUserManager.saveUserAttributes(user); } request.setAttribute("username", user.getNickname()); request.setAttribute(USER_ATTRIBUTE, user); System.out.println("Local Address = [" + request.getLocalAddr() + "]"); System.out.println("Local Name = [" + request.getLocalName() + "]"); System.out.println("Remote Address = [" + request.getRemoteAddr() + "]"); System.out.println("Remote Host = [" + request.getRemoteHost() + "]"); System.out.println("Remote Port = [" + request.getRemotePort() + "]"); System.out.println("Remote User = [" + request.getRemoteUser() + "]"); System.out.println("Context Path = [" + request.getContextPath() + "]"); System.out.println("===================="); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("Cookie Domain = [" + cookie.getDomain() + "]"); System.out.println("Cookie Name = [" + cookie.getName() + "]"); System.out.println("Cookie Value = [" + cookie.getValue() + "]"); System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]"); System.out.println("===================="); if ("iwt_cookie".equals(cookie.getName())) { cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(cookie); } } } else { System.out.println("No cookies were found in the request"); } Cookie newCookie = new Cookie("iwt_cookie", "harrr2!"); newCookie.setPath(request.getContextPath()); newCookie.setDomain(request.getLocalName()); newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(newCookie); request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png"); return true; }
From source file:org.apache.archiva.redback.integration.util.AutoLoginCookies.java
public AuthenticationKey getSignonKey(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) { Cookie ssoCookie = getCookie(httpServletRequest, SIGNON_KEY); if (ssoCookie == null) { log.debug("Single Sign On Cookie Not Found: {}", SIGNON_KEY); return null; }/*from ww w . j a v a 2 s . c o m*/ // Found user with a single sign on key. String providedKey = ssoCookie.getValue(); log.debug("Found sso cookie : {}", providedKey); CookieSettings settings = securitySystem.getPolicy().getSignonCookieSettings(); return findAuthKey(SIGNON_KEY, providedKey, settings.getDomain(), settings.getPath(), httpServletResponse, httpServletRequest); }
From source file:com.sunrun.crportal.util.CRPortalUtil.java
public static String getValueFromCookies(HttpServletRequest request, String cookieName) { String cookieValue = ""; Cookie[] cookieArray = request.getCookies(); if (cookieArray != null) { for (int i = 0; i < cookieArray.length; i++) { Cookie aCookie = cookieArray[i]; if (cookieName.equals(aCookie.getName())) { cookieValue = aCookie.getValue(); }//from w w w. j a v a 2 s.co m } } return cookieValue; }
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;//from w ww .jav a 2 s. c o m } 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.google.gerrit.httpd.ProjectOAuthFilter.java
private AuthInfo extractAuthInfo(Cookie cookie) throws UnsupportedEncodingException { String username = URLDecoder.decode(cookie.getName().substring(GIT_COOKIE_PREFIX.length()), UTF_8.name()); String value = cookie.getValue(); int splitPos = value.lastIndexOf('@'); if (splitPos < 1 || splitPos == value.length() - 1) { // no providerId in the cookie value => assume default provider // note: a leading/trailing at sign is considered to belong to // the access token rather than being a separator return new AuthInfo(username, cookie.getValue(), defaultAuthPlugin, defaultAuthProvider); }// w ww . j av a 2s . co m String token = value.substring(0, splitPos); String providerId = value.substring(splitPos + 1); splitPos = providerId.lastIndexOf(':'); if (splitPos < 1 || splitPos == providerId.length() - 1) { // no colon at all or leading/trailing colon: malformed providerId return null; } String pluginName = providerId.substring(0, splitPos); String exportName = providerId.substring(splitPos + 1); OAuthLoginProvider provider = loginProviders.get(pluginName, exportName); if (provider == null) { return null; } return new AuthInfo(username, token, pluginName, exportName); }
From source file:fr.gael.dhus.server.http.valve.AccessValve.java
/** * Logs information into temporary cache. According to the Valve * configuration, log will also display into the logger. * @param request the input user request to log. * @param response the response to the user to be incremented. * return the log entry.// w w w.j a v a 2 s. c o m * @throws IOException * @throws ServletException */ private void doLog(Request request, Response response, AccessInformation ai) throws IOException, ServletException { // Retrieve cookie to obtains existing context if any. Cookie integrityCookie = CookieKey.getIntegrityCookie(request.getCookies()); SecurityContext ctx = null; if (integrityCookie != null) { String integrity = integrityCookie.getValue(); if (integrity != null && !integrity.isEmpty()) { ctx = SEC_CTX_PROVIDER.getSecurityContext(integrity); } } if ((ctx != null) && (ctx.getAuthentication() != null)) { ai.setUsername(ctx.getAuthentication().getName()); } else { String[] basicAuth = extractAndDecodeHeader(request.getHeader("Authorization")); if (basicAuth != null) ai.setUsername(basicAuth[0]); } if (request.getQueryString() != null) { ai.setRequest(request.getRequestURL().append('?').append(request.getQueryString()).toString()); } else { ai.setRequest(request.getRequestURL().toString()); } ai.setLocalAddress(LOCAL_ADDR_VALUE); ai.setLocalHost(request.getServerName()); ai.setRemoteAddress(ProxyWebAuthenticationDetails.getRemoteIp(request)); ai.setRemoteHost(ProxyWebAuthenticationDetails.getRemoteHost(request)); }
From source file:com.nkapps.billing.services.SearchServiceImpl.java
@Override public String execSearchBy(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie sbtCookie = null; String searchBy = request.getParameter("searchBy"); if (searchBy == null) { Cookie[] requestCookies = request.getCookies(); for (Cookie c : requestCookies) { if (c.getName().equals("searchBy")) { sbtCookie = c;// w w w . j a v a2s .c om } } if (sbtCookie != null) { searchBy = URLDecoder.decode(sbtCookie.getValue(), "UTF-8"); } else { searchBy = ""; } } else { sbtCookie = new Cookie("searchBy", URLEncoder.encode(searchBy, "UTF-8")); sbtCookie.setPath("/"); response.addCookie(sbtCookie); } return searchBy; }