Java Code Examples for javax.servlet.http.Cookie#getValue()

The following examples show how to use javax.servlet.http.Cookie#getValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecuritySessionManager.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public String getCurrentProfile(HttpServletRequest request) {
	String sessionId = request.getParameter(SecurityConstants.HEADER_AUTH_PROFILE);
	if(isBlank(sessionId)){
		sessionId = request.getHeader(SecurityConstants.HEADER_AUTH_PROFILE);
	}
	if(isBlank(sessionId)){
		Cookie[] cookies = request.getCookies();
		if(cookies == null)return null;
		for (Cookie cookie : cookies) {
			if(SecurityConstants.HEADER_AUTH_PROFILE.equals(cookie.getName())){
				sessionId = cookie.getValue();
				break;
			}
		}
	}
	
	if(StringUtils.isNotBlank(sessionId)){
		sessionId = SecurityCryptUtils.decrypt(sessionId);
	}
	return sessionId;
}
 
Example 2
Source File: JWTAuthenticationHandler.java    From registry with Apache License 2.0 6 votes vote down vote up
/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request.
 *
 * @param req servlet request to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
    String serializedJWT = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                LOG.info(cookieName
                        + " cookie has been found and is being processed");
                serializedJWT = cookie.getValue();
                break;
            }
        }
    }
    return serializedJWT;
}
 
Example 3
Source File: EngineSessionCookie.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
public static void addCookie(HttpServletRequest request, HttpServletResponse response,
    Cookie cookie) {
  Cookie[] cookies = request.getCookies();
  boolean contains = false;
  if (cookies != null && cookies.length > 0) {
    for (Cookie existingCookie : cookies) {
      if (cookie.getName().equals(existingCookie.getName())) {
        String cookieValue = cookie.getValue();
        if (cookieValue == null) {
          contains = existingCookie.getValue() == null;
        } else {
          contains = cookieValue.equals(existingCookie.getValue());
        }
      }
    }
  }
  if (!contains) {
    response.addCookie(cookie);
  }
}
 
Example 4
Source File: AtlasKnoxSSOAuthenticationFilter.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request.
 *
 * @param req servlet request to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
    String serializedJWT = null;
    Cookie[] cookies = req.getCookies();
    if (cookieName != null && cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} cookie has been found and is being processed", cookieName);
                }
                serializedJWT = cookie.getValue();
                break;
            }
        }
    }
    return serializedJWT;
}
 
Example 5
Source File: KnoxSSOAuthenticationFilter.java    From metron with Apache License 2.0 6 votes vote down vote up
/**
 * Encapsulate the acquisition of the JWT token from HTTP cookies within the
 * request.
 *
 * @param req ServletRequest to get the JWT token from
 * @return serialized JWT token
 */
protected String getJWTFromCookie(HttpServletRequest req) {
  String serializedJWT = null;
  Cookie[] cookies = req.getCookies();
  if (cookies != null) {
    for (Cookie cookie : cookies) {
      LOG.debug(String.format("Found cookie: %s [%s]", cookie.getName(), cookie.getValue()));
      if (knoxCookie.equals(cookie.getName())) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(knoxCookie + " cookie has been found and is being processed");
        }
        serializedJWT = cookie.getValue();
        break;
      }
    }
  } else {
    if (LOG.isDebugEnabled()) {
      LOG.debug(knoxCookie + " not found");
    }
  }
  return serializedJWT;
}
 
Example 6
Source File: RoleQueryHelper.java    From fess with Apache License 2.0 6 votes vote down vote up
protected void processCookie(final HttpServletRequest request, final Set<String> roleSet) {

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (cookieKey.equals(cookie.getName())) {
                    final String value = cookie.getValue();
                    if (logger.isDebugEnabled()) {
                        logger.debug("{}:{}", cookieKey, value);
                    }
                    if (StringUtil.isNotEmpty(value)) {
                        parseRoleSet(value, encryptedCookieValue, roleSet);
                    }
                }
            }
        }

    }
 
