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:au.gov.dto.springframework.security.web.csrf.CookieCsrfTokenRepository.java

@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    Cookie csrfCookie;
    if (token == null) {
        csrfCookie = new Cookie(csrfCookieName, "");
        csrfCookie.setMaxAge(0);/*from ww  w  . jav  a2 s  .  c  o  m*/
    } else {
        csrfCookie = new Cookie(csrfCookieName, token.getToken());
        csrfCookie.setMaxAge(csrfCookieMaxAgeSeconds);
    }
    csrfCookie.setHttpOnly(true);
    csrfCookie.setSecure(request.isSecure());
    csrfCookie.setPath(csrfCookiePath);
    response.addCookie(csrfCookie);
}

From source file:com.qut.middleware.esoe.sso.plugins.post.handler.impl.PostLogicImpl.java

private void sendPostResponseDocument(SSOProcessorData data) throws PostBindingException {
    String remoteAddress = data.getHttpRequest().getRemoteAddr();
    try {/*from  w  w  w  .  j a  v a  2 s  .  c o  m*/
        HttpServletResponse response = data.getHttpResponse();
        PrintWriter writer = response.getWriter();

        response.setContentType("text/html");

        /* Set cookie to allow javascript enabled browsers to auto submit, ensures navigation with the back button is not broken
         * because auto submit is active only when this cookie exists, and the submit javascript removes it */
        Cookie autoSubmit = new Cookie("esoeAutoSubmit", "enabled");
        autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT
        autoSubmit.setPath("/");
        response.addCookie(autoSubmit);

        this.logger.debug("[SSO for {}] Cookie added. About to check for response document.", remoteAddress); //$NON-NLS-1$

        if (data.getResponseDocument() == null) {
            this.logger.error(
                    "[SSO for {}] No response document was generated. Unable to respond to HTTP-POST binding request.", //$NON-NLS-1$
                    remoteAddress);
            throw new PostBindingException(
                    "No response document was generated. Unable to respond to HTTP-POST binding request.");
        }

        // TODO relaystate
        String responseRelayState = "";// = data.getRelayState();
        if (responseRelayState == null)
            responseRelayState = new String("");

        /* Encode SAML Response in base64 */
        byte[] samlResponseEncoded = Base64.encodeBase64(data.getResponseDocument()); //$NON-NLS-1$
        Object[] responseArgs = new Object[] { data.getResponseEndpoint(), new String(samlResponseEncoded),
                responseRelayState };
        String htmlOutput = this.samlMessageFormat.format(responseArgs);

        this.logger.debug(
                "[SSO for {}] Writing HTML document, response for HTTP-POST request. Length: {} bytes",
                remoteAddress, htmlOutput.length());

        this.logger.trace("[SSO for {}] Writing HTML document. Content:\n{}", remoteAddress, htmlOutput);

        writer.print(htmlOutput);
        writer.flush();
    } catch (IOException e) {
        this.logger.error(
                "[SSO for {}] I/O exception occurred trying to write the HTTP response. Unable to respond with HTTP-POST binding. Error was: {}",
                remoteAddress, e.getMessage());
        throw new PostBindingException(
                "I/O exception occurred trying to write the HTTP response. Unable to respond with HTTP-POST binding.",
                e);
    }
}

From source file:org.craftercms.cstudio.share.servlet.CookieManagerImpl.java

public void destroyCookie(HttpServletRequest request, HttpServletResponse response, String key, String path) {
    Cookie[] cookieArray = request.getCookies();
    if (cookieArray != null) {
        for (Cookie cookie : cookieArray) {
            String name = cookie.getName();
            if (name != null && name.equals(key)) {
                if (!StringUtils.isEmpty(path)) {
                    cookie.setPath(path);
                } else {
                    cookie.setPath("/");
                }/*  w  w  w  . j a v  a  2s. c  om*/
                cookie.setMaxAge(0);
                cookie.setValue(null);

                if (_cookieDomain != null) {
                    cookie.setDomain(_cookieDomain);
                }

                response.addCookie(cookie);
            }
        }
    }
}

From source file:com.toft.widgets.login.LoginAction.java

/**
 * cookie??/* ww w  . j  a  va  2 s.  c  om*/
 * 
 * @throws Exception
 */
private void addCookie() throws Exception {
    String isChange = (String) this.getContext().getParam("isChange");
    if (isChange == null) {
        return;
    }
    if (!isChange.equals("1")) {
        return;
    }
    String keepUser = (String) this.getContext().getParam("keepUser");
    String keepPassword = (String) this.getContext().getParam("keepPassword");

    if ("1".equals(keepUser)) {
        // cookie???
        String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser" };
        for (int i = 0; i < keys.length; i++) {
            String value = (String) getContext().getParam(keys[i]);
            Cookie cookie = new Cookie(keys[i], value);
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setPath("/");
            getResponse().addCookie(cookie);
        }
        if ("1".equals(keepPassword)) {
            String[] passkeys = new String[] { "keepPassword", "password" };
            for (int i = 0; i < passkeys.length; i++) {
                String value = (String) getContext().getParam(passkeys[i]);
                Cookie cookie = new Cookie(passkeys[i], value);
                cookie.setMaxAge(60 * 60 * 24 * 365);
                cookie.setPath("/");
                getResponse().addCookie(cookie);
            }
        } else {
            String[] passkeys = new String[] { "keepPassword", "password" };
            for (int i = 0; i < passkeys.length; i++) {
                Cookie cookie = new Cookie(passkeys[i], "");
                cookie.setMaxAge(0);
                cookie.setPath("/");
                getResponse().addCookie(cookie);
            }
        }
    } else {
        String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser", "keepPassword",
                "password" };
        for (int i = 0; i < keys.length; i++) {
            Cookie cookie = new Cookie(keys[i], "");
            cookie.setMaxAge(0);
            cookie.setPath("/");
            getResponse().addCookie(cookie);
        }
    }

}

From source file:cn.org.once.cstack.config.SecurityConfiguration.java

/**
 * Filter CRSF to add XSFR-TOKEN between exchange
 *
 * @return/*  w w w  .  ja v a 2s .  c om*/
 */
private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        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:com.persistent.cloudninja.controller.TenantTaskListController.java

@RequestMapping(value = "/logout.htm")
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response,
        @CookieValue(value = "CLOUDNINJAAUTH", required = false) String cookie) throws CloudNinjaException {

    if (cookie != null) {
        cookie = null;// ww w .  j a v a2s .c  o m
        Cookie c = new Cookie("CLOUDNINJAAUTH", null);
        c.setPath("/");
        response.addCookie(c);
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
    }
    if (request.getAttribute("cookieNameAttr") != null) {
        request.setAttribute("cookieNameAttr", null);
    }

    return new ModelAndView("logoutsuccess");
}

From source file:gr.abiss.calipso.wicket.HeaderPanel.java

public HeaderPanel() {
    super("header");

    final User user = getPrincipal();
    final List<Space> spaces = user != null ? new ArrayList<Space>(user.getSpaces()) : new ArrayList<Space>();

    boolean hideLogin = BooleanUtils.toBoolean(getCalipso().loadConfig("calipso.hideLoginLink"));
    boolean hideRegister = BooleanUtils.toBoolean(getCalipso().loadConfig("calipso.hideRegisterLink"));
    // manage single space
    if (spaces.size() == 1) {
        setCurrentSpace(spaces.get(0));//from   w w  w .j a  v  a 2s. c  o m
    }
    final Space space = getCurrentSpace();
    Component link = null;
    if (getPrincipal().isAnonymous()) {
        ExternalLink externalLink = new ExternalLink("dashboard", "/");
        externalLink.setContextRelative(true);
        link = externalLink;
    } else {
        link = new Link("dashboard") {
            public void onClick() {
                setCurrentSpace(null);
                setResponsePage(DashboardPage.class);
            }
        };
    }
    add(link);

    if (space == null) {

        // add(new Label("space", "").setVisible(false));// 1
        // add(new Label("new", "").setVisible(false));// 2
        add(new Link("search") {// 3
            public void onClick() {
                setResponsePage(ItemSearchFormPage.class);
            }
        }.setVisible(user != null && user.getSpaceCount() > 0 && !user.isAnonymous()));
    } else {
        /*
         * add(new Link("space") {
         * 
         * @Override public void onClick() {
         * setResponsePage(SpacePage.class); } }.add(new Label("space",
         * space.getName())));
         */
        // add(new WebMarkupContainer("space").add(new Label("space",
        // space.getName())));

        // In case that User opens an Item direct from e-mail notification
        // link
        // and has no access to this Item
        /*
         * try { if (user.getPermittedTransitions(space, State.NEW).size() >
         * 0) { add(new Link("new") { public void onClick() {
         * setResponsePage(ItemFormPage.class); } }); } else { add(new
         * WebMarkupContainer("new").setVisible(false)); } } catch
         * (Exception e) { logger.error("user.getPermittedTransitions :: " +
         * e.getMessage()); add(new
         * WebMarkupContainer("new").setVisible(false)); }
         */
        add(new Link("search") {
            public void onClick() {
                // if search then we user global search
                setCurrentSpace(null);
                setResponsePage(ItemSearchFormPage.class);
            }
        }.setVisible(user.getSpaceCount() > 0 && !user.isAnonymous()));
    }

    if (user == null || user.getId() == 0) {
        add(new WebMarkupContainer("options").setVisible(false));
        add(new WebMarkupContainer("logout").setVisible(false));
        add(new Link("login") {
            public void onClick() {
                setResponsePage(LoginPage.class);
            }
        }.setVisible(!hideLogin));
        add(new Link("register") {
            public void onClick() {
                setResponsePage(RegisterAnonymousUserFormPage.class);
            }
        }.setVisible(!hideRegister));
        add(new WebMarkupContainer("user").setVisible(false));
    } else {
        add(new Link("options") {
            public void onClick() {
                // when options clicked then we go to menu that space
                // doesn't have meaning
                setCurrentSpace(null);
                setResponsePage(OptionsPage.class);
            }
        });
        add(new Link("logout") {
            public void onClick() {
                Cookie cookie = new Cookie("calipsoService", "");
                String path = ((WebRequest) getRequest()).getContextPath();
                cookie.setPath(path);
                ((WebResponse) getResponse()).clearCookie(cookie);
                getSession().invalidate();
                logger.debug("invalidated session and cleared cookie");
                // is acegi - cas being used ?
                String logoutUrl = ((CalipsoApplication) getApplication()).getCasLogoutUrl();
                if (logoutUrl != null) {
                    logger.debug(
                            "cas authentication being used, clearing security context and redirecting to cas logout page");
                    SecurityContextHolder.clearContext();
                    // have to use stateless page reference because session
                    // is killed
                    setResponsePage(CasLogoutPage.class);
                } else {
                    setResponsePage(LogoutPage.class, new PageParameters("locale=" + user.getLocale()));
                }
            }
        });
        add(new WebMarkupContainer("login").setVisible(false));
        // issue
        add(new WebMarkupContainer("register").setVisible(false));

        add(new Link("user") {
            public void onClick() {
                setResponsePage(new UserViewPage(user));
            }
        }.add(new Label("user", user.getDisplayValue()).setRenderBodyOnly(true)));
    }
}

From source file:org.jahia.params.valves.LoginEngineAuthValveImpl.java

