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.apache.hadoop.security.authentication.server.AuthenticationFilter.java

/**
 * Creates the Hadoop authentiation HTTP cookie.
 * <p/>/*  w w  w  .j a v a  2 s .c o m*/
 * It sets the domain and path specified in the configuration.
 *
 * @param token authentication token for the cookie.
 *
 * @return the HTTP cookie.
 */
protected Cookie createCookie(String token) {
    Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, token);
    if (getCookieDomain() != null) {
        cookie.setDomain(getCookieDomain());
    }
    if (getCookiePath() != null) {
        cookie.setPath(getCookiePath());
    }
    return cookie;
}

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 . j  a v a  2s  . c  o 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.orcid.core.manager.impl.InternalSSOManagerImpl.java

@SuppressWarnings("unchecked")
@Override//w ww.j av a2 s. c  om
public void updateCookie(String orcid, HttpServletRequest request, HttpServletResponse response) {
    if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(COOKIE_NAME)) {
                HashMap<String, String> cookieValues = JsonUtils.readObjectFromJsonString(cookie.getValue(),
                        HashMap.class);
                if (cookieValues.containsKey(COOKIE_KEY_TOKEN)) {
                    if (internalSSODao.update(orcid, cookieValues.get(COOKIE_KEY_TOKEN))) {
                        //Create new cookie
                        Cookie tokenCookie = new Cookie(COOKIE_NAME, cookie.getValue());
                        tokenCookie.setMaxAge(maxAgeMinutes * 60);
                        tokenCookie.setPath("/");
                        tokenCookie.setSecure(true);
                        tokenCookie.setHttpOnly(true);
                        tokenCookie.setDomain(allowedDomain.trim());
                        //Add new cookie to response
                        response.addCookie(tokenCookie);
                    }
                }
                break;
            }
        }
    }
}

From source file:org.jasig.portal.portlet.dao.jpa.PortletCookieImpl.java

@Override
public Cookie toCookie() {
    Cookie cookie = new Cookie(this.name, this.value);
    cookie.setComment(this.comment);
    if (this.domain != null) {
        // FYI: setDomain requires non-null argument (requirement not documented)
        cookie.setDomain(this.domain);
    }//  w w w  .  java 2  s.  c o m

    final int maxAge;
    if (this.expires == null) {
        maxAge = -1;
    } else {
        maxAge = (int) TimeUnit.MILLISECONDS.toSeconds(this.expires.getTime() - System.currentTimeMillis());
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath(this.path);
    cookie.setSecure(this.secure);
    cookie.setVersion(this.version);
    return cookie;
}

From source file:net.ymate.platform.webmvc.util.CookieHelper.java

/**
 * @param key    //  w w  w.  j  a  v a 2 s.c  om
 * @param value  
 * @param maxAge 
 * @return ?Cookie
 */
public CookieHelper setCookie(String key, String value, int maxAge) {
    Cookie _cookie = new Cookie(__owner.getModuleCfg().getCookiePrefix() + key,
            StringUtils.isBlank(value) ? "" : encodeValue(value));
    _cookie.setMaxAge(maxAge);
    _cookie.setPath(__owner.getModuleCfg().getCookiePath());
    if (StringUtils.isNotBlank(__owner.getModuleCfg().getCookieDomain())) {
        _cookie.setDomain(__owner.getModuleCfg().getCookieDomain());
    }
    _cookie.setSecure(WebContext.getRequest().isSecure());
    WebContext.getResponse().addCookie(_cookie);
    return this;
}

From source file:com.ctc.storefront.controllers.pages.CartPageController.java

private void setCookie(final HttpServletResponse response, final CartData cartData) {
    final Cookie cookie = new Cookie("cartQuantity", String.valueOf(cartData.getTotalUnitCount()));
    cookie.setMaxAge(60 * 60);//from w  w  w .j a v  a2 s. c  o m
    cookie.setPath("/");
    cookie.setDomain(getSiteConfigService().getString(CART_COUNT_COOKIE_DOMAIN_NAME, ".ctc.com"));
    response.addCookie(cookie);
}

From source file:net.ymate.platform.mvc.web.support.CookieHelper.java

/**
 * @param key /*from ww w  .j a  va 2  s.  com*/
 * @param value 
 * @param maxAge 
 * @return ?Cookie
 */
public CookieHelper setCookie(String key, String value, int maxAge) {
    Cookie _cookie = new Cookie(WebMVC.getConfig().getCookiePrefix() + key,
            StringUtils.isBlank(value) ? "" : encodeValue(value));
    _cookie.setMaxAge(maxAge);
    _cookie.setPath(WebMVC.getConfig().getCookiePath());
    if (StringUtils.isNotBlank(WebMVC.getConfig().getCookieDomain())) {
        _cookie.setDomain(WebMVC.getConfig().getCookieDomain());
    }
    _cookie.setSecure(__request.getServerPort() == 443 ? true : false);
    WebContext.getResponse().addCookie(_cookie);
    return this;
}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie/*from  ww  w  .jav  a2s . c om*/
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

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

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

    return extAuthCookie;
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse,
        final String cookieName, final String cookieValue) {
    if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   ww w  .  ja v a  2  s  . c  om*/
    final Cookie cookie = new Cookie(cookieName, "");
    cookie.setValue(cookieValue);
    cookie.setMaxAge(-1);
    cookie.setSecure(true);
    cookie.setDomain(httpRequest.getServerName());
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    httpResponse.addCookie(cookie);
    return cookie.getValue();
}

From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java

/**
 * Generate a server side cookie given the cookie value as the input.
 * @param str Input string token./*from   w w  w  .  j  av a 2 s .  c om*/
 * @return The generated cookie.
 * @throws UnsupportedEncodingException
 */
private Cookie createCookie(String str) throws UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Cookie name = " + AUTH_COOKIE + " value = " + str);
    }
    Cookie cookie = new Cookie(AUTH_COOKIE, str);

    cookie.setMaxAge(cookieMaxAge);
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (cookiePath != null) {
        cookie.setPath(cookiePath);
    }
    cookie.setSecure(isCookieSecure);
    return cookie;
}