Example 7
Source File: ProvidersController.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Record search history to cookies, steps:
 * Check whether the added record exists in the cookie, and if so, update the list order; if it does not exist, insert it to the front
 *
 * @param value
 */
private void setSearchHistroy(String value, HttpServletRequest request, HttpServletResponse response) {
    //System.out.println("add new cookie: " + value);
    // Analyze existing cookies
    String separatorsB = "\\.\\.\\.\\.\\.\\.";
    String newCookiev = value;
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if (c.getName().equals("HISTORY")) {
            String cookiev = c.getValue();
            String[] values = cookiev.split(separatorsB);
            int count = 1;
            for (String v : values) {
                if (count <= 10) {
                    if (!value.equals(v)) {
                        newCookiev = newCookiev + separatorsB + v;
                        //System.out.println("new cookie: " + newCookiev);
                    }
                }
                count++;
            }
            break;
        }
    }

    Cookie _cookie = new Cookie("HISTORY", newCookiev);
    _cookie.setMaxAge(60 * 60 * 24 * 7); // Set the cookie's lifetime to 30 minutes
    _cookie.setPath("/");
    response.addCookie(_cookie); // Write to client hard disk
}
 
Example 8
Source File: CmsLoginAct.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
private Integer getCookieErrorRemaining(HttpServletRequest request,
		HttpServletResponse response) {
	Cookie cookie = CookieUtils.getCookie(request, COOKIE_ERROR_REMAINING);
	if (cookie != null) {
		String value = cookie.getValue();
		if (NumberUtils.isDigits(value)) {
			return Integer.parseInt(value);
		}
	}
	return null;
}
 
Example 9
Source File: CookieUtil.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 查询value
 *
 * @param request
 * @param key
 * @return
 */
public static String getValue(HttpServletRequest request, String key) {
	Cookie cookie = get(request, key);
	if (cookie != null) {
		return cookie.getValue();
	}
	return null;
}
 
Example 10
Source File: CookieUtil.java    From xxl-mq with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 查询value
 *
 * @param request
 * @param key
 * @return
 */
public static String getValue(HttpServletRequest request, String key) {
	Cookie cookie = get(request, key);
	if (cookie != null) {
		return cookie.getValue();
	}
	return null;
}
 
Example 11
Source File: CookieUtil.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 根据Cookie的key得到Cookie的值.
 *
 * @param request the request
 * @param name    the name
 *
 * @return the cookie value
 */
public static String getCookieValue(HttpServletRequest request, String name) {
	Cookie cookie = getCookie(request, name);
	if (cookie != null) {
		return cookie.getValue();
	} else {
		return null;
	}
}
 
Example 12
Source File: DatastoreSessionFilter.java    From getting-started-java with Apache License 2.0 5 votes vote down vote up
protected String getCookieValue(HttpServletRequest req, String cookieName) {
  Cookie[] cookies = req.getCookies();
  if (cookies != null) {
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(cookieName)) {
        return cookie.getValue();
      }
    }
  }
  return "";
}
 
Example 13
Source File: KnoxAuthenticationFilter.java    From nifi with Apache License 2.0 5 votes vote down vote up
public String getJwtFromCookie(final HttpServletRequest request, final String cookieName) {
    String jwt = null;

    final Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                jwt = cookie.getValue();
                break;
            }
        }
    }

    return jwt;
}
 
Example 14
Source File: UserArgumentResolver.java    From SecKillShop with MIT License 5 votes vote down vote up
/**
 * get cookie by request
 *
 * @param request
 * @param loginCookieToken
 * @return
 */
private String getCookieValue(HttpServletRequest request, String loginCookieToken) {
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if (c.getName().equals(loginCookieToken)) {
            return c.getValue();
        }
    }
    return null;
}
 
Example 15
Source File: ParameterMap.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private Object getCookieValue(String key) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
    }
    return null;
}
 
