Example usage for javax.servlet.http Cookie setDomain

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

Introduction

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

Prototype

public void setDomain(String domain) 

Source Link

Document

Specifies the domain within which this cookie should be presented.

Usage

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request,
        HttpServletResponse response) {//from  www .ja va2  s. c o  m
    Cookie sessionCookie;
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), "LOGGED_OUT");
    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
    sharedSession.invalidate();

}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Remove a cookie.//from  w  w w .  jav  a2  s .  com
 * 
 * @param request The servlet request.
 * @param response The servlet response.
 * @param cookieName The name of the cookie that must be removed.
 */
private void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
    Cookie cookie = getCookie(request.getCookies(), cookieName);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setPath(this.cookiePath);
        addCookie(response, cookie);
        String cookieDomain = getCookieDomain(request);
        if (cookieDomain != null) {
            cookie.setDomain(cookieDomain);
            addCookie(response, cookie);
        }
    }
}

From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java

/**
 * @param response/*from w  ww  .  j  a v a2s .  c o  m*/
 * @param config
 * @param value
 * 
 * @throws Exception
 */
private void saveCookie(HttpServletResponse response, SessionAttributeConfig config, Object value)
        throws Exception {
    String cookieName = config.getNickName();
    int lifeTime = config.getLifeTime();

    //COOKIE
    String attrValue = getEncodedValue(config, value);
    Cookie cookie = null;

    if (attrValue != null) {
        // if (config.isEncrypt()) {
        attrValue = URLEncoder.encode(attrValue, "UTF-8");
        // }

        cookie = new Cookie(cookieName, attrValue);
    } else {
        cookie = new Cookie(cookieName, "");
    }

    log.debug("cookie name: " + cookieName + "  cookie value: " + attrValue);

    //COOKIE
    String cookiePath = COOKIE_PATH;

    if (config.getCookiePath() != null) {
        cookiePath = config.getCookiePath();
    }

    cookie.setPath(cookiePath);

    if (lifeTime > 0) {
        cookie.setMaxAge(lifeTime);
    }

    String domain = config.getDomain();

    if ((domain != null) && (domain.length() > 0)) {
        cookie.setDomain(domain);
    }

    response.addCookie(cookie);
}

From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java

/**
 * This method simulates the authentication process against a content 
 * source, so that every document is consider here as public.
 * <p>/*  w  ww  .j a v a  2s.  co m*/
 * Creates the authentication cookie and always return 200, unless there is 
 * any problem processing the request.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    // Debug
    logger.debug("HTTP No authentication start");

    //
    // Launch the authentication process
    //

    // Protection
    try {

        Cookie extAuthCookie = null;
        extAuthCookie = new Cookie("gsa_basic_noauth", "");

        extAuthCookie.setValue("true");

        String authCookieDomain = null;
        String authCookiePath = null;
        int authMaxAge = -1;

        // Cache cookie properties
        authCookieDomain = (request.getAttribute("authCookieDomain")).toString();
        authCookiePath = (request.getAttribute("authCookiePath")).toString();
        //authMaxAge
        try {
            authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
        } catch (NumberFormatException nfe) {
            logger.error(
                    "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
        }

        // Set extra cookie parameters
        extAuthCookie.setDomain(authCookieDomain);
        extAuthCookie.setPath(authCookiePath);
        extAuthCookie.setMaxAge(authMaxAge);

        // Log info
        if (logger.isDebugEnabled())
            logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":"
                    + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain()
                    + ":" + extAuthCookie.getSecure());

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP No Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:com.jfinal.core.Controller.java

/**
 * Set Cookie to response./*  w  w w  .  j  ava2s.com*/
 * @param name cookie name
 * @param value cookie value
 * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately.  n>0 : max age in n seconds.
 * @param path see Cookie.setPath(String)
 * @param domain the domain name within which this cookie is visible; form is according to RFC 2109
 */
public Controller setCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
    Cookie cookie = new Cookie(name, value);
    if (domain != null)
        cookie.setDomain(domain);
    cookie.setMaxAge(maxAgeInSeconds);
    cookie.setPath(path);
    response.addCookie(cookie);
    return this;
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);/*from   ww w  . j av a 2 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.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    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);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
 * {@inheritDoc}//  w  ww .j  a  v a2 s.c  o m
  *
  * @param request
  * @param response
  * @param name
  */
