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:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Sets a "cancel cookie" (with maxAge = 0) on the response to disable persistent
 * logins./*from  w w  w  .  j a v  a 2s  .  c o  m*/
 */
protected void cancelCookie(HttpServletRequest request, HttpServletResponse response) {
    logger.debug("Cancelling cookie");
    Cookie cookie = new Cookie(cookieName, null);
    cookie.setMaxAge(0);
    cookie.setPath(getCookiePath(request));
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    response.addCookie(cookie);
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//from  www. j ava2 s. com
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

From source file:org.gss_project.gss.server.Login.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Fetch the next URL to display, if any.
    String nextUrl = request.getParameter(NEXT_URL_PARAM);
    // Fetch the supplied nonce, if any.
    String nonce = request.getParameter(NONCE_PARAM);
    String[] attrs = new String[] { "REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
            "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME", "HTTP_SHIB_PERSON_SURNAME",
            "HTTP_SHIB_INETORGPERSON_MAIL", "HTTP_SHIB_EP_UNSCOPEDAFFILIATION", "HTTP_PERSISTENT_ID",
            "HTTP_SHIB_HOMEORGANIZATION" };
    StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
    for (String attr : attrs)
        buf.append(attr + ": ").append(request.getAttribute(attr)).append('\n');
    logger.info(buf);//from   w w  w.j  a va  2 s .c  o  m
    if (logger.isDebugEnabled()) {
        buf = new StringBuilder("Shibboleth Attributes as bytes\n");
        for (String attr : attrs)
            if (request.getAttribute(attr) != null)
                buf.append(attr + ": ")
                        .append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8")))
                        .append('\n');
        logger.debug(buf);
    }
    User user = null;
    response.setContentType("text/html");
    Object usernameAttr = request.getAttribute("REMOTE_USER");
    Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
    Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
    Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
    Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
    Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
    Object persistentIdAttr = request.getAttribute("HTTP_PERSISTENT_ID");
    Object homeOrganizationAttr = request.getAttribute("HTTP_SHIB_HOMEORGANIZATION");
    // Use a configured test username if found, as a shortcut for development deployments.
    String gwtServer = null;
    if (getConfiguration().getString("testUsername") != null) {
        usernameAttr = getConfiguration().getString("testUsername");
        // Fetch the GWT code server URL, if any.
        gwtServer = request.getParameter(GWT_SERVER_PARAM);
    }
    if (usernameAttr == null) {
        String authErrorUrl = "authenticationError.jsp";
        authErrorUrl += "?name=" + (nameAttr == null ? "-" : nameAttr.toString());
        authErrorUrl += "&givenname=" + (givennameAttr == null ? "-" : givennameAttr.toString());
        authErrorUrl += "&sn=" + (snAttr == null ? "-" : snAttr.toString());
        authErrorUrl += "&cn=" + (cnAttr == null ? "-" : cnAttr.toString());
        authErrorUrl += "&mail=" + (mailAttr == null ? "-" : mailAttr.toString());
        authErrorUrl += "&homeOrg=" + (homeOrganizationAttr == null ? "-" : homeOrganizationAttr.toString());
        response.sendRedirect(authErrorUrl);
        return;
    }
    String username = decodeAttribute(usernameAttr);
    String name;
    if (nameAttr != null && !nameAttr.toString().isEmpty())
        name = decodeAttribute(nameAttr);
    else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
        name = decodeAttribute(cnAttr);
        if (name.indexOf(';') != -1)
            name = name.substring(0, name.indexOf(';'));
    } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty()
            && !snAttr.toString().isEmpty()) {
        String givenname = decodeAttribute(givennameAttr);
        if (givenname.indexOf(';') != -1)
            givenname = givenname.substring(0, givenname.indexOf(';'));
        String sn = decodeAttribute(snAttr);
        if (sn.indexOf(';') != -1)
            sn = sn.substring(0, sn.indexOf(';'));
        name = givenname + ' ' + sn;
    } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
        name = decodeAttribute(snAttr);
        if (name.indexOf(';') != -1)
            name = name.substring(0, name.indexOf(';'));
    } else
        name = username;
    String mail = mailAttr != null ? mailAttr.toString() : username;
    if (mail.indexOf(';') != -1)
        mail = mail.substring(0, mail.indexOf(';'));
    String persistentId = persistentIdAttr != null ? persistentIdAttr.toString() : "";
    String idp = "";
    String idpid = "";
    if (!persistentId.isEmpty()) {
        int bang = persistentId.indexOf('!');
        if (bang > -1) {
            idp = persistentId.substring(0, bang);
            idpid = persistentId.substring(bang + 1);
        }
    }
    String homeOrganization = homeOrganizationAttr != null ? decodeAttribute(homeOrganizationAttr.toString())
            : "";
    try {
        user = getService().findUser(username);
        if (user == null)
            user = getService().createUser(username, name, mail, idp, idpid, homeOrganization);
        if (!user.isActive()) {
            logger.info("Disabled user " + username + " tried to login.");
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "This account is disabled");
            return;
        }
        if (!user.hasAcceptedPolicy()) {
            String policyUrl = "policy.jsp";
            if (request.getQueryString() != null)
                policyUrl += "?user=" + username + "&" + request.getQueryString();
            response.sendRedirect(policyUrl);
            return;
        }
        user.setName(name);
        user.setEmail(mail);
        user.setIdentityProvider(idp);
        user.setIdentityProviderId(idpid);
        user.setHomeOrganization(homeOrganization);

        UserLogin userLogin = new UserLogin();
        userLogin.setLoginDate(new Date());
        userLogin.setUser(user);
        if (user.getAuthToken() == null)
            user = getService().updateUserToken(user.getId());
        // Set WebDAV password to token if it's never been set.
        if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
            String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
            user.setWebDAVPassword(tokenEncoded);
        }
        // Set the default user class if none was set.
        if (user.getUserClass() == null)
            user.setUserClass(getService().getUserClasses().get(0));
        getService().updateUser(user);
        getService().addUserLogin(userLogin);
    } catch (RpcException e) {
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    } catch (DuplicateNameException e) {
        String error = "User with username " + username + " already exists";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    } catch (ObjectNotFoundException e) {
        String error = "No username was provided";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
        return;
    }
    String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
    String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
    if (logger.isDebugEnabled())
        logger.debug("user: " + userEncoded + " token: " + tokenEncoded);
    if (nextUrl != null && !nextUrl.isEmpty()) {
        URI next;
        if (gwtServer != null)
            nextUrl += '?' + GWT_SERVER_PARAM + '=' + gwtServer;

        if (nextUrl.indexOf(FileHeader.PATH_FILES) != -1) {
            int pathIndex = nextUrl.indexOf(FileHeader.PATH_FILES) + FileHeader.PATH_FILES.length() + 1;
            String path = nextUrl.substring(pathIndex);
            path = URLEncoder.encode(path, "UTF-8");
            nextUrl = nextUrl.substring(0, pathIndex) + path;
        }
        try {
            next = new URI(nextUrl);
        } catch (URISyntaxException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }
        if ("x-gr-ebs-igss".equalsIgnoreCase(next.getScheme()))
            nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
        else {
            String domain = next.getHost();
            String path = getServletContext().getContextPath() + '/';
            Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR + tokenEncoded);
            cookie.setMaxAge(-1);
            cookie.setDomain(domain);
            cookie.setPath(path);
            response.addCookie(cookie);
            cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
            cookie.setMaxAge(-1);
            cookie.setDomain(domain);
            cookie.setPath(path);
            response.addCookie(cookie);
        }
        response.sendRedirect(nextUrl);
    } else if (nonce != null) {
        nonce = URLEncoder.encode(nonce, "US-ASCII");
        Nonce n = null;
        try {
            if (logger.isDebugEnabled())
                logger.debug("user: " + user.getId() + " nonce: " + nonce);
            n = getService().getNonce(nonce, user.getId());
        } catch (ObjectNotFoundException e) {
            PrintWriter out = response.getWriter();
            out.println("<HTML>");
            out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                    + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
            out.println("<BODY><CENTER><P>");
            out.println("The supplied nonce could not be found!");
            out.println("</CENTER></BODY></HTML>");
            return;
        } catch (RpcException e) {
            String error = "An error occurred while communicating with the service";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        }
        try {
            getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
        } catch (ObjectNotFoundException e) {
            String error = "Unable to find user";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        } catch (RpcException e) {
            String error = "An error occurred while communicating with the service";
            logger.error(error, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
            return;
        }
        try {
            getService().removeNonce(n.getId());
        } catch (ObjectNotFoundException e) {
            logger.info("Nonce already removed!", e);
        } catch (RpcException e) {
            logger.warn("Could not remove nonce from data store", e);
        }
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
        out.println("<BODY><CENTER><P>");
        out.println("You can now close this browser window and return to your application.");
        out.println("</CENTER></BODY></HTML>");
    } else {
        PrintWriter out = response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>"
                + "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
        out.println("<BODY><CENTER><P>");
        out.println("Name: " + user.getName() + "<BR>");
        out.println("E-mail: " + user.getEmail() + "<BR><P>");
        out.println("Username: " + user.getUsername() + "<BR>");
        out.println("Athentication token: " + tokenEncoded + "<BR>");
        out.println("</CENTER></BODY></HTML>");
    }
}

From source file:wicket.markup.html.form.persistence.CookieValuePersister.java

/**
 * Persist/save the data using Cookies.//from   w w w.  java2s .c om
 * 
 * @param cookie
 *            The Cookie to be persisted.
 * @return The cookie provided
 */
private Cookie save(final Cookie cookie) {
    if (cookie == null) {
        return null;
    }

    final String comment = getSettings().getComment();
    if (comment != null) {
        cookie.setComment(comment);
    }

    final String domain = getSettings().getDomain();
    if (domain != null) {
        cookie.setDomain(domain);
    }

    cookie.setPath(getWebRequest().getContextPath());

    cookie.setVersion(getSettings().getVersion());
    cookie.setSecure(getSettings().getSecure());

    getWebResponse().addCookie(cookie);

    if (log.isDebugEnabled()) {
        log.debug("saved: " + cookieToDebugString(new CookieWrapper(cookie)));
    }

    return cookie;
}

From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Sets the cookie on the response./*from w ww  . ja v  a 2  s .  c o  m*/
 *
 * By default a secure cookie will be used if the connection is secure. You can set
 * the {@code useSecureCookie} property to {@code false} to override this. If you set
 * it to {@code true}, the cookie will always be flagged as secure. By default the cookie
 * will be marked as HttpOnly.
 *
 * @param tokens the tokens which will be encoded to make the cookie value.
 * @param maxAge the value passed to {@link Cookie#setMaxAge(int)}
 * @param request the request
 * @param response the response to add the cookie to.
 */
protected void setCookie(String[] tokens, int maxAge, HttpServletRequest request,
        HttpServletResponse response) {
    String cookieValue = encodeCookie(tokens);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(maxAge);
    cookie.setPath(getCookiePath(request));
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (maxAge < 1) {
        cookie.setVersion(1);
    }

    if (useSecureCookie == null) {
        cookie.setSecure(request.isSecure());
    } else {
        cookie.setSecure(useSecureCookie);
    }

    cookie.setHttpOnly(true);

    response.addCookie(cookie);
}

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

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

    Cookie cookie = new Cookie(cookieName, null);
    ;
    // COOKIE
    String cookiePath = COOKIE_PATH;

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

    cookie.setPath(cookiePath);

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

    cookie.setMaxAge(0);
    String domain = config.getDomain();

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

    response.addCookie(cookie);
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//w w  w  . j av a  2s  . c  om
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
@SuppressWarnings("unchecked")
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

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.  ja  v a  2s  . com*/
                cookie.setMaxAge(0);
                cookie.setValue(null);

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

                response.addCookie(cookie);
            }
        }
    }
}

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

