Java Code Examples for javax.servlet.http.Cookie#setPath()
The following examples show how to use
javax.servlet.http.Cookie#setPath() .
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: CsrfCookieGeneratorFilter.java From demo-spring-security-cas with Apache License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Spring put the CSRF token in session attribute "_csrf" CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf"); // Send the cookie only if the token has changed String actualToken = request.getHeader("X-CSRF-TOKEN"); if (actualToken == null || !actualToken.equals(csrfToken.getToken())) { // Session cookie that will be used by AngularJS String pCookieName = "CSRF-TOKEN"; Cookie cookie = new Cookie(pCookieName, csrfToken.getToken()); cookie.setMaxAge(-1); cookie.setHttpOnly(false); cookie.setPath("/"); response.addCookie(cookie); } filterChain.doFilter(request, response); }
Example 2
Source File: DefaultHttpSessionManager.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Create the session. * * @param webApplication the web application. * @param request the request. * @return the session. */ @Override public synchronized HttpSession createSession(WebApplication webApplication, HttpServletRequest request) { String sessionId = UUID.randomUUID().toString(); DefaultHttpSession session = new DefaultHttpSession(webApplication, sessionId, true); session.setSessionManager(this); sessions.put(sessionId, session); HttpServletResponse response = (HttpServletResponse) webApplication.getResponse(request); Cookie cookie = new Cookie(name, sessionId); if (path != null) { cookie.setPath(path); } else { cookie.setPath("".equals(webApplication.getContextPath())? "/" : webApplication.getContextPath()); } response.addCookie(cookie); sessionListeners.stream().forEach((sessionListener) -> { sessionListener.sessionCreated(new HttpSessionEvent(session)); }); return session; }
Example 3
Source File: GrafanaAuthenticationTest.java From Insights with Apache License 2.0 | 6 votes |
@BeforeTest public void onInit() throws InterruptedException, IOException { ApplicationConfigCache.loadConfigCache(); Map<String, String> cookiesMap = null; try { httpRequest.addHeader("Authorization", GrafanaAuthenticationTestData.authorization); cookiesMap = PlatformServiceUtil.getGrafanaCookies(httpRequest); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } cookiesString = cookiesMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.joining(";")); log.debug(" cookiesString " + cookiesString); for (Map.Entry<String, String> entry : cookiesMap.entrySet()) { Cookie cookie = new Cookie(entry.getKey(), entry.getValue()); cookie.setHttpOnly(true); cookie.setMaxAge(60 * 30); cookie.setPath("/"); httpRequest.setCookies(cookie); } }
Example 4
Source File: CustomAuthenticationSuccessHandler.java From oauth2-client with MIT License | 5 votes |
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String redirectUrl = ""; SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest != null && StringUtils.isNotEmpty(savedRequest.getRedirectUrl())) { redirectUrl = savedRequest.getRedirectUrl(); } // 根据需要设置 cookie,js携带token直接访问api接口等 if (authentication instanceof OAuth2AuthenticationToken) { OAuth2AuthorizedClient client = authorizedClientService .loadAuthorizedClient( ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId(), authentication.getName()); String token = client.getAccessToken().getTokenValue(); Cookie tokenCookie = new Cookie("access_token", token); tokenCookie.setHttpOnly(true); tokenCookie.setDomain(cookieDomain); tokenCookie.setPath("/"); response.addCookie(tokenCookie); } //设置回调成功的页面, if (StringUtils.isNotEmpty(redirectUrl)) { super.onAuthenticationSuccess(request, response, authentication); } else { response.sendRedirect("/"); } }
Example 5
Source File: HttpUtils.java From scoold with Apache License 2.0 | 5 votes |
/** * Sets a cookie. * @param name the name * @param value the value * @param req HTTP request * @param res HTTP response * @param httpOnly HTTP only flag * @param maxAge max age */ public static void setRawCookie(String name, String value, HttpServletRequest req, HttpServletResponse res, boolean httpOnly, int maxAge) { if (StringUtils.isBlank(name) || value == null || req == null || res == null) { return; } Cookie cookie = new Cookie(name, value); cookie.setHttpOnly(httpOnly); cookie.setMaxAge(maxAge < 0 ? Config.SESSION_TIMEOUT_SEC : maxAge); cookie.setPath(CONTEXT_PATH.isEmpty() ? "/" : CONTEXT_PATH); cookie.setSecure(req.isSecure()); res.addCookie(cookie); }
Example 6
Source File: Providers.java From dubbo3 with Apache License 2.0 | 5 votes |
/** * 设置search记录到cookie中,操作步骤: * 检查加入的记录是否已经存在cookie中,如果存在,则更新列表次序;如果不存在,则插入到最前面 * @param context * @param value */ private void setSearchHistroy(Map<String, Object> context, String value) { //分析已有的cookie 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; } } count ++; } break; } } Cookie _cookie=new Cookie("HISTORY", newCookiev); _cookie.setMaxAge(60*60*24*7); // 设置Cookie的存活时间为30分钟 _cookie.setPath("/"); response.addCookie(_cookie); // 写入客户端硬盘 }
Example 7
Source File: AccessResource.java From nifi with Apache License 2.0 | 5 votes |
private void removeOidcRequestCookie(final HttpServletResponse httpServletResponse) { final Cookie cookie = new Cookie(OIDC_REQUEST_IDENTIFIER, null); cookie.setPath("/"); cookie.setHttpOnly(true); cookie.setMaxAge(0); cookie.setSecure(true); httpServletResponse.addCookie(cookie); }
Example 8
Source File: HttpCookieManager.java From javamelody with Apache License 2.0 | 5 votes |
void addCookie(HttpServletRequest req, HttpServletResponse resp, String cookieName, String cookieValue) { if (!"added".equals(req.getAttribute(cookieName))) { final Cookie cookie = new Cookie(cookieName, cookieValue); // cookie persistant, valide pendant 30 jours cookie.setMaxAge(30 * 24 * 60 * 60); // inutile d'envoyer ce cookie aux autres URLs que le monitoring cookie.setPath(req.getRequestURI()); resp.addCookie(cookie); req.setAttribute(cookieName, "added"); } }
Example 9
Source File: LoginController.java From xiaoyaoji with GNU General Public License v3.0 | 5 votes |
private Cookie setCookie(String token,User user){ CacheUtils.putUser(token, user); Cookie cookie = new Cookie(Constants.TOKEN_COOKIE_NAME,token); cookie.setPath("/"); cookie.setMaxAge(ConfigUtils.getTokenExpires()); return cookie; }
Example 10
Source File: ToolsUtil.java From jivejdon with Apache License 2.0 | 5 votes |
public static void removeSessionCookie(HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie("JSESSIONID", ""); cookie.setMaxAge(0); // 立即删除型 cookie.setPath("/"); // 项目所有目录均有效,这句很关键,否则不敢保证删除 cookie.setDomain(request.getHeader("host")); response.addCookie(cookie); // 重新写入,将覆盖之前的%> }
Example 11
Source File: AccountController.java From kaif with Apache License 2.0 | 5 votes |
@RequestMapping("/activation") public ModelAndView activation(@RequestParam("key") String key, HttpServletResponse response) { boolean success = accountService.activate(key); if (success) { //see AccountSession.dart#detectForceLogout(); Cookie cookie = new Cookie("force-logout", "true"); cookie.setPath("/"); cookie.setSecure(true); response.addCookie(cookie); } return new ModelAndView("account/activation").addObject("success", success); }
Example 12
Source File: SLIPostAuthentication.java From secure-data-service with Apache License 2.0 | 5 votes |
@Override public void onLoginSuccess(Map requestParams, HttpServletRequest request, HttpServletResponse response, SSOToken token) throws AuthenticationException { log(token.getTokenID()); for (Object key : requestParams.keySet()) { log(key + " -> " + requestParams.get(key)); } String sessionId = token.getTokenID().toString(); response.setContentType("text/html"); response.addHeader("X-sli-session", sessionId); response.setHeader("X-sli-session", sessionId); Cookie c = new Cookie("sliSessionId", sessionId); c.setPath("/"); c.setDomain(".slidev.org"); c.setMaxAge(5 * 60); response.addCookie(c); Cookie c2 = new Cookie("sliSessionId", sessionId); c2.setPath("/"); c2.setDomain(".dk.com"); c2.setMaxAge(5 * 60); response.addCookie(c2); Cookie c3 = new Cookie("fversion", "1:51"); c.setPath("/"); c.setDomain(".slidev.org"); c.setMaxAge(5 * 60); response.addCookie(c3); }
Example 13
Source File: CookieUtils.java From sso-oauth2 with Apache License 2.0 | 5 votes |
/** * 销毁cookie * * @param response * @param tokenName * @return */ public static boolean delCookieValue(HttpServletResponse response, String tokenName) { try { Cookie cookie = new Cookie(tokenName, ""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example 14
Source File: CookieUtils.java From sso-oauth2 with Apache License 2.0 | 5 votes |
/** * accessToken生存时间设置为30min * * refreshToken生存时间设置为1天 * * @param response * @param path * @param time * @param accessToken */ public static void setCookieValue(HttpServletResponse response, String path, Integer time, AccessTokenModel accessToken) { /* * P3P解决跨域 */ response.addHeader("P3P", "CP=CAO PSA OUR"); // response.setHeader("P3P","CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa // PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM // CNT PRE LOC\""); // accessToken及账号 Map<String, String> map1 = new HashMap<String, String>(); map1.put("accessToken", accessToken.getAccessToken()); map1.put("account", accessToken.getAccount()); Cookie cookie1 = new Cookie("accessToken", JsonTools.mapToJson(map1).toString()); cookie1.setPath(path); cookie1.setMaxAge(time); response.addCookie(cookie1); // refreshToken及账号 Map<String, String> map2 = new HashMap<String, String>(); map2.put("refreshToken", accessToken.getRefreshToken()); map2.put("account", accessToken.getAccount()); Cookie cookie2 = new Cookie("refreshToken", JsonTools.mapToJson(map2).toString()); cookie2.setPath(path); cookie2.setMaxAge(86400);// refreshToken默认一天 response.addCookie(cookie2); }
Example 15
Source File: AuthenticationFilter.java From oxTrust with MIT License | 5 votes |
private Cookie cloneCokie(Cookie sourceCookie, String newValue, int maxAge) { Cookie resultCookie = new Cookie(sourceCookie.getName(), newValue); resultCookie.setPath("/"); resultCookie.setMaxAge(maxAge); resultCookie.setVersion(1); resultCookie.setSecure(true); return resultCookie; }
Example 16
Source File: Response.java From pippo with Apache License 2.0 | 5 votes |
private void addCookie(Cookie cookie) { checkCommitted(); if (StringUtils.isNullOrEmpty(cookie.getPath())) { cookie.setPath(StringUtils.addStart(contextPath, "/")); } getCookieMap().put(cookie.getName(), cookie); }
Example 17
Source File: CookieMonster.java From cs601 with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void killCookie(HttpServletResponse response, String name) { Cookie c = new Cookie(name,"false"); c.setMaxAge( 0 ); // An age of 0 is defined to mean "delete cookie" c.setPath( "/" ); // for all subdirs response.addCookie( c ); }
Example 18
Source File: SakaiLogin.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Actual login method * @param id * @param pw * @return */ private java.lang.String login(java.lang.String id, java.lang.String pw) { Message message = PhaseInterceptorChain.getCurrentMessage(); HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); String ipAddress = request.getRemoteAddr(); boolean allowLogin = serverConfigurationService.getBoolean("webservices.allowlogin", false); if (!allowLogin) { throw new RuntimeException("Web Services Login Disabled"); } try { if ("GET".equals(request.getMethod())) { log.info("This endpoint {} should use POST instead of GET, GET will be deprecated in a future release", request.getRequestURI()); } Evidence e = new IdPwEvidence(id, pw, ipAddress); Authentication a = authenticationManager.authenticate(e); Session s = sessionManager.startSession(); sessionManager.setCurrentSession(s); if (s == null) { log.warn("Web Services Login failed to establish session for id=" + id + " ip=" + ipAddress); throw new RuntimeException("Unable to establish session"); } else { // We do not care too much on the off-chance that this fails - folks simply won't show up in presense // and events won't be trackable back to people / IP Addresses - but if it fails - there is nothing // we can do anyways. usageSessionService.login(a.getUid(), id, ipAddress, "SakaiLogin", UsageSessionService.EVENT_LOGIN_WS); log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId()); // retrieve the configured cookie name, if any if (System.getProperty(RequestFilter.SAKAI_COOKIE_PROP) != null) { cookieName = System.getProperty(RequestFilter.SAKAI_COOKIE_PROP); } // retrieve the configured cookie domain, if any // compute the session cookie suffix, based on this configured server id String suffix = System.getProperty(RequestFilter.SAKAI_SERVERID); if (StringUtils.isEmpty(suffix)) { if (m_displayModJkWarning) { log.warn("no sakai.serverId system property set - mod_jk load balancing will not function properly"); } m_displayModJkWarning = false; suffix = "sakai"; } Cookie c = new Cookie(cookieName, s.getId() + "." + suffix); c.setPath("/"); c.setMaxAge(-1); if (System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN) != null) { c.setDomain(System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN)); } if (request.isSecure() == true) { c.setSecure(true); } HttpServletResponse res = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP_RESPONSE); if (res != null) { res.addCookie(c); } log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId()); return s.getId(); } } catch (AuthenticationException ex) { log.warn("Failed Web Services Login id=" + id + " ip=" + ipAddress + ": " + ex.getMessage()); } throw new RuntimeException("Unable to login"); }
Example 19
Source File: LoadBalancerDrainingValve.java From Tomcat8-Source-Read with MIT License | 4 votes |
@Override public void invoke(Request request, Response response) throws IOException, ServletException { if ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) && !request.isRequestedSessionIdValid()) { if (containerLog.isDebugEnabled()) { containerLog.debug("Load-balancer is in DISABLED state; draining this node"); } boolean ignoreRebalance = false; Cookie sessionCookie = null; final Cookie[] cookies = request.getCookies(); final String sessionCookieName = SessionConfig.getSessionCookieName(request.getContext()); if (null != cookies) { for (Cookie cookie : cookies) { final String cookieName = cookie.getName(); if (containerLog.isTraceEnabled()) { containerLog.trace("Checking cookie " + cookieName + "=" + cookie.getValue()); } if (sessionCookieName.equals(cookieName) && request.getRequestedSessionId().equals(cookie.getValue())) { sessionCookie = cookie; } else if (null != _ignoreCookieName && _ignoreCookieName.equals(cookieName) && null != _ignoreCookieValue && _ignoreCookieValue.equals(cookie.getValue())) { // The client presenting a valid ignore-cookie value? ignoreRebalance = true; } } } if (ignoreRebalance) { if (containerLog.isDebugEnabled()) { containerLog.debug("Client is presenting a valid " + _ignoreCookieName + " cookie, re-balancing is being skipped"); } getNext().invoke(request, response); return; } // Kill any session cookie that was found // TODO: Consider implications of SSO cookies if (null != sessionCookie) { sessionCookie.setPath(SessionConfig.getSessionCookiePath(request.getContext())); sessionCookie.setMaxAge(0); // Delete sessionCookie.setValue(""); // Purge the cookie's value response.addCookie(sessionCookie); } // Re-write the URI if it contains a ;jsessionid parameter String uri = request.getRequestURI(); String sessionURIParamName = SessionConfig.getSessionUriParamName(request.getContext()); if (uri.contains(";" + sessionURIParamName + "=")) { uri = uri.replaceFirst(";" + sessionURIParamName + "=[^&?]*", ""); } String queryString = request.getQueryString(); if (null != queryString) { uri = uri + "?" + queryString; } // NOTE: Do not call response.encodeRedirectURL or the bad // sessionid will be restored response.setHeader("Location", uri); response.setStatus(_redirectStatusCode); } else { getNext().invoke(request, response); } }
Example 20
Source File: WebUtils.java From smaker with GNU Lesser General Public License v3.0 | 3 votes |
/** * 设置cookie * * @param response HttpServletResponse * @param name cookie name * @param value cookie value * @param maxAgeInSeconds maxage */ public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAgeInSeconds); cookie.setHttpOnly(true); response.addCookie(cookie); }