List of usage examples for javax.servlet.http Cookie setMaxAge
public void setMaxAge(int expiry)
From source file:com.kodemore.servlet.ScServletData.java
/** * The cookie should be a new instance that contains the correct * values for name, domain, and path.//from www . j a v a 2 s.com */ public void _clearCookie(Cookie e) { e.setValue(REMOVED_COOKIE_VALUE); e.setMaxAge(0); _setCookie(e); }
From source file:com.kodemore.servlet.ScServletData.java
public void setCookie(String key, String value, Integer expireSeconds, boolean secure) { value = Kmu.encodeUtf8(value);//w ww. j ava 2 s.com Cookie cookie = new Cookie(key, value); if (expireSeconds != null) cookie.setMaxAge(expireSeconds); if (secure) cookie.setSecure(true); // share cookies across the domain, regardless of the [servlet] path. cookie.setPath("/"); _setCookie(cookie); }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * Clear cookie./*from w w w. ja v a 2 s . com*/ * * @param key the key */ public void clearCookie(String key) { Cookie tsc = new Cookie(key, ""); tsc.setPath(getWikiWeb().getContextPath()); // tsc.setSecure(true); tsc.setMaxAge(0); response.addCookie(tsc); }
From source file:com.liferay.portal.util.HttpImpl.java
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain);/*from w w w . j a v a 2 s . co m*/ } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }
From source file:com.google.gsa.valve.modules.httpbasic.HTTPBasicAuthenticationProcess.java
/** * This is the main method that does the authentication and should be * invoked by the classes that would like to open a new authentication * process against an HTTP Basic protected source. * <p>//from w w w . j a v a 2 s .com * The username and password for the source are assumed to be the ones * captured during the authentication. These are stored in creds and in * this case the root parameters. creds is an array of credentials for * all external sources. The first element is 'root' which contains the * credentials captured from the login page. This method reviews if there * is a credential id identical to the name associated to this module * in the config file. If so, these credentials are used to authenticate * against this HTTP Basic source, and if not 'root' one will be used * instead. * <p> * If the HTTP Basic authentication result is OK, it creates an * authentication cookie containing the HTTP Basic credentials * to be reused during authorization. The content returned back from the * remote secure backend system is sent as well. Anyway, the HTTP * response code is returned in this method to inform the caller on the * status. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; //Credentials UsernamePasswordCredentials credentials = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP Basic authentication start"); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("HttpBasic: trying to get creds from repository ID: " + id); Credential httpBasicCred = null; try { httpBasicCred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (httpBasicCred != null) { credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } else { logger.debug("HttpBasic: trying to get creds from repository \"root\""); httpBasicCred = creds.getCredential("root"); if (httpBasicCred != null) { logger.info("Trying with root credentails"); credentials = new UsernamePasswordCredentials(httpBasicCred.getUsername(), httpBasicCred.getPassword()); } } logger.debug("Authenticating"); Header[] headers = null; HttpMethodBase method = null; //Get Max connections int maxConnectionsPerHost = 30; int maxTotalConnections = 100; //Cookie Max Age int authMaxAge = -1; try { maxConnectionsPerHost = new Integer(valveConf.getMaxConnectionsPerHost()).intValue(); maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue(); authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the numbers set for any of the following parameters are not OK:"); logger.error(" * maxConnectionsPerHost * maxTotalConnections * authMaxAge"); } // Protection if (webProcessor == null) { // Instantiate Web processor if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) { webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections); } else { webProcessor = new WebProcessor(); } } // // Launch the authentication process // // A fixed URL in the repository that all users have access to which can be used to authN a user // and capture the HTTP Authorization Header String authURL = valveConf.getRepository(id).getParameterValue("HTTPAuthPage"); try { // Set HTTP headers headers = new Header[1]; // Set User-Agent headers[0] = new Header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5"); // Request page, testing if credentials are valid if (credentials != null) { logger.debug("Username: " + credentials.getUserName()); logger.debug("URL: " + authURL); } //HTTP request method = webProcessor.sendRequest(credentials, RequestType.GET_REQUEST, headers, null, authURL); //Read the auth header and store in the cookie, the authZ class will use this later headers = method.getRequestHeaders(); Header authHeader = null; authHeader = method.getRequestHeader("Authorization"); // Cache status code if (method != null) statusCode = method.getStatusCode(); if (statusCode == HttpServletResponse.SC_OK) { //Authentication worked, so create the auth cookie to indicate it has worked Cookie extAuthCookie = null; extAuthCookie = new Cookie(BASIC_COOKIE, ""); if (authHeader != null) { String basicCookie = null; try { basicCookie = URLEncoder.encode(getBasicAuthNChain(authHeader.getValue()), encoder); if (basicCookie == null) { basicCookie = ""; } } catch (Exception ex) { logger.error("Error when setting Basic cookie value: " + ex.getMessage(), ex); basicCookie = ""; } extAuthCookie.setValue(basicCookie); } String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding " + BASIC_COOKIE + " cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()) .booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { logger.debug("Adding cookie to response"); response.addCookie(extAuthCookie); } //Add cookies to the Cookie array to support sessions authCookies.add(extAuthCookie); logger.debug("Cookie added to the array"); } // Clear webProcessor cookies webProcessor.clearCookies(); } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Garbagge collect method = null; // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP Basic Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java
public Cookie getSessionCookie(HttpSession session, boolean requestIsSecure) { if (_handler.isUsingCookies()) { Cookie cookie = _handler.getSessionManager().getHttpOnly() ? new HttpOnlyCookie(SessionManager.__SessionCookie, session.getId()) : new Cookie(SessionManager.__SessionCookie, session.getId()); String domain = _handler.getServletContext().getInitParameter(SessionManager.__SessionDomain); String maxAge = _handler.getServletContext().getInitParameter(SessionManager.__MaxAge); String path = _handler.getServletContext().getInitParameter(SessionManager.__SessionPath); if (path == null) path = getCrossContextSessionIDs() ? "/" : _handler.getHttpContext().getContextPath(); if (path == null || path.length() == 0) path = "/"; if (domain != null) cookie.setDomain(domain);/*from w ww . j a v a2 s .co m*/ if (maxAge != null) cookie.setMaxAge(Integer.parseInt(maxAge)); else cookie.setMaxAge(-1); cookie.setSecure(requestIsSecure && getSecureCookies()); cookie.setPath(path); return cookie; } return null; }
From source file:de.micromata.genome.gwiki.page.GWikiContext.java
/** * set a cookie./* w w w. j a v a2s. co m*/ * * @param key the key * @param value the value */ @SuppressWarnings("deprecation") public void setCookie(String key, String value) { String cvalue = URLEncoder.encode(value); Cookie tsc = new Cookie(key, cvalue); tsc.setPath(getWikiWeb().getContextPath()); if (StringUtils.isEmpty(tsc.getPath()) == true) { tsc.setPath("/"); } tsc.setMaxAge((int) TimeInMillis.YEAR); response.addCookie(tsc); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
@RequestMapping(value = "/logout/**", method = RequestMethod.GET) public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) { // clear cookies// w w w .j a v a2 s . co m Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String ckName = cookies[i].getName(); if (ckName.equals(loginCookie) || ckName.startsWith("_shib")) { log.debug("cookie to clear " + ckName); Cookie c = new Cookie(ckName, "void"); c.setSecure(true); c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } } } /** try { log.debug("redirect to: " + logoutUrl); response.sendRedirect(logoutUrl); } catch (IOException e) { log.error("redirect: " + e); } return emptyMV("configuration error"); **/ String view = "browser"; Device currentDevice = DeviceUtils.getCurrentDevice(request); if (currentDevice != null && currentDevice.isMobile()) view = "mobile"; ModelAndView mv = new ModelAndView(view + "/chooser"); mv.addObject("root", browserRootPath); mv.addObject("vers", request.getServletPath()); mv.addObject("pagetype", "browser/loggedout"); mv.addObject("pathextra", ""); mv.addObject("uwloginpath", standardLoginPath); mv.addObject("googleloginpath", googleLoginPath); mv.addObject("incommonloginpath", incommonLoginPath); return (mv); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private void sendToLogin(HttpServletRequest request, HttpServletResponse response, String loginPath) { // delete any existing sessions first Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().startsWith("_shib")) { log.debug("clearing cookie " + cookies[i].getName()); Cookie c = new Cookie(cookies[i].getName(), ""); c.setSecure(true);//from w ww. j a v a 2 s . co m c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } } } String rp = ""; if (request.getPathInfo() != null) rp = request.getPathInfo(); String rqs = ""; if (request.getQueryString() != null) rqs = "?" + request.getQueryString(); String red = browserRootPath + request.getServletPath() + loginPath + rp + rqs; log.debug("no user yet: redirect for login to " + red); try { response.sendRedirect(red); } catch (IOException e) { log.error("redirect: " + e); } }
From source file:nl.nn.adapterframework.http.rest.ApiListenerServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /**//from ww w.ja v a 2s . co m * Initiate and populate messageContext */ PipeLineSessionBase messageContext = new PipeLineSessionBase(); messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request); messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response); messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext()); messageContext.setSecurityHandler(new HttpSecurityHandler(request)); try { String uri = request.getPathInfo(); String method = request.getMethod().toUpperCase(); log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]"); if (uri == null) { response.setStatus(400); log.warn("Aborting request with status [400], empty uri"); return; } if (uri.startsWith("/")) uri = uri.substring(1); if (uri.endsWith("/")) uri = uri.substring(0, uri.length() - 1); ApiDispatchConfig config = dispatcher.findConfigForUri(uri); if (config == null) { response.setStatus(404); log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]"); return; } /** * Handle Cross-Origin Resource Sharing * TODO make this work behind loadbalancers/reverse proxies * TODO check if request ip/origin header matches allowOrigin property */ String origin = request.getHeader("Origin"); if (method.equals("OPTIONS") || origin != null) { response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin); String headers = request.getHeader("Access-Control-Request-Headers"); if (headers != null) response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders); StringBuilder methods = new StringBuilder(); for (String mtd : config.getMethods()) { methods.append(", ").append(mtd); } response.setHeader("Access-Control-Allow-Methods", methods.toString()); //Only cut off OPTIONS (aka preflight) requests if (method.equals("OPTIONS")) { response.setStatus(200); log.trace("Aborting preflight request with status [200], method [" + method + "]"); return; } } /** * Get serviceClient */ ApiListener listener = config.getApiListener(method); if (listener == null) { response.setStatus(405); log.trace("Aborting request with status [405], method [" + method + "] not allowed"); return; } log.trace("ApiListenerServlet calling service [" + listener.getName() + "]"); /** * Check authentication */ ApiPrincipal userPrincipal = null; if (listener.getAuthenticationMethod() != null) { String authorizationToken = null; Cookie authorizationCookie = null; if (listener.getAuthenticationMethod().equals("COOKIE")) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("authenticationToken")) { authorizationToken = cookie.getValue(); authorizationCookie = cookie; authorizationCookie.setPath("/"); } } } else if (listener.getAuthenticationMethod().equals("HEADER")) { authorizationToken = request.getHeader("Authorization"); } if (authorizationToken != null && cache.containsKey(authorizationToken)) userPrincipal = (ApiPrincipal) cache.get(authorizationToken); if (userPrincipal == null || !userPrincipal.isLoggedIn()) { cache.remove(authorizationToken); if (authorizationCookie != null) { authorizationCookie.setMaxAge(0); response.addCookie(authorizationCookie); } response.setStatus(401); log.trace("Aborting request with status [401], no (valid) credentials supplied"); return; } if (authorizationCookie != null) { authorizationCookie.setMaxAge(authTTL); response.addCookie(authorizationCookie); } userPrincipal.updateExpiry(); userPrincipal.setToken(authorizationToken); cache.put(authorizationToken, userPrincipal, authTTL); messageContext.put("authorizationToken", authorizationToken); } messageContext.put("remoteAddr", request.getRemoteAddr()); messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal); messageContext.put("uri", uri); /** * Evaluate preconditions */ String accept = request.getHeader("Accept"); if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) { if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) { response.setStatus(406); response.getWriter().print("It appears you expected the MediaType [" + accept + "] but I only support the MediaType [" + listener.getContentType() + "] :)"); log.trace("Aborting request with status [406], client expects [" + accept + "] got [" + listener.getContentType() + "] instead"); return; } } if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) { response.setStatus(415); log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes() + "] got [" + request.getContentType() + "] instead"); return; } String etagCacheKey = ApiCacheManager.buildCacheKey(uri); log.debug("Evaluating preconditions for listener[" + listener.getName() + "] etagKey[" + etagCacheKey + "]"); if (cache.containsKey(etagCacheKey)) { String cachedEtag = (String) cache.get(etagCacheKey); log.debug("found etag value[" + cachedEtag + "] for key[" + etagCacheKey + "]"); if (method.equals("GET")) { String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) { response.setStatus(304); log.trace( "Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]"); return; } } else { String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !ifMatch.equals(cachedEtag)) { response.setStatus(412); log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method [" + method + "]"); return; } } } messageContext.put("updateEtag", listener.getUpdateEtag()); /** * Check authorization */ //TODO: authentication implementation /** * Map uriIdentifiers into messageContext */ String patternSegments[] = listener.getUriPattern().split("/"); String uriSegments[] = uri.split("/"); int uriIdentifier = 0; for (int i = 0; i < patternSegments.length; i++) { String segment = patternSegments[i]; if (segment.startsWith("{") && segment.endsWith("}")) { String name; if (segment.equals("*")) name = "uriIdentifier_" + uriIdentifier; else name = segment.substring(1, segment.length() - 1); uriIdentifier++; log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]"); messageContext.put(name, uriSegments[i]); } } /** * Map queryParameters into messageContext */ Enumeration<?> paramnames = request.getParameterNames(); while (paramnames.hasMoreElements()) { String paramname = (String) paramnames.nextElement(); String paramvalue = request.getParameter(paramname); log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]"); messageContext.put(paramname, paramvalue); } /** * Map multipart parts into messageContext */ if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]"); messageContext.put(fieldName, fieldValue); } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fieldNameName = fieldName + "Name"; String fileName = FilenameUtils.getName(item.getName()); log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]"); messageContext.put(fieldNameName, fileName); log.trace( "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); messageContext.put(fieldName, item.getInputStream()); } } } /** * Compile Allow header */ StringBuilder methods = new StringBuilder(); methods.append("OPTIONS, "); for (String mtd : config.getMethods()) { methods.append(mtd + ", "); } messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2)); /** * Process the request through the pipeline */ String body = ""; if (!ServletFileUpload.isMultipartContent(request)) { body = Misc.streamToString(request.getInputStream(), "\n", false); } String result = listener.processRequest(null, body, messageContext); /** * Calculate an eTag over the processed result and store in cache */ if (messageContext.get("updateEtag", true)) { log.debug("calculating etags over processed result"); String cleanPattern = listener.getCleanPattern(); if (result != null && method.equals("GET")) { String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode()); log.debug("adding/overwriting etag with key[" + etagCacheKey + "] value[" + eTag + "]"); cache.put(etagCacheKey, eTag); response.addHeader("etag", eTag); } else { log.debug("removing etag with key[" + etagCacheKey + "]"); cache.remove(etagCacheKey); // Not only remove the eTag for the selected resources but also the collection String key = ApiCacheManager.getParentCacheKey(listener, uri); if (key != null) { log.debug("removing parent etag with key[" + key + "]"); cache.remove(key); } } } /** * Add headers */ response.addHeader("Allow", (String) messageContext.get("allowedMethods")); String contentType = listener.getContentType() + "; charset=utf-8"; if (listener.getProduces().equals("ANY")) { contentType = messageContext.get("contentType", contentType); } response.setHeader("Content-Type", contentType); /** * Check if an exitcode has been defined or if a statuscode has been added to the messageContext. */ int statusCode = messageContext.get("exitcode", 0); if (statusCode > 0) response.setStatus(statusCode); /** * Finalize the pipeline and write the result to the response */ if (result != null) response.getWriter().print(result); log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]"); } catch (Exception e) { log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e); try { response.flushBuffer(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (IllegalStateException ex) { //We're only informing the end user(s), no need to catch this error... response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }