List of usage examples for javax.servlet.http Cookie setSecure
public void setSecure(boolean flag)
From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceImpl.java
/** * @param userId//from w w w . j a v a 2 s . com * @param response */ void addCookie(HttpServletResponse response, String userId, String tokenType) { Cookie c = new HttpOnlyCookie(trustedAuthCookieName, encodeCookie(userId, tokenType)); c.setMaxAge(-1); c.setPath("/"); c.setSecure(secureCookie); response.addCookie(c); // rfc 2109 section 4.5. stop http 1.1 caches caching the response response.addHeader("Cache-Control", "no-cache=\"set-cookie\" "); // and stop http 1.0 caches caching the response response.addDateHeader("Expires", 0); }
From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java
/** * Generate a server side cookie given the cookie value as the input. * @param str Input string token.//from w ww. j a v a 2 s.c om * @return The generated cookie. * @throws UnsupportedEncodingException */ private Cookie createCookie(String str) throws UnsupportedEncodingException { if (LOG.isDebugEnabled()) { LOG.debug("Cookie name = " + AUTH_COOKIE + " value = " + str); } Cookie cookie = new Cookie(AUTH_COOKIE, str); cookie.setMaxAge(cookieMaxAge); if (cookieDomain != null) { cookie.setDomain(cookieDomain); } if (cookiePath != null) { cookie.setPath(cookiePath); } cookie.setSecure(isCookieSecure); return cookie; }
From source file:hudson.security.SecurityRealm.java
/** * Handles the logout processing./* ww w . j a va 2s . com*/ * * <p> * The default implementation erases the session and do a few other clean up, then * redirect the user to the URL specified by {@link #getPostLogOutUrl(StaplerRequest, Authentication)}. * * @since 1.314 */ public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { HttpSession session = req.getSession(false); if (session != null) session.invalidate(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SecurityContextHolder.clearContext(); // reset remember-me cookie Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, ""); cookie.setMaxAge(0); cookie.setSecure(req.isSecure()); cookie.setHttpOnly(true); cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/"); rsp.addCookie(cookie); rsp.sendRedirect2(getPostLogOutUrl(req, auth)); }
From source file:com.qut.middleware.spep.filter.SPEPFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$ }/*from w w w. j a va 2 s . c o m*/ if (!(servletResponse instanceof HttpServletResponse)) { throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$ } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String resource, decodedResource, requested, redirectURL; URL serviceHost; ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName); // Get servlet context. if (spepContext == null) { throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$ } // Establish SPEPProxy object. SPEPProxy spep; try { spep = Initializer.init(spepContext); } catch (Exception e) { this.logger.error( "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n" + e.getLocalizedMessage()); throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$ } // Ensure SPEP startup. if (!spep.isStarted()) { // Don't allow anything to occur if SPEP hasn't started correctly. this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty "); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$ } // Get SPEP cookie. Cookie spepCookie = null; Cookie globalESOECookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(spep.getTokenName())) { spepCookie = cookie; this.logger.debug("Located spep cookie with value of " + spepCookie.getValue()); } if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) { globalESOECookie = cookie; this.logger .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue()); } } } // value for re-determining session status after Authz request boolean validSession = false; // Check SPEP session is valid. if (spepCookie != null) { String sessionID = spepCookie.getValue(); this.logger.info("Attempting to retrieve data for session with ID of " + sessionID); PrincipalSession PrincipalSession = spep.verifySession(sessionID); if (PrincipalSession != null) { this.logger.info("Located session with ID of " + sessionID); if (request.getSession().getAttribute(ATTRIBUTES) == null) { // over write with new data if it exists WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>(); attributeMap.putAll(PrincipalSession.getAttributes()); attributeMap.close(); request.getSession().setAttribute(ATTRIBUTES, attributeMap); request.getSession().setAttribute(SPEP_SESSIONID, sessionID); } /* * This section of code is critical, we must pass the PEP an exact representation of what the user is * attempting to access additionally the PEP expects that the string is not in encoded form as it will * do exact matching, so we decode before passing our request to it. */ resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource); // the authz processor may destroy the session if the PDP determines that the client // session is no longer valid, so we have to check it again if ((PrincipalSession = spep.verifySession(sessionID)) != null) validSession = true; if (validSession) { if (authzDecision == SPEPProxy.decision.permit) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was permissable"); chain.doFilter(request, response); return; } else if (authzDecision == SPEPProxy.decision.deny) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was denied, forcing response of" + HttpServletResponse.SC_FORBIDDEN); response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else if (authzDecision == SPEPProxy.decision.error) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was in error, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$ } else { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was undetermined, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$ } } } /* Clear the local session object the supplied request is invalid */ this.logger.debug("Invalidating session for ID of " + sessionID); request.getSession().invalidate(); } /* * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have * come back to the SPEP since logging out. */ List<Cookie> clearCookies = new Vector<Cookie>(); if (cookies != null) { for (Cookie cookie : cookies) { if (spep.getLogoutClearCookies() != null) { for (Cookie clearCookie : spep.getLogoutClearCookies()) { if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) { Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone(); clearCookieCloneInsecure.setMaxAge(0); clearCookieCloneInsecure.setSecure(false); clearCookies.add(clearCookieCloneInsecure); // Don't need to process the inner loop again for this cookie. break; } } } } } /* Add the cookies to be cleared into the response object. */ for (Cookie c : clearCookies) response.addCookie(c); /* * Remove any principal object details which may be in the session, this state can occur if the user has removed * their spepSession cookie but retained their jsessionid cookie */ request.getSession().removeAttribute(ATTRIBUTES); /* * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the * logical reasons below they will be forced to authenticate. */ if (spep.isLazyInit()) { this.logger.info( "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP"); /* * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out * if user is accessing something that has been configured to force a session to be established before it is * accessible */ if (globalESOECookie == null) { this.logger.debug("globalESOECookie was not set for this request"); boolean matchedLazyInitResource = false; resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); for (String lazyInitResource : spep.getLazyInitResources()) { if (decodedResource.matches(lazyInitResource)) { matchedLazyInitResource = true; this.logger.info("Lazy session init attempt matched initialization query of " + lazyInitResource + " from request of " + decodedResource); } else this.logger.debug("Lazy session init attempt failed to match initialization query of " + lazyInitResource + " from request of " + decodedResource); } // If we still have no reason to engage spep functionality for this request let the request pass if (matchedLazyInitResource) { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } else { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } } } /* * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically */ this.logger.debug("Failed all avenues to provide access to content"); if (request.getQueryString() != null) requested = request.getRequestURI() + "?" + request.getQueryString(); else requested = request.getRequestURI(); /* * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to * the local node. */ serviceHost = new URL(spep.getServiceHost()); String ssoRedirect = spep.getSsoRedirect(); String timestampParameter; if (ssoRedirect.indexOf('?') > -1) { timestampParameter = "&ts=" + System.currentTimeMillis(); } else { timestampParameter = "?ts=" + System.currentTimeMillis(); } if (request.getServerName().equals(serviceHost.getHost())) { /* Ensures that SSL offloading in Layer 7 environments is correctly handled */ requested = spep.getServiceHost() + requested; String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } else { String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } this.logger.debug("Redirecting to " + redirectURL + " to establish secure session"); response.sendRedirect(redirectURL); }
From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java
/** Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. *//*from ww w . jav a 2 s . c om*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:org.jahia.bin.Logout.java
protected void removeAuthCookie(HttpServletRequest request, HttpServletResponse response) { // now let's destroy the cookie authentication if there was one // set for this user. JahiaUser curUser = JCRSessionFactory.getInstance().getCurrentUser(); JCRPropertyWrapper cookieAuthKey = null; try {//ww w .j av a 2s .c o m if (!JahiaUserManagerService.isGuest(curUser)) { JCRUserNode userNode = userManagerService.lookupUserByPath(curUser.getLocalPath()); String userPropertyName = cookieAuthConfig.getUserPropertyName(); if (userNode != null && userNode.hasProperty(userPropertyName)) { cookieAuthKey = userNode.getProperty(userPropertyName); } } if (cookieAuthKey != null) { Cookie authCookie = new Cookie(cookieAuthConfig.getCookieName(), cookieAuthKey.getString()); authCookie .setPath(StringUtils.isNotEmpty(request.getContextPath()) ? request.getContextPath() : "/"); authCookie.setMaxAge(0); // means we want it deleted now ! authCookie.setHttpOnly(cookieAuthConfig.isHttpOnly()); authCookie.setSecure(cookieAuthConfig.isSecure()); response.addCookie(authCookie); cookieAuthKey.remove(); cookieAuthKey.getSession().save(); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } }
From source file:com.tremolosecurity.proxy.SessionManagerImpl.java
private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx) throws Exception { byte[] idBytes = new byte[20]; random.nextBytes(idBytes);//from w ww . j av a2 s .com StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); // HttpSession session = req.getSession(true); TremoloHttpSession tsession = new TremoloHttpSession(id); tsession.setOpen(true); tsession.refresh(this.ctx, this); this.anonMech.createSession(tsession, this.anonChainType); AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL); AuthInfo auInfo = actl.getAuthInfo(); auInfo.setAuthComplete(true); // session.setAttribute(app.getCookieConfig().getSessionCookieName(), // tsession); tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id); // TODO add global session timeout // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout()); // TODO add global open session name Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id); sessionCookie.setPath("/"); sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure()); sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly()); sessionCookie.setMaxAge(-1); // TODO add secure? // sessionCookie.setSecure(app.getCookieConfig().isSecure()); resp.addCookie(sessionCookie); sessions.put(id, tsession); return tsession; }
From source file:wicket.markup.html.form.persistence.CookieValuePersister.java
/** * Persist/save the data using Cookies.//www . j a va2 s . com * * @param cookie * The Cookie to be persisted. * @return The cookie provided */ private Cookie save(final Cookie cookie) { if (cookie == null) { return null; } final String comment = getSettings().getComment(); if (comment != null) { cookie.setComment(comment); } final String domain = getSettings().getDomain(); if (domain != null) { cookie.setDomain(domain); } cookie.setPath(getWebRequest().getContextPath()); cookie.setVersion(getSettings().getVersion()); cookie.setSecure(getSettings().getSecure()); getWebResponse().addCookie(cookie); if (log.isDebugEnabled()) { log.debug("saved: " + cookieToDebugString(new CookieWrapper(cookie))); } return cookie; }
From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java
/** * Sets the cookie on the response.//from www .ja va 2 s. c o m * * By default a secure cookie will be used if the connection is secure. You can set * the {@code useSecureCookie} property to {@code false} to override this. If you set * it to {@code true}, the cookie will always be flagged as secure. By default the cookie * will be marked as HttpOnly. * * @param tokens the tokens which will be encoded to make the cookie value. * @param maxAge the value passed to {@link Cookie#setMaxAge(int)} * @param request the request * @param response the response to add the cookie to. */ protected void setCookie(String[] tokens, int maxAge, HttpServletRequest request, HttpServletResponse response) { String cookieValue = encodeCookie(tokens); Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge(maxAge); cookie.setPath(getCookiePath(request)); if (cookieDomain != null) { cookie.setDomain(cookieDomain); } if (maxAge < 1) { cookie.setVersion(1); } if (useSecureCookie == null) { cookie.setSecure(request.isSecure()); } else { cookie.setSecure(useSecureCookie); } cookie.setHttpOnly(true); response.addCookie(cookie); }
From source file:uk.ac.ox.webauth.FilterWorker.java
/** * Set an app cookie authenticating the user to this WAS. * @param webauthr The users WEBAUTHR token. * @param privateKey The private WAS key to encrypt the app cookie with. * @param response The response object to send the cookie to. *//*from w ww . j a v a 2 s. co m*/ private void setAppCookie(Token webauthr, WebauthKey privateKey, HttpServletResponse response) throws ServletException { // set a cookie containing an app-token identifying the user Token app = new Token(); app.add("t", "app"); app.add("s", webauthr.getString("s")); app.add("et", webauthr.getBinary("et")); app.add("ct", Token.unixTimestampBytes(System.currentTimeMillis())); // If we want the last-used time to be updated it means the cookie has to be reencrypted each time that // is done, and that costs cpu time, so disabled for now. //app.add("lt", now); String encrypted = null; try { encrypted = app.encrypt(privateKey.key()); } catch (GeneralSecurityException gse) { throw new ServletException("Could not encrypt app-token.", gse); } Cookie webauth_at = new Cookie("webauth_at", encrypted); webauth_at.setMaxAge(-1); webauth_at.setSecure(true); webauth_at.setPath("/"); response.addCookie(webauth_at); cookies.put(webauth_at.getName(), webauth_at); }