Example 16
Source File: LoginWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static String getAutoUserLoginId(HttpServletRequest request) {
    String autoUserLoginId = null;
    Cookie[] cookies = request.getCookies();
    if (Debug.verboseOn()) Debug.logVerbose("Cookies:" + Arrays.toString(cookies), module); // SCIPIO: Fixed array print
    if (cookies != null) {
        for (Cookie cookie: cookies) {
            if (cookie.getName().equals(getAutoLoginCookieName(request))) {
                autoUserLoginId = cookie.getValue();
                break;
            }
        }
    }
    return autoUserLoginId;
}
 
Example 17
Source File: PixelServlet.java    From wt1 with Apache License 2.0 4 votes vote down vote up
/**
 * Sets or refreshes the third-party cookie, and returns its value.
 * @param generate Generate a global id if none
 * @param seed Seed to be used to generate the global id, or null if none
 * @return The global visitor id, or null if none, or the empty string if the user has opted out third-party tracking.  
 */
public static String getThirdPartyCookie(HttpServletRequest req, HttpServletResponse resp,
		boolean generate, String seed) {
	if (! ProcessingQueue.getInstance().isThirdPartyCookies()) {
		return null;
	}

	// Look for existing cookies
	String globalVisitorId = null;
	String optoutCookieVal = null;
	if (req.getCookies() != null) {
		for (Cookie cookie : req.getCookies()) {
			if (cookie.getName().equals(VISITOR_ID_THIRD_PARTY_COOKIE)) {
				globalVisitorId = cookie.getValue();
			} else if (cookie.getName().equals(VISITOR_ID_OPTOUT_COOKIE)) {
				optoutCookieVal = cookie.getValue();
			}
		}
	}
	
	// Send P3P header if configured
	String p3pHeader = ProcessingQueue.getInstance().getP3PHeader();
	if (p3pHeader != null) {
		resp.setHeader("P3P", p3pHeader);
	}
	
	// Parse and echo DNT header if present
	if (! ProcessingQueue.getInstance().isIgnoreDNT()) {
		String doNotTrackVal = req.getHeader(DO_NOT_TRACK_HEADER);
		if (doNotTrackVal != null) {
			resp.addHeader(DO_NOT_TRACK_HEADER, doNotTrackVal);
			if (doNotTrackVal.equals("1")) {
				// Remove any third-party cookie
				if (globalVisitorId != null) {
					setCookie(resp, VISITOR_ID_THIRD_PARTY_COOKIE, "0", 0);
				}
				if (optoutCookieVal != null) {
					setCookie(resp, VISITOR_ID_OPTOUT_COOKIE, "0", 0);
				}
				return "";
			}
		}
	}
	
	if (optoutCookieVal != null && optoutCookieVal.equals("1")) {
		/* Refresh the opt-out cookie. */
		setCookie(resp, VISITOR_ID_OPTOUT_COOKIE, "1", VISITOR_ID_OPTOUT_COOKIE_LIFETIME);
		return "";
	}

	if (globalVisitorId == null || globalVisitorId.equals("0")) {
		if (generate) {
			globalVisitorId = (seed == null) ? UUIDGenerator.generate() : UUIDGenerator.fromSeed(seed);
		} else {
			globalVisitorId = null;
		}
	}
	if (globalVisitorId != null) {
		/* Refresh the global visitor id cookie */
		setCookie(resp, VISITOR_ID_THIRD_PARTY_COOKIE, globalVisitorId, VISITOR_ID_THIRD_PARTY_COOKIE_LIFETIME);
	}
	return globalVisitorId;
}
 
Example 18
Source File: CookieUtils.java    From opencron with Apache License 2.0 4 votes vote down vote up
public static String getCookieValue(HttpServletRequest request, String name) {
    Cookie c = getCookie(request, name);
    return c != null ? c.getValue() : null;
}
 
