List of usage examples for javax.servlet.http Cookie getValue
public String getValue()
From source file:org.orbeon.oxf.util.Connection.java
/** * Get header names and values to send given: * * o the incoming request/* w w w . j a v a 2 s .co m*/ * o a list of headers names and values to set * o credentials information * o a list of headers to forward * * @param externalContext context * @param indentedLogger logger or null * @param credentials credentials or null * @param headerNameValues LinkedHashMap<String headerName, String[] headerValues> or null * @param headersToForward headers to forward or null * @return LinkedHashMap<String headerName, String[] headerValues> */ public static Map<String, String[]> getHeadersMap(ExternalContext externalContext, IndentedLogger indentedLogger, Credentials credentials, Map<String, String[]> headerNameValues, String headersToForward) { final boolean doLog = (indentedLogger != null && indentedLogger.isDebugEnabled()); // Resulting header names and values to set final LinkedHashMap<String, String[]> headersMap = new LinkedHashMap<String, String[]>(); // Get header forwarding information final Map<String, String> headersToForwardMap = getHeadersToForward(headersToForward); // Set headers if provided if (headerNameValues != null && headerNameValues.size() > 0) { for (final Map.Entry<String, String[]> currentEntry : headerNameValues.entrySet()) { final String currentHeaderName = currentEntry.getKey(); final String currentHeaderNameLowercase = currentHeaderName.toLowerCase(); final String[] currentHeaderValues = currentEntry.getValue(); // Set header headersMap.put(currentHeaderNameLowercase, currentHeaderValues); // Remove from list of headers to forward below if (headersToForwardMap != null) headersToForwardMap.remove(currentHeaderNameLowercase); } } // Forward cookies for session handling // NOTE: We use a property, as some app servers like WebLogic allow configuring the session cookie name. final String[] cookiesToForward = getForwardCookies(); if (credentials == null && cookiesToForward.length > 0) { // NOTES 2011-01-22: // // If this is requested when a page is generated, it turns out we cannot rely on a JSESSIONID that makes // sense right after authentication, even in the scenario where the JSESSIONID is clean, because Tomcat // replays the initial request. In other words the JSESSIONID cookie can be stale. // // This means that the forwarding done below often doesn't make sense. // // We could possibly allow it only for XForms Ajax/page updates, where the probability that JSESSIONID is // correct is greater. // // A stronger fix might be to simply disable JSESSIONID forwarding, or support a stronger SSO option. // // See: http://forge.ow2.org/tracker/?func=detail&atid=350207&aid=315104&group_id=168 // https://issues.apache.org/bugzilla/show_bug.cgi?id=50633 // // START "NEW" 2009 ALGORITHM // By convention, the first cookie name is the session cookie final String sessionCookieName = cookiesToForward[0]; // 1. If there is an incoming JSESSIONID cookie, use it. The reason is that there is not necessarily an // obvious mapping between "session id" and JSESSIONID cookie value. With Tomcat, this works, but with e.g. // WebSphere, you get session id="foobar" and JSESSIONID=0000foobar:-1. So we must first try to get the // incoming JSESSIONID. To do this, we get the cookie, then serialize it as a header. // TODO: ExternalContext must provide direct access to cookies final Object nativeRequest = externalContext.getRequest().getNativeRequest(); boolean sessionCookieSet = false; if (nativeRequest instanceof HttpServletRequest) { final Cookie[] cookies = ((HttpServletRequest) nativeRequest).getCookies(); final StringBuilder sb = new StringBuilder(); if (cookies != null) { // Figure out if we need to forward session cookies. We only forward if there is the requested // session id is the same as the current session. Otherwise, it means that the current session is no // longer valid, or that the incoming cookie is out of date. boolean forwardSessionCookies = false; final ExternalContext.Session session = externalContext.getSession(false); if (session != null) { final String requestedSessionId = externalContext.getRequest().getRequestedSessionId(); if (session.getId().equals(requestedSessionId)) { forwardSessionCookies = true; } } if (forwardSessionCookies) { final List<String> cookiesToForwardAsList = Arrays.asList(cookiesToForward); for (final Cookie cookie : cookies) { // Remember if we've seen the session cookie sessionCookieSet |= cookie.getName().equals(sessionCookieName); if (cookiesToForwardAsList.contains(cookie.getName())) { // Multiple cookies in the header, separated with ";" if (sb.length() > 0) sb.append("; "); sb.append(cookie.getName()); sb.append('='); sb.append(cookie.getValue()); } } if (sb.length() > 0) { // One or more cookies were set final String cookieString = sb.toString(); if (doLog) indentedLogger.logDebug(LOG_TYPE, "forwarding cookies", "cookie", cookieString, "requested session id", externalContext.getRequest().getRequestedSessionId()); StringConversions.addValueToStringArrayMap(headersMap, "cookie", cookieString); } } } } // 2. If there is no incoming session cookie, try to make our own cookie. This may fail with e.g. // WebSphere. if (!sessionCookieSet) { final ExternalContext.Session session = externalContext.getSession(false); if (session != null) { // This will work with Tomcat, but may not work with other app servers StringConversions.addValueToStringArrayMap(headersMap, "cookie", sessionCookieName + "=" + session.getId()); // All this is for logging! if (doLog) { String incomingSessionHeader = null; final String[] cookieHeaders = externalContext.getRequest().getHeaderValuesMap() .get("cookie"); if (cookieHeaders != null) { for (final String cookie : cookieHeaders) { if (cookie.contains(sessionCookieName)) { incomingSessionHeader = cookie; } } } String incomingSessionCookie = null; if (nativeRequest instanceof HttpServletRequest) { final Cookie[] cookies = ((HttpServletRequest) externalContext.getRequest() .getNativeRequest()).getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { if (cookie.getName().equals(sessionCookieName)) { incomingSessionCookie = cookie.getValue(); } } } } indentedLogger.logDebug(LOG_TYPE, "setting cookie", "new session", Boolean.toString(session.isNew()), "session id", session.getId(), "requested session id", externalContext.getRequest().getRequestedSessionId(), "session cookie name", sessionCookieName, "incoming session cookie", incomingSessionCookie, "incoming session header", incomingSessionHeader); } } } // END "NEW" 2009 ALGORITHM } // Forward headers if needed // NOTE: Forwarding the "Cookie" header may yield unpredictable results because of the above work done w/ session cookies if (headersToForwardMap != null) { final Map<String, String[]> requestHeaderValuesMap = externalContext.getRequest().getHeaderValuesMap(); for (final Map.Entry<String, String> currentEntry : headersToForwardMap.entrySet()) { final String currentHeaderNameLowercase = currentEntry.getKey(); // Get incoming header value (Map contains values in lowercase!) final String[] currentIncomingHeaderValues = requestHeaderValuesMap.get(currentHeaderNameLowercase); // Forward header if present if (currentIncomingHeaderValues != null) { final boolean isAuthorizationHeader = currentHeaderNameLowercase .equalsIgnoreCase(Connection.AUTHORIZATION_HEADER); if (!isAuthorizationHeader || isAuthorizationHeader && credentials == null) { // Only forward Authorization header if there is no credentials provided if (doLog) indentedLogger.logDebug(LOG_TYPE, "forwarding header", "name", currentHeaderNameLowercase, "value", StringUtils.join(currentIncomingHeaderValues, ' ')); StringConversions.addValuesToStringArrayMap(headersMap, currentHeaderNameLowercase, currentIncomingHeaderValues); } else { // Just log this information if (doLog) indentedLogger.logDebug(LOG_TYPE, "not forwarding Authorization header because credentials are present"); } } } } return headersMap; }
From source file:com.zimbra.cs.service.ExternalUserProvServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String displayName = req.getParameter("displayname"); String password = req.getParameter("password"); String prelimToken = null;/* w w w . ja v a 2 s .co m*/ javax.servlet.http.Cookie cookies[] = req.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("ZM_PRELIM_AUTH_TOKEN")) { prelimToken = cookie.getValue(); break; } } } if (prelimToken == null) { throw new ServletException("unauthorized request"); } Map<Object, Object> tokenMap = validatePrelimToken(prelimToken); String ownerId = (String) tokenMap.get("aid"); // String folderId = (String) tokenMap.get("fid"); String extUserEmail = (String) tokenMap.get("email"); provisionVirtualAccountAndRedirect(req, resp, displayName, password, ownerId, extUserEmail); }
From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java
protected String getCookieValue(HttpServletRequest req, String cookieName) { if (req.getCookies() == null) { return null; }//w w w. ja va 2 s . c o m for (Cookie cookie : req.getCookies()) { if (Objects.equals(cookieName, cookie.getName())) { return cookie.getValue(); } } return null; }
From source file:es.pode.soporte.seguridad.openId.ui.openid.PreviousProcessingFilter.java
/** * Devuelve el valor de la cookie de OpenId * @param ServletRequest //from w ww. ja v a 2s. c o m * @param ServletResponse * @param nombreCookie */ private String getCookieValor(HttpServletRequest request, String nombreCookie) { Cookie cookie = null; String valor = null; if (log.isDebugEnabled()) log.debug("Se coge la cookie " + nombreCookie); cookie = getCookie(nombreCookie, request.getCookies()); valor = cookie.getValue(); if (log.isDebugEnabled()) log.debug("Valor cookie:" + valor); return valor; }
From source file:fragment.web.AbstractManageResourceControllerTest.java
/** * @author Abhaik/*from www . ja v a 2 s . c o m*/ * @description : Test to get the SSO Cmd for an Active Tenant through Service Provider User by setting cookies */ @Test public void testSSOFromSPUserForSetCookie() { setSSOHandler(); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); map = new ModelMap(); Tenant systemTenant = tenantService.getSystemTenant(); Tenant tenant = tenantdao.find(2L); ServiceInstance instance = serviceInstanceDao.find(1L); request.setAttribute("effectiveTenant", tenant); request.setAttribute("isSurrogatedTenant", isSurrogatedTenant(systemTenant, tenant.getParam())); Map<String, String> resultMap = controller.getSSOCmdString(systemTenant, tenant.getParam(), instance.getUuid(), map, request, response); Assert.assertNotNull(resultMap); String status = resultMap.get("status"); Assert.assertEquals("success", status); String cmdString = resultMap.get("cmdString"); Assert.assertNotNull(cmdString); Cookie obtCookie = response.getCookie("Test"); Assert.assertEquals("Test", obtCookie.getValue()); }
From source file:com.maydesk.base.PDUserSession.java
public String getCookie(String cookieName) { ContainerContext ctx = (ContainerContext) ApplicationInstance.getActive() .getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME); Cookie[] cookies = ctx.getCookies(); for (Cookie cookie : cookies) { if (StringUtils.equals(cookie.getName(), cookieName)) { return cookie.getValue(); }/*from w ww . ja v a2 s.c o m*/ } return null; }
From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java
public XWikiUser checkAuth(XWikiContext context) throws XWikiException { Cookie cookie;/*from w w w . j a va 2s . c o m*/ 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:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java
private void processCookie(MockHttpServletRequest result, List<Cookie> cookies, Cookie cookie) { cookies.add(cookie);/* w w w. j a va 2 s .co m*/ if ("JSESSIONID".equals(cookie.getName())) { result.setRequestedSessionId(cookie.getValue()); result.setSession(httpSession(result, cookie.getValue())); } }
From source file:com.appeligo.search.actions.BaseAction.java
protected String getCookieId() { Cookie[] cookies = getServletRequest().getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(BaseAction.COOKIE_ID)) { cookie.setMaxAge(Integer.MAX_VALUE); return cookie.getValue(); }/* w ww .ja v a2s . c o m*/ } } //No cookie found; String cookieValue = request.getRemoteAddr() + System.currentTimeMillis(); Cookie cookie = new Cookie(COOKIE_ID, cookieValue); cookie.setMaxAge(Integer.MAX_VALUE); response.addCookie(cookie); return cookieValue; }
From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java
protected void redirectToApp(HttpServletRequest request, HttpServletResponse response, String contextName, String[] uriParts, String action) throws IOException { StringBuilder redirectAddress = new StringBuilder(); for (int i = 0; i < uriParts.length; i++) { redirectAddress.append(uriParts[i]); if (uriParts[i].equals(contextName)) { break; }//from w w w. j a v a2 s . com if (i < uriParts.length - 1) { redirectAddress.append("/"); } } // redirect to ROOT context if (redirectAddress.length() == 0) { redirectAddress.append("/"); } HttpSession httpSession = request.getSession(); if (action != null) { httpSession.setAttribute(AppUI.LAST_REQUEST_ACTION_ATTR, action); } if (request.getParameterNames().hasMoreElements()) { Map<String, String> params = new HashMap<>(); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String) parameterNames.nextElement(); if (!FROM_HTML_REDIRECT_PARAM.equals(name)) { params.put(name, request.getParameter(name)); } } httpSession.setAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR, params); } statisticsCounter.incWebRequestsCount(); String httpSessionId = httpSession.getId(); log.debug("Redirect to application {}", httpSessionId); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("JSESSIONID".equals(cookie.getName()) && !httpSessionId.equals(cookie.getValue())) { cookie.setValue(httpSessionId); break; } } } response.sendRedirect(redirectAddress.toString()); }