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:org.craftercms.social.util.support.security.CrafterProfileFilter.java

/**
 * Build cipher auth cookie// w w  w .  j  a  v  a2  s.c  om
 *
 * @param cipher
 * @param profileToken
 * @param userProfile
 * @return
 * @throws org.craftercms.social.exceptions.AuthenticationException
 */
private Cookie getCipherCookie(SimpleDesCipher cipher, String profileToken, Profile userProfile)
        throws org.craftercms.social.exceptions.AuthenticationException {
    Cookie cipherAuth = new Cookie(cipherTokenCookieKey,
            generateEncryptedToken(cipher, profileToken, userProfile));
    cipherAuth.setMaxAge(60 * 60 * 8);
    cipherAuth.setPath(CRAFTER_SOCIAL_COOKIE_PATH);
    return cipherAuth;
}

From source file:com.stormcloud.ide.api.filter.UserFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

    try {/*from www .  j av  a 2 s .  co  m*/

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

        LOG.info("Filter Request [" + request.getRemoteAddr() + "]");

        MDC.put("api", httpRequest.getRequestURI());

        if (httpRequest.getRequestURI().endsWith("/api/login")) {

            // configure MDC for the remainging trip
            MDC.put("userName", httpRequest.getRemoteUser());

            LOG.debug("Login Request.");

            // it's a login request which succeeded (Basic Auth)
            // so we now need to genereate an authentication token
            // and store it in a cookie we sent back
            // create the cookie with key for consecutive Rest API Calls

            // Get user from db and add to the localthread
            User user = dao.getUser(httpRequest.getRemoteUser());

            if (user == null) {

                LOG.error("User not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;
            }

            // update last login
            user.setLastLogin(Calendar.getInstance().getTime());

            dao.save(user);

            RemoteUser.set(user);

            try {

                // set the key cookie
                Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr()));

                keyCookie.setMaxAge(60 * 60 * 24); // 1 day

                keyCookie.setPath("/");
                keyCookie.setSecure(true);

                httpResponse.addCookie(keyCookie);

                // set the username cookie
                Cookie userCookie = new Cookie("stormcloud-user", user.getUserName());

                userCookie.setMaxAge(60 * 60 * 24); // 1 day

                userCookie.setPath("/");
                userCookie.setSecure(true);

                httpResponse.addCookie(userCookie);

            } catch (NoSuchAlgorithmException e) {

                LOG.error(e);

                try {

                    // no go
                    httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());

                    httpResponse.flushBuffer();
                    return;

                } catch (IOException ioe) {
                    LOG.error(ioe);
                }
            }

        } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) {

            // intercept and do something with create account
            LOG.debug("Create Account Request.");

        } else {

            LOG.info("API Request.");

            // any other request than a login
            // we need to check the username and received key
            Cookie[] cookies = httpRequest.getCookies();

            String userName = null;
            String key = null;

            if (cookies != null) {

                LOG.info("Found " + cookies.length + " Cookies");

                // loop trough the cookies
                for (int i = 0; i < cookies.length; i++) {

                    if (cookies[i].getName().equals("stormcloud-user")) {

                        LOG.debug("userName = " + cookies[i].getValue());
                        userName = cookies[i].getValue();
                    }

                    if (cookies[i].getName().equals("stormcloud-key")) {

                        LOG.debug("key = " + cookies[i].getValue());
                        key = cookies[i].getValue();
                    }
                }
            }

            if (userName == null || key == null) {

                LOG.info("Required credentials not found.");
                httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                httpResponse.flushBuffer();
                return;

            } else {

                // configure MDC for the remainging trip
                MDC.put("userName", userName);

                // get user
                LOG.debug("Get Persisted User");
                User user = dao.getUser(userName);

                if (user == null) {
                    httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                    httpResponse.flushBuffer();
                    return;
                }

                RemoteUser.set(user);

                try {

                    String matchKey = createKey(user, httpRequest.getRemoteAddr());

                    LOG.info("Validating Key.");

                    if (!matchKey.equals(key)) {

                        LOG.warn("Invalid Key!");
                        httpResponse.sendError(HttpStatus.FORBIDDEN.value());
                        httpResponse.flushBuffer();
                        return;

                    } else {

                        LOG.info("Request Authenticated");
                    }

                } catch (NoSuchAlgorithmException e) {

                    LOG.error(e);

                    try {

                        // no go
                        httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                        httpResponse.flushBuffer();
                        return;

                    } catch (IOException ioe) {
                        LOG.error(ioe);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    } catch (IOException e) {
        LOG.error(e);
    } catch (ServletException e) {
        LOG.error(e);
    } finally {

        // clear the logging diagnostics context
        MDC.clear();

        // Remove the user from memoty
        RemoteUser.destroy();
    }
}

From source file:fr.paris.lutece.plugins.mylutece.modules.openam.service.OpenamService.java

/**
 * set a paris connect cokkie in the HttpServletResponse
 *
 * @param strPCUID//w ww  .ja  v  a  2 s  .c om
 *            the user PCUID
 * @param response
 *            The HTTP response
 */
public void removeConnectionCookie(HttpServletResponse response) {
    // remove  openam cookie using the setMaxAgeParameters
    Cookie openamCookie = new Cookie(COOKIE_OPENAM_NAME, null);
    openamCookie.setDomain(COOKIE_OPENAM_DOMAIN);
    openamCookie.setSecure(COOKIE_OPENAM_SECURE);
    openamCookie.setMaxAge(0);
    openamCookie.setPath(COOKIE_OPENAM_PATH);
    response.addCookie(openamCookie);
}

From source file:org.collectionspace.chain.controller.WebUIRequest.java

private void setSession() {
    //if(session.isOld())
    //   return; // No need to reset session

    Cookie cookie = new Cookie(COOKIENAME, session.getID());
    cookie.setPath("/");//XXX should be /chain - so either need to have a parameter in cspace-config or try and ask tomcat who we are
    cookie.setMaxAge(60 * lifeInMins);//from ww  w .  jav a  2s .com
    response.addCookie(cookie);
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

/**
 * Copy cookie from the proxy to the servlet client.
 * Replaces cookie path to local path and renames cookie to avoid collisions.
 *//*from   w  ww.j  av a 2  s  .c  o m*/
private 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 (int i = 0, l = cookies.size(); i < l; i++) {
        HttpCookie cookie = cookies.get(i);
        //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.josso.gateway.signon.SignonBaseAction.java

protected Cookie newJossoCookie(String path, String name, String value) throws Exception {
    SSOWebConfiguration cfg = Lookup.getInstance().lookupSSOWebConfiguration();

    Cookie ssoCookie = new Cookie(name, value);
    ssoCookie.setMaxAge(-1);//from  ww  w  .  j a  va2 s .  c  o m

    if (cfg.isSessionTokenSecure()) {
        ssoCookie.setSecure(true);
    }

    ssoCookie.setPath(path);

    return ssoCookie;

    //        if (cfg.getSessionTokenScope() != null) {
    //            ssoCookie.setDomain(cfg.getSessionTokenScope());
    //        }

}

From source file:net.sourceforge.subsonic.service.PlayerService.java

/**
 * Returns the player associated with the given HTTP request.  If no such player exists, a new
 * one is created.// w  w  w  .j a v  a2  s .  com
 *
 * @param request              The HTTP request.
 * @param response             The HTTP response.
 * @param remoteControlEnabled Whether this method should return a remote-controlled player.
 * @param isStreamRequest      Whether the HTTP request is a request for streaming data.
 * @return The player associated with the given HTTP request.
 */
public synchronized Player getPlayer(HttpServletRequest request, HttpServletResponse response,
        boolean remoteControlEnabled, boolean isStreamRequest) {

    // Find by 'player' request parameter.
    Player player = getPlayerById(request.getParameter("player"));

    // Find in session context.
    if (player == null && remoteControlEnabled) {
        String playerId = (String) request.getSession().getAttribute("player");
        if (playerId != null) {
            player = getPlayerById(playerId);
        }
    }

    // Find by cookie.
    String username = securityService.getCurrentUsername(request);
    if (player == null && remoteControlEnabled) {
        player = getPlayerById(getPlayerIdFromCookie(request, username));
    }

    // Make sure we're not hijacking the player of another user.
    if (player != null && player.getUsername() != null && username != null
            && !player.getUsername().equals(username)) {
        player = null;
    }

    // Look for player with same IP address and user name.
    if (player == null) {
        player = getPlayerByIpAddressAndUsername(request.getRemoteAddr(), username);

        // Don't use this player if it's used by REST API.
        if (player != null && player.getClientId() != null) {
            player = null;
        }
    }

    // If no player was found, create it.
    if (player == null) {
        player = new Player();
        createPlayer(player);
        //            LOG.debug("Created player " + player.getId() + " (remoteControlEnabled: " + remoteControlEnabled +
        //                      ", isStreamRequest: " + isStreamRequest + ", username: " + username +
        //                      ", ip: " + request.getRemoteAddr() + ").");
    }

    // Update player data.
    boolean isUpdate = false;
    if (username != null && player.getUsername() == null) {
        player.setUsername(username);
        isUpdate = true;
    }
    if (player.getIpAddress() == null || isStreamRequest || (!isPlayerConnected(player) && player.isDynamicIp()
            && !request.getRemoteAddr().equals(player.getIpAddress()))) {
        player.setIpAddress(request.getRemoteAddr());
        isUpdate = true;
    }
    String userAgent = request.getHeader("user-agent");
    if (isStreamRequest) {
        player.setType(userAgent);
        player.setLastSeen(new Date());
        isUpdate = true;
    }

    if (isUpdate) {
        updatePlayer(player);
    }

    // Set cookie in response.
    if (response != null) {
        String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username);
        Cookie cookie = new Cookie(cookieName, player.getId());
        cookie.setMaxAge(COOKIE_EXPIRY);
        String path = request.getContextPath();
        if (StringUtils.isEmpty(path)) {
            path = "/";
        }
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    // Save player in session context.
    if (remoteControlEnabled) {
        request.getSession().setAttribute("player", player.getId());
    }

    return player;
}

From source file:org.kuali.mobility.shared.interceptors.NativeCookieInterceptor.java

/**
 * Attempts to detect the platform and sets the platform cookie
 *
 * @param request//from ww w.  java 2  s .  c om
 * @param response
 * @return
 */
private String checkPlatform(HttpServletRequest request, HttpServletResponse response) {
    String platformParam = request.getParameter(COOKIE_PLATFORM);
    String platformCookie = findCookie(request.getCookies(), COOKIE_PLATFORM);
    String platformName;

    // If there is a platform param, rather use that
    if (!StringUtils.isEmpty(platformParam)) {
        platformName = platformParam;
    }
    // if there is a platform cookie, refresh it
    else if (!StringUtils.isEmpty(platformCookie)) {
        platformName = platformCookie;
    }
    // If there still is no platform, try and detect it
    else {
        platformName = findPlatform(request);
    }

    boolean useSecureCookies = Boolean
            .parseBoolean(getKmeProperties().getProperty("kme.secure.cookie", "false"));
    Cookie cookie = new Cookie(COOKIE_PLATFORM, platformName);
    int cookieMaxAge = Integer.parseInt(getKmeProperties().getProperty("cookie.max.age", "3600"));
    cookie.setMaxAge(cookieMaxAge); // default one hour, should implement in kme.config properties.
    cookie.setPath(request.getContextPath());
    cookie.setSecure(useSecureCookies);
    response.addCookie(cookie);
    LOG.debug("Setting platform cookie : " + platformName);

    request.getSession().setAttribute(SESSION_PLATFORM, platformName);
    return platformName;
}

From source file:org.guanxi.idp.service.AuthHandler.java

/**
 * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after
 * a successful authentication at the IdP, either via the login page or an application cookie handler,
 * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value.
 * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet
 * context under GuanxiPrincipal.id//from  w ww . ja  va 2s.co  m
 *
 * @param request Standard HttpServletRequest
 * @param response Standard HttpServletResponse
 * @param object handler
 * @return true 
 * @throws Exception if an error occurs
 */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
        throws Exception {
    request.setCharacterEncoding("UTF-8");

    String missingParams = checkRequestParameters(request);
    if (missingParams != null) {
        logger.info("Missing param(s) : " + missingParams);
        request.setAttribute("message",
                messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG);

    boolean spSupported = false;
    EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM);
    EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam));
    if (manager != null) {
        SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam));
        // Apply the trust rules to the SP
        if (metadata != null) {
            if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) {
                spSupported = true;
            } else {
                logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> "
                        + request.getParameter("shire"));
            }
        } else {
            logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam));
        }
    } else {
        logger.error("No Metadata Manager");
    }

    // Check the locally registered SPs
    if (!spSupported) {
        ServiceProvider[] spList = idpConfig.getServiceProviderArray();
        for (int c = 0; c < spList.length; c++) {
            if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) {
                // If it's in here, we trust it explicitly
                spSupported = true;
            }
        }
    }

    // Did we find the service provider?
    if (!spSupported) {
        logger.error(
                "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported");
        request.setAttribute("message", messageSource.getMessage("sp.not.supported",
                new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale()));
        request.getRequestDispatcher(errorPage).forward(request, response);
        return false;
    }

    // Look for our cookie. This is after any application cookie handler has authenticated the user
    String cookieName = getCookieName();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int c = 0; c < cookies.length; c++) {
            if (cookies[c].getName().equals(cookieName)) {
                // Retrieve the principal from the servlet context
                if (servletContext.getAttribute(cookies[c].getValue()) == null) {
                    // Out of date cookie value, so remove the cookie
                    cookies[c].setMaxAge(0);
                    response.addCookie(cookies[c]);
                } else {
                    // Found the principal from a previously established authentication
                    request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL,
                            (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue()));
                    return true;
                }
            }
        }
    }

    // Are we getting an authentication request from the login page?
    if (request.getParameter("guanxi:mode") != null) {
        if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) {
            // Get a new GuanxiPrincipal...
            GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request);
            if (authenticator.authenticate(principal, request.getParameter("userid"),
                    request.getParameter("password"))) {
                // ...associate it with a login name...
                if (principal.getName() == null) {
                    //The login name from the authenticator page
                    principal.setName(request.getParameter("userid"));
                }
                // ...store it in the request for the SSO to use...
                request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal);
                // ...and store it in application scope for the rest of the profile to use
                servletContext.setAttribute(principal.getUniqueId(), principal);

                // Get a new cookie ready to reference the principal in the servlet context
                Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId());
                cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN));
                cookie.setPath(idpConfig.getCookie().getPath());
                if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                        .intValue() != -1)
                    cookie.setMaxAge(
                            ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE)))
                                    .intValue());
                response.addCookie(cookie);

                return true;
            } // if (authenticator.authenticate...
            else {
                logger.error("Authentication error : " + authenticator.getErrorMessage());
                request.setAttribute("message",
                        messageSource.getMessage("authentication.error", null, request.getLocale()));
                request.getRequestDispatcher(errorPage).forward(request, response);
                return false;
            }
        }
    }

    // No embedded cookie authentication or local auth, so show the login page
    String authPage = null;
    AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray();
    for (int c = 0; c < authPages.length; c++) {
        // We'll use the default auth page if none is specified for this service provider
        if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) {
            authPage = authPages[c].getUrl();
        }

        // Customised auth page for this service provider
        if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) {
            authPage = authPages[c].getUrl();
        }
    }

    addRequiredParamsAsPrefixedAttributes(request);
    request.getRequestDispatcher(authPage).forward(request, response);

    return false;
}

