Example usage for javax.servlet.http Cookie setPath

List of usage examples for javax.servlet.http Cookie setPath

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setPath.

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:com.vmware.identity.openidconnect.server.LogoutRequestProcessor.java

private Cookie loggedOutSessionCookie() {
    Cookie cookie = new Cookie(SessionManager.getSessionCookieName(this.tenant), "");
    cookie.setPath("/openidconnect");
    cookie.setSecure(true);/*from w ww  .  j a  v  a2s  . c o m*/
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0);
    return cookie;
}

From source file:org.bibsonomy.webapp.util.CookieLogic.java

/** Adds a cookie to the response. Sets default values for path and maxAge. 
 * /* w w  w  .j a  va2  s. c  om*/
 * @param key - The key identifying this cookie.
 * @param value - The value of the cookie.
 */
private void addCookie(final String key, final String value) {
    log.debug("Adding cookie " + key + ": " + value);
    final Cookie cookie = new Cookie(key, value);
    cookie.setPath(cookiePath);
    cookie.setMaxAge(cookieAge);
    responseLogic.addCookie(cookie);
}

From source file:pl.szcze.userserviceproject.CsrfHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

    if (csrfToken != null) {
        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
        String token = csrfToken.getToken();

        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);//from  ww w .j a  v a 2s . co m
        }
    }

    filterChain.doFilter(request, response);
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java

/**
 * Sets dynamically the {@link Cookie#setPath(String)} value using available
 * {@link HttpServletRequest#getContextPath()}.
 */// w  ww  . j  av  a 2s  .c  o  m
protected void setEnhancedCookiePath(final Cookie cookie) {
    if (!canUseDefaultPath()) {
        final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        cookie.setPath(request.getContextPath());
    }
}

From source file:org.ohmage.request.auth.AuthTokenLogoutRequest.java

@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    LOGGER.info("Responding to the logout request.");

    if (getUser() != null) {
        final String token = getUser().getToken();

        if (token != null) {

            Cookie authTokenCookie = new Cookie(InputKeys.AUTH_TOKEN, token);
            authTokenCookie.setHttpOnly(false);
            authTokenCookie.setMaxAge(0);
            authTokenCookie.setPath("/");
            httpResponse.addCookie(authTokenCookie);

        }//from w w  w  .j  a va 2s  .com
        UserBin.expireUser(token);
    }

    JSONObject response = new JSONObject();
    try {
        response.put(JSON_KEY_METADATA, JSONObject.NULL);
        response.put(JSON_KEY_DATA, JSONObject.NULL);
    } catch (JSONException e) {
        LOGGER.error("There was an error building the response.", e);
        setFailed();

    }

    super.respond(httpRequest, httpResponse, response);
}

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

public void writeNewMessages() {
    if (logger.isDebugEnabled()) {
        logger.debug("writeNextMessages");
    }/*from www  .j a v a2  s . com*/
    HttpServletResponse response = invocation.getResponse();
    List<String> responseCookies = null;
    for (Map.Entry<String, String> entry : next.entrySet()) {
        if (responseCookies == null) {
            responseCookies = new ArrayList<String>(next.size());
        }
        String cookieValue;
        if (entry.getValue() == null) {
            cookieValue = "";
        } else {
            try {
                cookieValue = base64.encodeToString(entry.getValue().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new Error(e);
            }
        }
        Cookie cookie = new Cookie(cookiePrefix + entry.getKey(), cookieValue);
        cookie.setPath("/");
        // cookie.setMaxAge(1);
        response.addCookie(cookie);
        responseCookies.add(cookie.getName());
        if (logger.isDebugEnabled()) {
            logger.debug("write flash cookie:" + cookie.getName() + "=" + cookie.getValue());
        }
    }
    for (Map.Entry<String, String> entry : last.entrySet()) {
        if (responseCookies == null || !responseCookies.contains(entry.getKey())) {
            Cookie c = new Cookie(entry.getKey(), null);
            c.setMaxAge(0);
            c.setPath("/");
            response.addCookie(c);
            if (logger.isDebugEnabled()) {
                logger.debug("delete flash cookie:" + c.getName() + "=" + c.getValue());
            }
        }
    }
}

From source file:com.lti.system.MyLogoutFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }/*from  w ww. j  a  v a2 s  . com*/

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (requiresLogout(httpRequest, httpResponse)) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (logger.isDebugEnabled()) {
            logger.debug("Logging out user '" + auth + "' and redirecting to logout page");
        }

        for (int i = 0; i < handlers.length; i++) {
            handlers[i].logout(httpRequest, httpResponse, auth);
        }

        Cookie cookie = new Cookie("jforumSSOCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        cookie = new Cookie("jforumSSOGroupCookie", null);
        cookie.setMaxAge(0);
        cookie.setPath("/jforum");
        httpResponse.addCookie(cookie);

        request.removeAttribute("legalDate");

        sendRedirect(httpRequest, httpResponse, logoutSuccessUrl);

        return;
    }

    chain.doFilter(request, response);
}

From source file:com.sinosoft.one.mvc.web.var.FlashImpl.java

protected synchronized void readLastMessages() {
    if (lastRead) {
        return;// w  w w.  j  av  a  2 s  .  co m
    }
    lastRead = true;
    if (logger.isDebugEnabled()) {
        logger.debug("readLastMessages");
    }
    Cookie[] cookies = invocation.getRequest().getCookies();
    for (int i = 0; cookies != null && i < cookies.length; i++) {
        if (logger.isDebugEnabled()) {
            logger.debug("cookie " + cookies[i].getName() + "=" + cookies[i].getValue() + "; age="
                    + cookies[i].getMaxAge());
        }
        if (cookies[i].getValue() == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("ignore cookie: " + cookies[i].getName());
            }
            continue;
        }
        if (cookies[i].getName().startsWith(cookiePrefix)) {
            StringTokenizer st = new StringTokenizer(cookies[i].getName(), DELIM);
            String[] splits = new String[st.countTokens()];
            for (int j = 0; j < splits.length; j++) {
                splits[j] = st.nextToken();
            }
            if (splits.length < 2) {
                if (logger.isInfoEnabled()) {
                    logger.info("ignore flash cookie: " + cookies[i].getName());
                }
                continue;
            }
            String name = splits[1];
            String cookieValue = cookies[i].getValue();
            String flashMessage;
            if (cookieValue.length() == 0) {
                flashMessage = "";
            } else {
                try {
                    flashMessage = new String(base64.decodeFromString(cookieValue), "UTF-8");
                } catch (Exception e) {
                    logger.error("failed to decode '" + cookieValue + "' as" + " a base64 string", e);
                    flashMessage = cookieValue;
                }
            }
            if (last.size() == 0) {
                last = new LinkedHashMap<String, String>();
            }
            this.last.put(name, flashMessage);
            Cookie cookie = new Cookie(cookies[i].getName(), "");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            invocation.getResponse().addCookie(cookie);
            if (logger.isDebugEnabled()) {
                logger.debug("found flash message:" + name + "=" + flashMessage);
            }
        }
    }
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//  ww w  .  j a v  a  2 s .c om
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:com.xwiki.authentication.AbstractSSOAuthServiceImpl.java

protected XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException {
    Cookie cookie;//from   ww w.  j a v  a 2s  . c  o  m

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie(COOKIE_NAME, context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }

        return null;
    }

    Principal principal = null;

    if (LOG.isDebugEnabled()) {
        Cookie[] cookies = context.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
            }
        }
    }

    cookie = getCookie(COOKIE_NAME, context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(username, password, context);
        if (principal == null) {
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie(COOKIE_NAME, 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());
    }

    return user;
}