public void invoke(Object context, ValveContext valveContext) throws PipelineException {
    if (!isEnabled()) {
        valveContext.invokeNext(context);
        return;//from  www .  j  a  v a  2 s . c  o  m
    }

    final AuthValveContext authContext = (AuthValveContext) context;
    final HttpServletRequest httpServletRequest = authContext.getRequest();

    JahiaUser theUser = null;
    boolean ok = false;

    if (isLoginRequested(httpServletRequest)) {

        final String username = httpServletRequest.getParameter("username");
        final String password = httpServletRequest.getParameter("password");

        if ((username != null) && (password != null)) {
            final ServicesRegistry theRegistry = ServicesRegistry.getInstance();
            if (theRegistry != null) {
                JahiaUserManagerService theService = theRegistry.getJahiaUserManagerService();
                if (theService != null) {
                    // Check if the user has site access ( even though it is not a user of this site )
                    theUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUser(username);
                    if (theUser != null) {
                        if (theUser.verifyPassword(password)) {
                            if (!theUser.isAccountLocked()) {
                                ok = true;
                            } else {
                                logger.warn("Login failed: account for user " + theUser.getUsername()
                                        + " is locked.");
                                httpServletRequest.setAttribute(VALVE_RESULT, ACCOUNT_LOCKED);
                            }
                        } else {
                            logger.warn(
                                    "Login failed: user " + theUser.getUsername() + " provided bad password.");
                            httpServletRequest.setAttribute(VALVE_RESULT, BAD_PASSWORD);
                        }
                    } else {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Login failed. Unknown username " + username + ".");
                        }
                        httpServletRequest.setAttribute(VALVE_RESULT, UNKNOWN_USER);
                    }
                }
            }
        }
    }
    if (ok) {
        if (logger.isDebugEnabled()) {
            logger.debug("User " + theUser + " logged in.");
        }

        // if there are any attributes to conserve between session, let's copy them into a map first
        Map<String, Object> savedSessionAttributes = preserveSessionAttributes(httpServletRequest);

        if (httpServletRequest.getSession(false) != null) {
            httpServletRequest.getSession().invalidate();
        }

        // if there were saved session attributes, we restore them here.
        restoreSessionAttributes(httpServletRequest, savedSessionAttributes);

        httpServletRequest.setAttribute(VALVE_RESULT, OK);
        authContext.getSessionFactory().setCurrentUser(theUser);

        // do a switch to the user's preferred language
        if (SettingsBean.getInstance().isConsiderPreferredLanguageAfterLogin()) {
            Locale preferredUserLocale = UserPreferencesHelper.getPreferredLocale(theUser,
                    LanguageCodeConverters.resolveLocaleForGuest(httpServletRequest));
            JahiaSite site = (JahiaSite) authContext.getRequest().getSession()
                    .getAttribute(ProcessingContext.SESSION_SITE);
            if (site != null) {
                List<Locale> siteLocales = site.getLanguagesAsLocales();
                if (siteLocales.contains(preferredUserLocale)) {
                    httpServletRequest.getSession().setAttribute(ProcessingContext.SESSION_LOCALE,
                            preferredUserLocale);
                }
            }
        }

        String useCookie = httpServletRequest.getParameter(USE_COOKIE);
        if ((useCookie != null) && ("on".equals(useCookie))) {
            // the user has indicated he wants to use cookie authentication
            // now let's create a random identifier to store in the cookie.
            String cookieUserKey = null;
            // now let's look for a free random cookie value key.
            while (cookieUserKey == null) {
                cookieUserKey = CookieAuthValveImpl.generateRandomString(cookieAuthConfig.getIdLength());
                Properties searchCriterias = new Properties();
                searchCriterias.setProperty(cookieAuthConfig.getUserPropertyName(), cookieUserKey);
                Set<Principal> foundUsers = ServicesRegistry.getInstance().getJahiaUserManagerService()
                        .searchUsers(searchCriterias);
                if (foundUsers.size() > 0) {
                    cookieUserKey = null;
                }
            }
            // let's save the identifier for the user in the database
            theUser.setProperty(cookieAuthConfig.getUserPropertyName(), cookieUserKey);
            // now let's save the same identifier in the cookie.
            Cookie authCookie = new Cookie(cookieAuthConfig.getCookieName(), cookieUserKey);
            authCookie.setPath(StringUtils.isNotEmpty(httpServletRequest.getContextPath())
                    ? httpServletRequest.getContextPath()
                    : "/");
            authCookie.setMaxAge(cookieAuthConfig.getMaxAgeInSeconds());
            authContext.getResponse().addCookie(authCookie);
        }

        enforcePasswordPolicy(theUser);
        // The following was deactivated for performance reasons. We should instead look at doing this with Camel
        // or some other asynchronous way.
        //theUser.setProperty(Constants.JCR_LASTLOGINDATE,
        //        String.valueOf(System.currentTimeMillis()));

        if (fireLoginEvent) {
            SpringContextSingleton.getInstance().getModuleContext()
                    .publishEvent(new LoginEvent(this, theUser, authContext));
        }

    } else {
        valveContext.invokeNext(context);
    }
}

