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:csns.web.controller.SectionController.java

@RequestMapping("/section/taught")
public String taught(@RequestParam(required = false) Quarter quarter, ModelMap models, HttpSession session,
        HttpServletResponse response) {//from w  ww. ja v a  2  s . c o m
    Cookie cookie = new Cookie("default-home", "/section/taught");
    cookie.setPath("/");
    cookie.setMaxAge(100000000);
    response.addCookie(cookie);

    return list("taught", quarter, models, session);
}

From source file:cn.designthougths.sample.axon.sfav.webui.UIApplication.java

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override/*from  www.j av  a2s . c  o  m*/
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

From source file:de.theit.jenkins.crowd.CrowdServletFilter.java

/**
 * {@inheritDoc}//from  w  ww. ja  v  a  2 s .  c  o m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // check if we have a token
        // if it is not present, we are not / no longer authenticated
        boolean isValidated = false;
        try {
            isValidated = this.configuration.crowdHttpAuthenticator.isAuthenticated(req, res);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
        }

        if (!isValidated) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("User is not logged in (anymore) via Crowd => logout user");
            }
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(null);
            // close the SSO session
            if (null != this.rememberMe) {
                this.rememberMe.logout(req, res);
            }

            // invalidate the current session
            // (see SecurityRealm#doLogout())
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            SecurityContextHolder.clearContext();

            // reset remember-me cookie
            Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "");
            cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
            res.addCookie(cookie);
        } else {
            SecurityContext sc = SecurityContextHolder.getContext();

            if (!(sc.getAuthentication() instanceof CrowdAuthenticationToken)) {
                // user logged in via Crowd, but no Crowd-specific
                // authentication token available
                // => try to auto-login the user
                if (null != this.rememberMe) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine(
                                "User is logged in via Crowd, but no authentication token available; trying auto-login...");
                    }
                    Authentication auth = this.rememberMe.autoLogin(req, res);
                    if (null != auth) {
                        if (LOG.isLoggable(Level.FINE)) {
                            LOG.fine("User sucessfully logged in");
                        }
                        sc.setAuthentication(auth);
                    }
                }
            }
        }
    }

    this.defaultFilter.doFilter(request, response, chain);
}

From source file:com.adito.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/*from w  ww  . j  a v  a 2  s . c  om*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("adito.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:csns.web.controller.SectionController.java

@RequestMapping("/section/evaluated")
public String evaluated(@RequestParam(required = false) Quarter quarter, ModelMap models, HttpSession session,
        HttpServletResponse response) {/*  w w w.j  ava 2  s  .c  o  m*/
    Cookie cookie = new Cookie("default-home", "/section/evaluated");
    cookie.setPath("/");
    cookie.setMaxAge(100000000);
    response.addCookie(cookie);

    return list("evaluated", quarter, models, session);
}

From source file:com.tenduke.example.scribeoauth.SessionManager.java

/**
 * Terminates session.//from  ww w . ja v a2s . c o m
 * @param request Client HTTP request.
 * @param response HTTP response.
 */
public void endSession(final HttpServletRequest request, final HttpServletResponse response) {
    //
    final Cookie cookie = new Cookie(SIGNED_SESSION_COOKIE_NAME, null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:nl.strohalm.cyclos.utils.ResponseHelper.java

/**
 * Adds a cookie with the given name and value set for the context path root
 *///w ww  .  jav a 2  s .  c  o  m
public Cookie addRootCookie(final HttpServletRequest request, final HttpServletResponse response,
        final String name, final Object value) {
    final Cookie cookie = new Cookie(name, value == null ? "" : value.toString());
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
    return cookie;
}

From source file:org.apache.unomi.plugins.baseplugin.actions.MergeProfilesOnPropertyAction.java

public void sendProfileCookie(Profile profile, ServletResponse response) {
    if (response instanceof HttpServletResponse) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        Cookie profileIdCookie = new Cookie(profileIdCookieName, profile.getItemId());
        profileIdCookie.setPath("/");
        profileIdCookie.setMaxAge(cookieAgeInSeconds);
        httpServletResponse.addCookie(profileIdCookie);
    }//from ww w  .  j  a  v a 2 s .c o m
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnResponse(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    String remoteAddress = request.getRemoteAddr();
    this.logger.debug("[Authn for {}] Going to process authentication response.", remoteAddress);

    String base64SAMLDocument = request.getParameter("SAMLResponse");
    if (base64SAMLDocument == null || base64SAMLDocument.length() == 0) {
        throw new AuthenticationException(
                "SAMLResponse request parameter was null. Unable to process response.");
    }/*from   ww w  . j  a  v  a2 s  .  co m*/

    byte[] samlDocument;
    try {
        samlDocument = Base64.decodeBase64(base64SAMLDocument.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationException(
                "Unable to complete authentication because a required character encoding is not supported.", e);
    }
    // Use the AuthnProcessor to unmarshal the response document.
    Response responseObject = spep.getAuthnProcessor().unmarshalResponse(samlDocument);
    this.logger.info(
            "[Authn for {}] Got an authentication response, going to process. Response ID: {}  InResponseTo: {}",
            new Object[] { remoteAddress, responseObject.getID(), responseObject.getInResponseTo() });

    spep.getAuthnProcessor().processAuthnResponse(data, responseObject);

    String sessionID = data.getSessionID();
    if (sessionID == null) {
        throw new AuthenticationException(
                "Session identifier from AuthnProcessor was null. Unable to process SSO event");
    }

    Cookie cookie = new Cookie(spep.getTokenName(), sessionID);

    cookie.setPath("/");
    response.addCookie(cookie);

    try {
        String redirectURL = null;
        String base64RequestURL = data.getRequestURL();
        if (base64RequestURL != null) {
            redirectURL = new String(Base64.decodeBase64(base64RequestURL.getBytes()));
        } else {
            redirectURL = spep.getDefaultUrl();
        }

        this.logger.info(
                "[Authn for {}] Processed response ID: {} .. Created local session with session ID: {}  Redirecting user to requested content: {}",
                new Object[] { remoteAddress, responseObject.getID(), sessionID, redirectURL });

        response.sendRedirect(redirectURL);
    } catch (IOException e) {
        throw new AuthenticationException(
                "Unable to send redirect back to authenticated content as an I/O error occurred", e);
    }
}

From source file:com.sslexplorer.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }//from   w w  w  . j  a va  2 s.  c o m
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("sslexplorer.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}