public void killCookie(HttpServletRequest request, HttpServletResponse response, String name) {
    String path = "//";
    String domain = "";
    Cookie cookie = getFirstCookie(request, name);
    if (cookie != null) {
        path = cookie.getPath();
        domain = cookie.getDomain();
    }
    Cookie deleter = new Cookie(name, "deleted");
    deleter.setMaxAge(0);
    if (domain != null)
        deleter.setDomain(domain);
    if (path != null)
        deleter.setPath(path);
    response.addCookie(deleter);
}

From source file:org.sakaiproject.portal.charon.handlers.PDAHandler.java

@Override
public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session)
        throws PortalHandlerException {
    if ((parts.length == 3) && parts[1].equals(PDAHandler.URL_FRAGMENT)
            && parts[2].equals(XLoginHandler.URL_FRAGMENT)) {
        try {// www . j a  v a  2 s.  c om
            portal.doLogin(req, res, session, "/pda", true);
            return END;
        } catch (Exception ex) {
            throw new PortalHandlerException(ex);
        }
    } else if ((parts.length >= 2) && (parts[1].equals("pda"))) {
        // Indicate that we are the controlling portal
        session.setAttribute(PortalService.SAKAI_CONTROLLING_PORTAL, PDAHandler.URL_FRAGMENT);
        try {

            //check if we want to force back to the classic view
            String forceClassic = req.getParameter(Portal.FORCE_CLASSIC_REQ_PARAM);
            if (StringUtils.equals(forceClassic, "yes")) {

                log.debug("PDAHandler - force.classic");

                //set the portal mode cookie to force classic
                Cookie c = new Cookie(Portal.PORTAL_MODE_COOKIE_NAME, Portal.FORCE_CLASSIC_COOKIE_VALUE);
                c.setPath("/");
                c.setMaxAge(-1);

                //need to set domain and https as per RequestFilter
                if (System.getProperty(SAKAI_COOKIE_DOMAIN) != null) {
                    c.setDomain(System.getProperty(SAKAI_COOKIE_DOMAIN));
                }
                if (req.isSecure() == true) {
                    c.setSecure(true);
                }
                res.addCookie(c);

                //redirect to classic view
                res.sendRedirect(req.getContextPath());
            }

            // /portal/pda/site-id
            String siteId = null;
            if (parts.length >= 3) {
                siteId = parts[2];
            }

            // SAK-12873
            // If we have no site at all and are not logged in - and there is 
            // only one gateway site, go directly to the gateway site
            if (siteId == null && session.getUserId() == null) {
                String siteList = ServerConfigurationService.getString("gatewaySiteList");
                String gatewaySiteId = ServerConfigurationService.getGatewaySiteId();
                if (siteList.trim().length() == 0 && gatewaySiteId.trim().length() != 0) {
                    siteId = gatewaySiteId;
                }
            }

            // Tool resetting URL - clear state and forward to the real tool
            // URL
            // /portal/pda/site-id/tool-reset/toolId
            // 0 1 2 3 4
            String toolId = null;
            if ((siteId != null) && (parts.length == 5) && (parts[3].equals("tool-reset"))) {
                toolId = parts[4];
                String toolUrl = req.getContextPath() + "/pda/" + siteId + "/tool"
                        + Web.makePath(parts, 4, parts.length);
                String queryString = Validator.generateQueryString(req);
                if (queryString != null) {
                    toolUrl = toolUrl + "?" + queryString;
                }
                portalService.setResetState("true");
                res.sendRedirect(toolUrl);
                return RESET_DONE;
            }

            // Tool after the reset
            // /portal/pda/site-id/tool/toolId
            if ((parts.length > 4) && (parts[3].equals("tool"))) {
                // look for page and pick up the top-left tool to show
                toolId = parts[4];
            }

            String forceLogout = req.getParameter(Portal.PARAM_FORCE_LOGOUT);
            if ("yes".equalsIgnoreCase(forceLogout) || "true".equalsIgnoreCase(forceLogout)) {
                portal.doLogout(req, res, session, "/pda");
                return END;
            }

            if (session.getUserId() == null) {
                String forceLogin = req.getParameter(Portal.PARAM_FORCE_LOGIN);
                if ("yes".equalsIgnoreCase(forceLogin) || "true".equalsIgnoreCase(forceLogin)) {
                    portal.doLogin(req, res, session, URLUtils.getSafePathInfo(req), false);
                    return END;
                }
            }

            SitePage page = null;
            // /portal/site/site-id/page/page-id
            // /portal/pda/site-id/page/page-id
            // 1 2 3 4
            if ((parts.length == 5) && (parts[3].equals("page"))) {
                // look for page and pick up the top-left tool to show
                String pageId = parts[4];
                page = SiteService.findPage(pageId);
                if (page == null) {
                    portal.doError(req, res, session, Portal.ERROR_WORKSITE);
                    return END;
                } else {
                    List<ToolConfiguration> tools = page.getTools(0);
                    if (tools != null && !tools.isEmpty()) {
                        toolId = tools.get(0).getId();
                    }
                    parts[3] = "tool";
                    parts[4] = toolId;
                }
            }

            // Set the site language
            Site site = null;
            if (siteId == null && session.getUserId() != null) {
                site = portal.getSiteHelper().getMyWorkspace(session);
            } else {
                try {
                    Set<SecurityAdvisor> advisors = (Set<SecurityAdvisor>) session
                            .getAttribute("sitevisit.security.advisor");
                    if (advisors != null) {
                        for (SecurityAdvisor advisor : advisors) {
                            SecurityService.pushAdvisor(advisor);
                        }
                    }

                    // This should understand aliases as well as IDs
                    site = portal.getSiteHelper().getSiteVisit(siteId);
                } catch (IdUnusedException e) {
                } catch (PermissionException e) {
                }
            }
            if (site != null) {
                super.setSiteLanguage(site);
            }

            // See if we can buffer the content, if not, pass the request through
            boolean allowBuffer = false;
            ToolConfiguration siteTool = SiteService.findTool(toolId);
            String commonToolId = null;

            String toolContextPath = null;
            String toolPathInfo = null;

            if (parts.length >= 5) {
                toolContextPath = req.getContextPath() + req.getServletPath() + Web.makePath(parts, 1, 5);
                toolPathInfo = Web.makePath(parts, 5, parts.length);
            }
            Object BC = null;
            if (siteTool != null && parts.length >= 5) {
                commonToolId = siteTool.getToolId();

                // Does the tool allow us to buffer?
                allowBuffer = allowBufferContent(req, site, siteTool);

                if (allowBuffer) {

                    // Should we bypass buffering based on the request?
                    boolean matched = checkBufferBypass(req, siteTool);

                    if (matched) {
                        ActiveTool tool = ActiveToolManager.getActiveTool(commonToolId);
                        portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), toolContextPath,
                                toolPathInfo);
                        return END;
                    }
                    // Inform includeTool called by portal.includePortal below
                    ThreadLocalManager.set("sakai:inline-tool", "true");
                }
            }

            // Prepare for the full output...
            PortalRenderContext rcontext = portal.includePortal(req, res, session, siteId, toolId,
                    req.getContextPath() + req.getServletPath(), "pda", /* doPages */false,
                    /* resetTools */true, /* includeSummary */false, /* expandSite */false);

            if (allowBuffer) {
                BC = bufferContent(req, res, session, toolId, toolContextPath, toolPathInfo, siteTool);

                // If the buffered response was not parseable
                if (BC instanceof ByteArrayServletResponse) {
                    ByteArrayServletResponse bufferResponse = (ByteArrayServletResponse) BC;
                    StringBuffer queryUrl = req.getRequestURL();
                    String queryString = req.getQueryString();
                    if (queryString != null)
                        queryUrl.append('?').append(queryString);
                    // SAK-25494 - This probably should be a log.debug later
                    String msg = "Post buffer bypass CTI=" + commonToolId + " URL=" + queryUrl;
                    String redir = bufferResponse.getRedirect();
                    if (redir != null)
                        msg = msg + " redirect to=" + redir;
                    log.warn(msg);
                    bufferResponse.forwardResponse();
                    return END;
                }
            }

            //  TODO: Should this be a property?  Probably because it does cause an 
            // uncached SQL query
            portal.includeSubSites(rcontext, req, session, siteId, req.getContextPath() + req.getServletPath(),
                    "pda", /* resetTools */ true);

            // Add the buttons
            if (siteTool != null) {
                boolean showResetButton = !"false"
                        .equals(siteTool.getConfig().getProperty(TOOLCONFIG_SHOW_RESET_BUTTON));
                rcontext.put("showResetButton", Boolean.valueOf(showResetButton));
                if (toolContextPath != null && showResetButton) {
                    rcontext.put("resetActionUrl", toolContextPath.replace("/tool/", "/tool-reset/"));
                }
            }

            // Include the buffered content if we have it
            if (BC instanceof Map) {
                rcontext.put("bufferedResponse", Boolean.TRUE);
                Map<String, String> bufferMap = (Map<String, String>) BC;
                rcontext.put("responseHead", (String) bufferMap.get("responseHead"));
                rcontext.put("responseBody", (String) bufferMap.get("responseBody"));
            }

            // Add any device specific information to the context
            portal.setupMobileDevice(req, rcontext);

            addLocale(rcontext, site);

            portal.sendResponse(rcontext, res, "pda", null);

            try {
                boolean presenceEvents = ServerConfigurationService.getBoolean("presence.events.log", true);
                if (presenceEvents)
                    org.sakaiproject.presence.cover.PresenceService.setPresence(siteId + "-presence");
            } catch (Exception e) {
                return END;
            }
            return END;
        } catch (Exception ex) {
            throw new PortalHandlerException(ex);
        }
    } else {
        return NEXT;
    }
}