Example 19
Source File: CookieLocaleResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
	if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
		Locale locale = null;
		TimeZone timeZone = null;

		// Retrieve and parse cookie value.
		String cookieName = getCookieName();
		if (cookieName != null) {
			Cookie cookie = WebUtils.getCookie(request, cookieName);
			if (cookie != null) {
				String value = cookie.getValue();
				String localePart = value;
				String timeZonePart = null;
				int separatorIndex = localePart.indexOf('/');
				if (separatorIndex == -1) {
					// Leniently accept older cookies separated by a space...
					separatorIndex = localePart.indexOf(' ');
				}
				if (separatorIndex >= 0) {
					localePart = value.substring(0, separatorIndex);
					timeZonePart = value.substring(separatorIndex + 1);
				}
				try {
					locale = (!"-".equals(localePart) ? parseLocaleValue(localePart) : null);
					if (timeZonePart != null) {
						timeZone = StringUtils.parseTimeZoneString(timeZonePart);
					}
				}
				catch (IllegalArgumentException ex) {
					String cookieDescription = "invalid locale cookie '" + cookieName +
							"': [" + value + "] due to: " + ex.getMessage();
					if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
						// Error dispatch: ignore locale/timezone parse exceptions
						if (logger.isDebugEnabled()) {
							logger.debug("Ignoring " + cookieDescription);
						}
					}
					else {
						throw new IllegalStateException("Encountered " + cookieDescription);
					}
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
							"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
				}
			}
		}

		request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
				(locale != null ? locale : determineDefaultLocale(request)));
		request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
				(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
	}
}
 
Example 20
Source File: WebSSOResourceTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testDefaultTTL() throws Exception {

  ServletContext context = EasyMock.createNiceMock(ServletContext.class);
  EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(expectGatewayConfig()).anyTimes();
  EasyMock.expect(context.getInitParameter("knoxsso.cookie.name")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.cookie.secure.only")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.cookie.max.age")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.cookie.domain.suffix")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.redirect.whitelist.regex")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.token.audiences")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.token.ttl")).andReturn(null);
  EasyMock.expect(context.getInitParameter("knoxsso.enable.session")).andReturn(null);

  HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
  EasyMock.expect(request.getParameter("originalUrl")).andReturn("http://localhost:9080/service");
  EasyMock.expect(request.getParameterMap()).andReturn(Collections.emptyMap());
  EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes();

  Principal principal = EasyMock.createNiceMock(Principal.class);
  EasyMock.expect(principal.getName()).andReturn("alice").anyTimes();
  EasyMock.expect(request.getUserPrincipal()).andReturn(principal).anyTimes();

  GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
  EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(services);

  JWTokenAuthority authority = new TestJWTokenAuthority(gatewayPublicKey, gatewayPrivateKey);
  EasyMock.expect(services.getService(ServiceType.TOKEN_SERVICE)).andReturn(authority);

  HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
  ServletOutputStream outputStream = EasyMock.createNiceMock(ServletOutputStream.class);
  CookieResponseWrapper responseWrapper = new CookieResponseWrapper(response, outputStream);

  EasyMock.replay(principal, services, context, request);

  WebSSOResource webSSOResponse = new WebSSOResource();
  webSSOResponse.request = request;
  webSSOResponse.response = responseWrapper;
  webSSOResponse.context = context;
  webSSOResponse.init();

  // Issue a token
  webSSOResponse.doGet();

  // Check the cookie
  Cookie cookie = responseWrapper.getCookie("hadoop-jwt");
  assertNotNull(cookie);

  JWT parsedToken = new JWTToken(cookie.getValue());
  assertEquals("alice", parsedToken.getSubject());
  assertTrue(authority.verifyToken(parsedToken));

  Date expiresDate = parsedToken.getExpiresDate();
  Date now = new Date();
  assertTrue(expiresDate.after(now));
  assertTrue((expiresDate.getTime() - now.getTime()) < 30000L);
}