From source file:org.kuali.mobility.shared.interceptors.NativeCookieInterceptor.java

/**
 * Attempts to detect the phonegap version and sets a cookie with the value
 *
 * @param request//from   w ww . j  av a 2 s.  c  o  m
 * @param response
 * @return
 */
private String checkPhonegap(HttpServletRequest request, HttpServletResponse response) {
    String phonegapParam = request.getParameter(COOKIE_PHONEGAP);
    String phoneGapCookie = findCookie(request.getCookies(), COOKIE_PHONEGAP);
    String phonegapVersion = null;

    // If there is a phonegap param present, rather use that
    if (!StringUtils.isEmpty(phonegapParam)) {
        phonegapVersion = phonegapParam;
    }
    // Else use the existing cookie if present
    else if (!StringUtils.isEmpty(phoneGapCookie)) {
        phonegapVersion = phoneGapCookie;
    }

    boolean useSecureCookies = Boolean
            .parseBoolean(getKmeProperties().getProperty("kme.secure.cookie", "false"));
    Cookie cookie = new Cookie(COOKIE_PHONEGAP, phonegapVersion);

    int cookieMaxAge = Integer.parseInt(getKmeProperties().getProperty("cookie.max.age", "3600"));
    cookie.setMaxAge(cookieMaxAge); // default one hour, should implement in kme.config properties.
    cookie.setPath(request.getContextPath());
    cookie.setSecure(useSecureCookies);
    response.addCookie(cookie);

    LOG.debug("Setting cordova version : " + phonegapVersion);
    request.getSession().setAttribute(SESSION_PHONEGAP, phonegapVersion);

    return phonegapVersion;
}