List of usage examples for javax.servlet.http Cookie getName
public String getName()
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract cookies and other global fields into inData * //from www .java 2 s. c om * @param req * @param inData */ @SuppressWarnings("unchecked") private void getStandardFields(HttpServletRequest req, ServiceData inData) { // log field if (suppressSqlLog) { inData.addValue(ExilityConstants.SUPPRESS_SQL_LOG, "1"); } if (AP.cookiesToBeExtracted != null) { Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 0) { for (Cookie cookie : cookies) { if (AP.cookiesToBeExtracted.contains(cookie.getName())) { Spit.out(cookie.getName() + " extracted from cookie"); inData.addValue(cookie.getName(), cookie.getValue()); } } } } this.extractParametersAndFiles(req, inData); /** * is there a sessionData object? */ HttpSession session = req.getSession(); String token = req.getHeader(CommonFieldNames.CSRF_HEADER); if (token == null) { // try form fields token = inData.getValue(CommonFieldNames.CSRF_HEADER); } if (token == null) { // for the sake of jsps that still exist in our system.. Object obj = session.getAttribute(HttpRequestHandler.SESSION_TOKEN_NAME); if (obj != null) { token = obj.toString(); } } if (token != null) { Object obj = session.getAttribute(token); if (obj != null && obj instanceof SessionData) { Spit.out("Session fields being extracted from new token based object."); ((SessionData) obj).extractAll(inData); } else { Spit.out("CSRF token found to be " + token + " but session data not found"); } } else { Spit.out("NO CSRF token. Will try old ways of session data."); Object data = session.getAttribute(HtmlRequestHandler.GLOBAL_SERVER_DATA_NAME + inData.getValue(HtmlRequestHandler.getUserIdName())); if (data != null && data instanceof Map) { Map<String, String> sessionData = (Map<String, String>) data; for (String name : sessionData.keySet()) { // Spit.out("Trying " + name + " as a global field"); String val = sessionData.get(name); if (val != null && val.length() > 0) { inData.addValue(name, val); } } } } }
From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java
@Override public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception { AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)) .getAuthInfo();// w w w . j ava 2 s .c o m ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); List<Cookie> cookies = null; if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) { UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); HttpSession session = request.getSession(); String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH"); if (uid == null || !uid.equals(userData.getUserDN())) { session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN()); HashMap<String, String> uriParams = new HashMap<String, String>(); uriParams.put("fullURI", this.uri); UrlHolder remHolder = cfg.findURL(this.url); org.apache.http.client.methods.HttpRequestBase method = null; if (this.postSAML) { PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias); java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias); Saml2Assertion assertion = new Saml2Assertion( userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null, this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion, this.signResponse, false, this.nameIDType, this.authnCtxClassRef); String respXML = ""; try { respXML = assertion.generateSaml2Response(); } catch (Exception e) { throw new ServletException("Could not generate SAMLResponse", e); } List<NameValuePair> formparams = new ArrayList<NameValuePair>(); String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8")); formparams.add(new BasicNameValuePair("SAMLResponse", base64)); if (this.relayState != null && !this.relayState.isEmpty()) { formparams.add(new BasicNameValuePair("RelayState", this.relayState)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost post = new HttpPost(this.assertionConsumerURL); post.setEntity(entity); method = post; } else { HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams)); method = get; } LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0), this.loginAttribute, method, lastMileKeyAlias, true); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfg.getHttpClientSocketRegistry()); try { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm) .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build(); HttpResponse resp = httpclient.execute(method); if (resp.getStatusLine().getStatusCode() == 500) { BufferedReader in = new BufferedReader( new InputStreamReader(resp.getEntity().getContent())); StringBuffer error = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { error.append(line).append('\n'); } logger.warn("Pre-Auth Failed : " + error); } org.apache.http.Header[] headers = resp.getAllHeaders(); StringBuffer stmp = new StringBuffer(); cookies = new ArrayList<Cookie>(); for (org.apache.http.Header header : headers) { if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal); for (HttpCookie cookie : cookiesx) { String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'"); Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { //respcookie.setDomain(cookie.getDomain()); } respcookie.setMaxAge((int) cookie.getMaxAge()); respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); cookies.add(respcookie); if (request.getCookieNames().contains(respcookie.getName())) { request.removeCookie(cookieFinalName); } request.addCookie(new Cookie(cookie.getName(), cookie.getValue())); } } } } finally { bhcm.shutdown(); } } } chain.nextFilter(request, response, chain); if (cookies != null) { for (Cookie cookie : cookies) { response.addCookie(cookie); } } }
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 a2 s.c o 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:ddf.security.samlp.impl.LogoutMessageImpl.java
@Override public String sendSamlLogoutRequest(LogoutRequest request, String targetUri, boolean isSoap, @Nullable Cookie cookie) throws IOException, WSSecurityException { XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage(request) : request; Element requestElement = getElementFromSaml(xmlObject); String requestMessage = DOM2Writer.nodeToString(requestElement); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost(targetUri); post.addHeader("Cache-Control", "no-cache, no-store"); post.addHeader("Pragma", "no-cache"); post.addHeader("SOAPAction", SAML_SOAP_ACTION); post.addHeader("Content-Type", "application/soap+xml"); post.setEntity(new StringEntity(requestMessage, "utf-8")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); BasicHttpContext context = new BasicHttpContext(); if (cookie != null) { BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); basicClientCookie.setDomain(cookie.getDomain()); basicClientCookie.setPath(cookie.getPath()); BasicCookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(basicClientCookie); context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); }//w w w .j a v a2 s . c o m return httpClient.execute(post, responseHandler, context); } }
From source file:com.liferay.portal.util.HttpImpl.java
protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) { org.apache.commons.httpclient.Cookie commonsCookie = new org.apache.commons.httpclient.Cookie( cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure());/*from w w w . jav a 2 s . co m*/ commonsCookie.setVersion(cookie.getVersion()); return commonsCookie; }
From source file:com.qut.middleware.esoe.sso.impl.SSOProcessorImpl.java
private void processCookies(SSOProcessorData data) { String remoteAddr = data.getRemoteAddress(); HttpServletRequest request = data.getHttpRequest(); if (request == null) { this.logger.warn( "[SSO for {}] No HTTP request object was passed in by the SSO handler. Unable to process cookies.", remoteAddr);/*from w w w. ja v a 2s .c o m*/ return; } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { this.logger.debug("[SSO for {}] Processing cookie {} = {}", new Object[] { remoteAddr, cookie.getName(), cookie.getValue() }); if (cookie.getName().equals(this.sessionTokenName)) { this.logger.debug("[SSO for {}] Identified ESOE cookie {} = {}", new Object[] { remoteAddr, cookie.getName(), cookie.getValue() }); data.setSessionID(cookie.getValue()); // We don't need any further cookies. Remove this if that changes. return; } } } else { this.logger.debug("[SSO for {}] No cookies in HTTP request.", remoteAddr); } }
From source file:org.workcast.ssoficlient.service.LoginHandler.java
/** * Returns the value of a named cookie if there is one, returns null if * there is not//from w w w . j a v a 2 s. co m */ public String findTenantCookieValue(String cookieName) throws Exception { // make a tenant-specific cookie name automatically if (aa != null && aa.tenant != null) { cookieName = cookieName + URLEncoder.encode(aa.tenant, "UTF-8"); } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie oneCookie : cookies) { if (oneCookie != null) { String cName = oneCookie.getName(); if (cName != null && cookieName.equals(cName)) { return oneCookie.getValue(); } } } } return ""; }
From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java
/** * This method simulates the authentication process against a content * source, so that every document is consider here as public. * <p>/*w ww. ja v a 2s .c om*/ * Creates the authentication cookie and always return 200, unless there is * any problem processing the request. * * @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; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP No authentication start"); // // Launch the authentication process // // Protection try { Cookie extAuthCookie = null; extAuthCookie = new Cookie("gsa_basic_noauth", ""); extAuthCookie.setValue("true"); String authCookieDomain = null; String authCookiePath = null; int authMaxAge = -1; // Cache cookie properties authCookieDomain = (request.getAttribute("authCookieDomain")).toString(); authCookiePath = (request.getAttribute("authCookiePath")).toString(); //authMaxAge try { authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:"); } // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //add 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))) { response.addCookie(extAuthCookie); } //add cookie to the array authCookies.add(extAuthCookie); statusCode = HttpServletResponse.SC_OK; } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP No Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java
/** * This method checks the request for the has conditions which may either be contained in URL * query arguments or in a cookie sent from the client. * * @param request/*from w w w.j ava 2 s. c o m*/ * the request object * @return The has conditions from the request. * @throws IOException * @throws UnsupportedEncodingException */ protected String getHasConditionsFromRequest(HttpServletRequest request) throws IOException { final String sourceMethod = "getHasConditionsFromRequest"; //$NON-NLS-1$ boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(AbstractHttpTransport.class.getName(), sourceMethod, new Object[] { request }); } String ret = null; if (request.getParameter(FEATUREMAPHASH_REQPARAM) != null) { // The cookie called 'has' contains the has conditions if (isTraceLogging) { log.finer("has hash = " + request.getParameter(FEATUREMAPHASH_REQPARAM)); //$NON-NLS-1$ } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; ret == null && i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals(FEATUREMAP_REQPARAM) && cookie.getValue() != null) { if (isTraceLogging) { log.finer("has cookie = " + cookie.getValue()); //$NON-NLS-1$ } ret = URLDecoder.decode(cookie.getValue(), "US-ASCII"); //$NON-NLS-1$ break; } } } if (ret == null) { if (log.isLoggable(Level.WARNING)) { StringBuffer url = request.getRequestURL(); if (url != null) { // might be null if using mock request for unit testing url.append("?").append(request.getQueryString()).toString(); //$NON-NLS-1$ log.warning(MessageFormat.format(Messages.AbstractHttpTransport_0, new Object[] { url, request.getHeader("User-Agent") })); //$NON-NLS-1$ } } } } else { ret = request.getParameter(FEATUREMAP_REQPARAM); if (isTraceLogging) { log.finer("reading features from has query arg"); //$NON-NLS-1$ } } if (isTraceLogging) { log.exiting(AbstractHttpTransport.class.getName(), sourceMethod, ret); } return ret; }
From source file:com.adito.security.DefaultLogonController.java
public void logoffSession(HttpServletRequest request, HttpServletResponse response) throws SecurityErrorException { if (log.isInfoEnabled()) log.info("Logging off session " + request.getSession().getId()); if (request.getSession().getAttribute(Constants.LOGON_TICKET) == null) { throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, "The current session does not contain a logon ticket"); } else {//from w w w .j a va 2 s . com String ticket = (String) request.getSession().getAttribute(Constants.LOGON_TICKET); SessionInfo session = getSessionInfo(ticket); logoff(ticket); if (request.getCookies() != null) { for (int i = 0; i < request.getCookies().length; i++) { Cookie cookie = request.getCookies()[i]; if (cookie.getName().equals(Constants.LOGON_TICKET) || cookie.getName().equals(Constants.DOMAIN_LOGON_TICKET)) { cookie.setMaxAge(0); response.addCookie(cookie); } } } request.getSession().removeAttribute(Constants.LOGON_TICKET); session.invalidate(); } }