public void putCookieValue(HttpServletRequest request, HttpServletResponse response, String path, String key,
        int age, Serializable value) throws CStudioException {

    String cookieValue = null;/*from  w  ww  .  j a va2s .c  o m*/

    if (_encryptCookies) {
        cookieValue = getEncryptedObjectAsString(value);
    } else {
        cookieValue = value.toString();
    }

    Cookie cookie = new Cookie(key, cookieValue);
    if (!StringUtils.isEmpty(path)) {
        cookie.setPath(path);
    } else {
        cookie.setPath("/");
    }
    cookie.setMaxAge(age);

    //if(request.getServerName().indexOf(".") != -1) {
    //   String validForDomain = request.getServerName().substring(request.getServerName().indexOf("."));
    //   cookie.setDomain(validForDomain);
    //}

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

    response.addCookie(cookie);
}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Creates a new completely initialized HTTP cookie, which is not yet assigned to the call.
 * Use {@link #addCookie(Cookie)} to do so and send it to the client.
 * The cookie is initialized with path (the OpenWGA context path), type/maxage (transient),
 * domain (either request host or host from configured server base url) and security
 * flag (true if the current call is HTTPS).
 * @param name Name of the cookie/*from  www  . j a  va2s.c om*/
 * @param value Value of the cookie
 * @return
 * @throws WGException
 */
public Cookie createCookie(String name, String value) throws WGException {

    URLBuilder baseURL = _wga.urlBuilder(_wga.server().getBaseURL());
    URLBuilder requestURL = _wga.urlBuilder(getURL());

    Cookie c = new Cookie();
    c.setName(name);
    c.setValue(value);
    c.setMaxAge(-1);
    c.setPath(baseURL.build(false));
    if (_wga.isRequestAvailable()) {
        c.setDomain(requestURL.getHost());
    } else {
        c.setDomain(baseURL.getHost());
    }
    c.setSecure(requestURL.getProtocol().equals("https"));

    return c;

}