From source file:org.infoglue.deliver.applications.actions.ExtranetLoginAction.java

private void handleCookies() throws Exception {
    DesEncryptionHelper encHelper = new DesEncryptionHelper();
    String userName = this.getRequest().getParameter("j_username");
    String encryptedName = encHelper.encrypt(userName);
    String password = this.getRequest().getParameter("j_password");
    String encryptedPassword = encHelper.encrypt(password);

    String encryptedNameAsBase64 = Base64.encodeBase64URLSafeString(encryptedName.getBytes("utf-8"));
    String encryptedPasswordAsBase64 = Base64.encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8"));

    //logger.info("encryptedName:" + encryptedName);
    //logger.info("encryptedPassword:" + encryptedPassword);

    try {//  w w w  .j  a  va 2  s  . c om
        String cmsBaseUrl = CmsPropertyHandler.getCmsFullBaseUrl();
        //logger.info("cmsBaseUrl:" + cmsBaseUrl);
        String[] parts = cmsBaseUrl.split("/");

        cmsBaseUrl = "/" + parts[parts.length - 1];
        //logger.info("used cmsBaseUrl:" + cmsBaseUrl);

        ServletContext servletContext = ActionContext.getServletContext().getContext(cmsBaseUrl);
        //logger.info("servletContext:" + servletContext.getServletContextName() + ":" + servletContext.getServletNames());

        if (servletContext == null) {
            logger.error("Could not autologin to CMS. Set cross context = true in Tomcat config.");
        } else {
            servletContext.setAttribute(encryptedName, userName);
        }

        //logger.info(encryptedName + "=" + userName);
        //logger.info("After attribute:" + servletContext.getAttribute(encryptedName));
    } catch (Exception e) {
        logger.error("Error: " + e.getMessage(), e);
    }

    int cmsCookieTimeout = 1800; //30 minutes default
    String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout();
    if (cmsCookieTimeoutString != null) {
        try {
            cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim());
        } catch (Exception e) {
        }
    }

    try {
        //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ"));
        Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64);
        cookie_iguserid.setPath("/");
        cookie_iguserid.setMaxAge(cmsCookieTimeout);
        this.getResponse().addCookie(cookie_iguserid);

        //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ"));
        Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64);
        cookie_igpassword.setPath("/");
        cookie_igpassword.setMaxAge(cmsCookieTimeout);
        this.getResponse().addCookie(cookie_igpassword);
    } catch (Exception e) {
        logger.error("Could not set cookies:" + e.getMessage(), e);
    }
    //END CMS COOKIE

    if (storeUserInfoCookie == null || !storeUserInfoCookie.equalsIgnoreCase("true"))
        return;

    boolean enableExtranetCookies = getEnableExtranetCookies();
    int extranetCookieTimeout = 43200; //30 days default
    String extranetCookieTimeoutString = CmsPropertyHandler.getExtranetCookieTimeout();
    if (extranetCookieTimeoutString != null) {
        try {
            extranetCookieTimeout = Integer.parseInt(extranetCookieTimeoutString.trim());
        } catch (Exception e) {
        }
    }

    if (enableExtranetCookies) {
        //Cookie cookie_userid = new Cookie("igextranetuserid", encryptedName);
        Cookie cookie_userid = new Cookie("igextranetuserid", encryptedNameAsBase64);
        cookie_userid.setMaxAge(30 * 24 * 60 * 60); //30 days
        this.getResponse().addCookie(cookie_userid);

        //Cookie cookie_password = new Cookie ("igextranetpassword", encryptedPassword);
        Cookie cookie_password = new Cookie("igextranetpassword", encryptedPasswordAsBase64);
        cookie_password.setMaxAge(30 * 24 * 60 * 60); //30 days
        this.getResponse().addCookie(cookie_password);
    }
}