From source file:org.ireland.jnetty.server.session.SessionManager.java

/**
 * ?JSESSIONID  Cookie/*from w  w  w  .j  ava2  s .com*/
 * @param session
 * @param contextPath
 * @param secure
 * @return
 */
public Cookie getSessionCookie(HttpSessionImpl session, String contextPath, boolean secure) {

    String sessionPath = contextPath;

    sessionPath = (sessionPath == null || sessionPath.length() == 0) ? "/" : sessionPath;

    String id = session.getId();

    Cookie cookie = null;

    cookie = new Cookie(_cookieName, id);

    cookie.setComment(_cookieComment);

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

    cookie.setHttpOnly(isHttpOnly());
    cookie.setMaxAge((int) _cookieMaxAge);

    cookie.setPath(sessionPath);

    cookie.setSecure(secure);
    cookie.setVersion(_cookieVersion);

    return cookie;

}

From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java

/**
 * {@inheritDoc}/*w  ww  .  j a  va  2s . c o m*/
 *
 * Save the user's remember me data in an encrypted cookie and send it to the user.
 * Any old remember me cookie is destroyed first. Setting this cookie will keep the user
 * logged in until the maxAge passes, the password is changed, or the cookie is deleted.
 * If the cookie exists for the current user, it will automatically be used by ESAPI to
 * log the user in, if the data is valid and not expired.
  *
  * @param request
  * @param response
  */
public String setRememberToken(HttpServletRequest request, HttpServletResponse response, String password,
        int maxAge, String domain, String path) {
    User user = ESAPI.authenticator().getCurrentUser();
    try {
        killCookie(request, response, REMEMBER_TOKEN_COOKIE_NAME);
        // seal already contains random data
        String clearToken = user.getAccountName() + "|" + password;
        long expiry = ESAPI.encryptor().getRelativeTimeStamp(maxAge * 1000);
        String cryptToken = ESAPI.encryptor().seal(clearToken, expiry);

        // Do NOT URLEncode cryptToken before creating cookie. See Google Issue # 144,
        // which was marked as "WontFix".

        Cookie cookie = new Cookie(REMEMBER_TOKEN_COOKIE_NAME, cryptToken);
        cookie.setMaxAge(maxAge);
        cookie.setDomain(domain);
        cookie.setPath(path);
        response.addCookie(cookie);
        logger.info(Logger.SECURITY_SUCCESS, "Enabled remember me token for " + user.getAccountName());
        return cryptToken;
    } catch (IntegrityException e) {
        logger.warning(Logger.SECURITY_FAILURE,
                "Attempt to set remember me token failed for " + user.getAccountName(), e);
        return null;
    }
}