javax.servlet.http.Cookie#setDomain()源码实例Demo

下面列出了javax.servlet.http.Cookie#setDomain() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: yyblog   文件: CookieUtils.java
/**
 * 设置Cookie的值,并使其在指定时间内生效
 * 
 * @param cookieMaxage cookie生效的最大秒数
 */
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
        String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
    try {
        if (cookieValue == null) {
            cookieValue = "";
        } else {
            cookieValue = URLEncoder.encode(cookieValue, encodeString);
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0)
            cookie.setMaxAge(cookieMaxage);
        if (null != request) {// 设置域名的cookie
        	String domainName = getDomainName(request);
        	System.out.println(domainName);
            if (!"localhost".equals(domainName)) {
            	cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    } catch (Exception e) {
    	 e.printStackTrace();
    }
}
 
源代码2 项目: gocd   文件: MockHttpServletResponseAssert.java
public SELF hasCookie(String path, String name, String value, int maxAge, boolean secured, boolean httpOnly) {
    Cookie actualCookie = actual.getCookie(name);

    Cookie expectedCookie = new Cookie(name, value);
    expectedCookie.setDomain("");
    expectedCookie.setPath(path);
    expectedCookie.setMaxAge(maxAge);
    expectedCookie.setSecure(secured);
    expectedCookie.setHttpOnly(httpOnly);

    if (!EqualsBuilder.reflectionEquals(expectedCookie, actualCookie)) {
        this.as("cookie");

        throw Failures.instance().failure(info, shouldBeEqual(ReflectionToStringBuilder.toString(actualCookie, ToStringStyle.MULTI_LINE_STYLE), ReflectionToStringBuilder.toString(expectedCookie, ToStringStyle.MULTI_LINE_STYLE), info.representation()));
    }
    return myself;
}
 
源代码3 项目: Jinx   文件: NettyHttpServletRequest.java
@Override
public Cookie[] getCookies() {
    String cookieString = this.request.headers().get(COOKIE);
    if (cookieString != null) {
        Set<io.netty.handler.codec.http.Cookie> cookies = CookieDecoder.decode(cookieString);
        if (!cookies.isEmpty()) {
            Cookie[] cookiesArray = new Cookie[cookies.size()];
            int indx = 0;
            for (io.netty.handler.codec.http.Cookie c : cookies) {
                Cookie cookie = new Cookie(c.getName(), c.getValue());
                cookie.setComment(c.getComment());
                cookie.setDomain(c.getDomain());
                cookie.setMaxAge((int) c.getMaxAge());
                cookie.setPath(c.getPath());
                cookie.setSecure(c.isSecure());
                cookie.setVersion(c.getVersion());
                cookiesArray[indx] = cookie;
                indx++;
            }
            return cookiesArray;

        }
    }
    return new Cookie[0];
}
 
源代码4 项目: kisso   文件: CookieHelper.java
/**
 * <p>
 * 清除指定Cookie 等同于 clearCookieByName(...)
 * </p>
 * <p>
 * <p>
 * 该方法不判断Cookie是否存在,因此不对外暴露防止Cookie不存在异常.
 * </p>
 *
 * @param response
 * @param cookieName cookie name
 * @param domain     Cookie所在的域
 * @param path       Cookie 路径
 * @return boolean
 */
private static boolean clearCookie(HttpServletResponse response, String cookieName, String domain, String path) {
    boolean result = false;
    try {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setMaxAge(CLEAR_IMMEDIATELY_REMOVE);
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        response.addCookie(cookie);
        log.debug("clear cookie " + cookieName);
        result = true;
    } catch (Exception e) {
        log.error("clear cookie " + cookieName + " is exception!\n" + e.toString());
    }
    return result;
}
 
源代码5 项目: onetwo   文件: ResponseUtils.java
/**
 * 删除cookie
 * 
 * @param response
 * @param name
 * @param path
 */
/*
 * public static void removeCookie(HttpServletRequest request,
 * HttpServletResponse response, String name) { Cookie[] cookies =
 * request.getCookies(); if(cookies==null) return ; for(Cookie ck :
 * cookies){ if(name.equals(ck.getName())){ ck.setMaxAge(0);
 * response.addCookie(ck); } } }
 */
public static void removeCookie(HttpServletResponse response, String name, String path, String domain) {
	Cookie ck = new Cookie(name, "");
	ck.setMaxAge(0);
	if (StringUtils.isNotBlank(path)) {
		ck.setPath(path);
	}
	if (StringUtils.isNotBlank(domain)) {
		ck.setDomain(domain);
	}
	response.addCookie(ck);
}
 
源代码6 项目: two-token-sw   文件: SessionUtil.java
public static void refreshSessionCookie(
    HttpServletRequest request,
    HttpServletResponse response,
    String cookieName,
    String domain,
    int maxAge) {
  Cookie cookie = getSessionCookie(request, cookieName);
  if (cookie != null) {
    cookie.setMaxAge(maxAge);
    cookie.setDomain(domain);
    cookie.setPath("/");
    response.addCookie(cookie);
  }
}
 
源代码7 项目: paascloud-master   文件: CookieUtil.java
/**
 * 删除指定名称的Cookie.
 *
 * @param name     the name
 * @param response the response
 */
public static void removeCookie(String name, HttpServletResponse response) {
	logger.info("removeCookie - 删除指定名称的Cookie. key={}", name);
	Cookie cookie = new Cookie(name, null);
	cookie.setDomain(COOKIE_DOMAIN);
	cookie.setPath(COOKIE_PATH);
	cookie.setMaxAge(0);
	response.addCookie(cookie);
	logger.info("removeCookie - 删除指定名称的Cookie. [OK]");
}
 
源代码8 项目: tutorials   文件: OAuth2CookieHelper.java
/**
 * Set cookie properties of access and refresh tokens.
 *
 * @param cookie   the cookie to modify.
 * @param isSecure whether it is coming from a secure request.
 * @param domain   the domain for which the cookie is valid. If null, then will fall back to default.
 */
private void setCookieProperties(Cookie cookie, boolean isSecure, String domain) {
    cookie.setHttpOnly(true);
    cookie.setPath("/");
    cookie.setSecure(isSecure);       //if the request comes per HTTPS set the secure option on the cookie
    if (domain != null) {
        cookie.setDomain(domain);
    }
}
 
源代码9 项目: zuihou-admin-cloud   文件: CookieUtil.java
/**
 * 保存
 *
 * @param response
 * @param key
 * @param value
 * @param maxAge
 */
private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
    Cookie cookie = new Cookie(key, value);
    if (domain != null) {
        cookie.setDomain(domain);
    }
    cookie.setPath(path);
    cookie.setMaxAge(maxAge);
    cookie.setHttpOnly(isHttpOnly);
    response.addCookie(cookie);
}
 
源代码10 项目: syndesis   文件: CredentialFlowStateHelperTest.java
@Test
public void shouldConvertServletCookieToJaxRsCookie() {
    final Cookie given = new Cookie("myCookie", "myValue");
    given.setDomain("example.com");
    given.setPath("/path");
    given.setMaxAge(1800);
    given.setHttpOnly(true);
    given.setSecure(true);

    final javax.ws.rs.core.Cookie expected = new javax.ws.rs.core.Cookie("myCookie", "myValue", "/path",
        "example.com");

    assertThat(CredentialFlowStateHelper.toJaxRsCookie(given)).isEqualTo(expected);
}
 
public static void setCookie(ServletRequest request, ServletResponse response, String name, String value,
                             boolean set, boolean global, boolean bSecureCookie, Integer maxAge, boolean httpOnly) {
    Cookie ck = new Cookie(name, value);

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (httpOnly) {
        ck.setHttpOnly(true);
    }

    if (set) {
        if (maxAge != null) {
            ck.setMaxAge(maxAge.intValue());
        } else {
            ck.setMaxAge(-1);
        }
    } else {
        ck.setMaxAge(0);
    }
    ck.setPath("/");

    // for local and fngn envs., we should not set cookie as a secure cookie
    if (bSecureCookie) {
        ck.setSecure(true);
    }

    ck.setDomain(COOKIE_DOMAIN);


    ((HttpServletResponse) response).addCookie(ck);
}
 
源代码12 项目: xxl-mq   文件: CookieUtil.java
/**
 * 保存
 *
 * @param response
 * @param key
 * @param value
 * @param maxAge
 */
private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
	Cookie cookie = new Cookie(key, value);
	if (domain != null) {
		cookie.setDomain(domain);
	}
	cookie.setPath(path);
	cookie.setMaxAge(maxAge);
	cookie.setHttpOnly(isHttpOnly);
	response.addCookie(cookie);
}
 
private void removeJWTAuthenticationCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie(authCookieName, null);
    cookie.setSecure(jwtCookieSecure);
    cookie.setPath(jwtCookiePath);
    cookie.setDomain(jwtCookieDomain);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
}
 
@Test
public void cookies() {
	Cookie cookie = new Cookie("foo", "bar");
	cookie.setPath("/path");
	cookie.setDomain("example.com");
	cookie.setMaxAge(0);
	cookie.setSecure(true);
	cookie.setHttpOnly(true);

	response.addCookie(cookie);

	assertEquals("foo=bar; Path=/path; Domain=example.com; " +
			"Max-Age=0; Expires=Thu, 1 Jan 1970 00:00:00 GMT; " +
			"Secure; HttpOnly", response.getHeader(HttpHeaders.SET_COOKIE));
}
 
源代码15 项目: hellokoding-courses   文件: CookieUtil.java
public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
    Cookie cookie = new Cookie(name, value);
    cookie.setSecure(secure);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(maxAge);
    cookie.setDomain(domain);
    cookie.setPath("/");
    httpServletResponse.addCookie(cookie);
}
 
源代码16 项目: lightconf   文件: CookieUtil.java
/**
 * 保存
 *
 * @param response
 * @param key
 * @param value
 * @param maxAge
 */
private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) {
    Cookie cookie = new Cookie(key, value);
    if (domain != null) {
        cookie.setDomain(domain);
    }
    cookie.setPath(path);
    cookie.setMaxAge(maxAge);
    cookie.setHttpOnly(isHttpOnly);
    response.addCookie(cookie);
}
 
源代码17 项目: cloudbreak   文件: MockCaasService.java
public void auth(@Nonnull HttpServletRequest httpServletRequest, @Nonnull HttpServletResponse httpServletResponse, @Nonnull Optional<String> tenant,
        @Nonnull Optional<String> userName, String redirectUri, Boolean active) {
    if (tenant.isEmpty() || userName.isEmpty()) {
        LOGGER.info("redirect to sign in page");
        httpServletResponse.setHeader(LOCATION_HEADER_KEY, "../caas/sign-in.html?redirect_uri=" + redirectUri);
    } else {
        Cookie cdpSessionToken = new Cookie(CDP_SESSION_TOKEN, getAltusToken(tenant.get(), userName.get()));
        cdpSessionToken.setDomain("");
        cdpSessionToken.setPath("/");
        httpServletResponse.addCookie(cdpSessionToken);

        httpServletResponse.setHeader(LOCATION_HEADER_KEY, redirectUri);
    }
    httpServletResponse.setStatus(SC_FOUND);
}
 
源代码18 项目: sakai   文件: SakaiLogin.java
/**
 * Actual login method
 * @param id
 * @param pw
 * @return
 */
private java.lang.String login(java.lang.String id, java.lang.String pw) {

    Message message = PhaseInterceptorChain.getCurrentMessage();
    HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
    String ipAddress = request.getRemoteAddr();

    boolean allowLogin = serverConfigurationService.getBoolean("webservices.allowlogin", false);

    if (!allowLogin) {
        throw new RuntimeException("Web Services Login Disabled");
    }

    try {
        if ("GET".equals(request.getMethod())) {
            log.info("This endpoint {} should use POST instead of GET, GET will be deprecated in a future release", request.getRequestURI());
        }

        Evidence e = new IdPwEvidence(id, pw, ipAddress);
        Authentication a = authenticationManager.authenticate(e);

        Session s = sessionManager.startSession();
        sessionManager.setCurrentSession(s);

        if (s == null) {
            log.warn("Web Services Login failed to establish session for id=" + id + " ip=" + ipAddress);
            throw new RuntimeException("Unable to establish session");
        } else {
            // We do not care too much on the off-chance that this fails - folks simply won't show up in presense
            // and events won't be trackable back to people / IP Addresses - but if it fails - there is nothing
            // we can do anyways.

            usageSessionService.login(a.getUid(), id, ipAddress, "SakaiLogin", UsageSessionService.EVENT_LOGIN_WS);

            log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());

            // retrieve the configured cookie name, if any
            if (System.getProperty(RequestFilter.SAKAI_COOKIE_PROP) != null) {
                cookieName = System.getProperty(RequestFilter.SAKAI_COOKIE_PROP);
            }

            // retrieve the configured cookie domain, if any

            // compute the session cookie suffix, based on this configured server id
            String suffix = System.getProperty(RequestFilter.SAKAI_SERVERID);
            if (StringUtils.isEmpty(suffix)) {
                if (m_displayModJkWarning) {
                    log.warn("no sakai.serverId system property set - mod_jk load balancing will not function properly");
                }
                m_displayModJkWarning = false;
                suffix = "sakai";
            }

            Cookie c = new Cookie(cookieName, s.getId() + "." + suffix);
            c.setPath("/");
            c.setMaxAge(-1);
            if (System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN) != null) {
                c.setDomain(System.getProperty(RequestFilter.SAKAI_COOKIE_DOMAIN));
            }
            if (request.isSecure() == true) {
                c.setSecure(true);
            }

            HttpServletResponse res = (HttpServletResponse) message.get(AbstractHTTPDestination.HTTP_RESPONSE);

            if (res != null) {
                res.addCookie(c);
            }

            log.debug("Sakai Web Services Login id={} ip={} session={}", id, ipAddress, s.getId());
            return s.getId();
        }
    } catch (AuthenticationException ex) {
        log.warn("Failed Web Services Login id=" + id + " ip=" + ipAddress + ": " + ex.getMessage());
    }

    throw new RuntimeException("Unable to login");
}
 
源代码19 项目: tomcatsrc   文件: SingleSignOn.java
/**
 * Perform single-sign-on support processing for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException {

    request.removeNote(Constants.REQ_SSOID_NOTE);

    // Has a valid user already been authenticated?
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.invoke", request.getRequestURI()));
    }
    if (request.getUserPrincipal() != null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.hasPrincipal",
                    request.getUserPrincipal().getName()));
        }
        getNext().invoke(request, response);
        return;
    }

    // Check for the single sign on cookie
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.cookieCheck"));
    }
    Cookie cookie = null;
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }
    }
    if (cookie == null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.cookieNotFound"));
        }
        getNext().invoke(request, response);
        return;
    }

    // Look up the cached Principal associated with this cookie value
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.principalCheck",
                cookie.getValue()));
    }
    SingleSignOnEntry entry = cache.get(cookie.getValue());
    if (entry != null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.principalFound",
                    entry.getPrincipal() != null ? entry.getPrincipal().getName() : "",
                    entry.getAuthType()));
        }
        request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
        // Only set security elements if reauthentication is not required
        if (!getRequireReauthentication()) {
            request.setAuthType(entry.getAuthType());
            request.setUserPrincipal(entry.getPrincipal());
        }
    } else {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.principalNotFound",
                    cookie.getValue()));
        }
        // No need to return a valid SSO session ID
        cookie.setValue("REMOVE");
        // Age of zero will trigger removal
        cookie.setMaxAge(0);
        // Domain and path have to match the original cookie to 'replace'
        // the original cookie
        cookie.setPath("/");
        String domain = getCookieDomain();
        if (domain != null) {
            cookie.setDomain(domain);
        }
        // This is going to trigger a Set-Cookie header. While the value is
        // not security sensitive, ensure that expectations for secure and
        // httpOnly are met
        cookie.setSecure(request.isSecure());
        if (request.getServletContext().getSessionCookieConfig().isHttpOnly() ||
                request.getContext().getUseHttpOnly()) {
            cookie.setHttpOnly(true);
        }

        response.addCookie(cookie);
    }

    // Invoke the next Valve in our pipeline
    getNext().invoke(request, response);
}
 
源代码20 项目: java-technology-stack   文件: CookieGenerator.java
/**
 * Create a cookie with the given value, using the cookie descriptor
 * settings of this generator (except for "cookieMaxAge").
 * @param cookieValue the value of the cookie to crate
 * @return the cookie
 * @see #setCookieName
 * @see #setCookieDomain
 * @see #setCookiePath
 */
protected Cookie createCookie(String cookieValue) {
	Cookie cookie = new Cookie(getCookieName(), cookieValue);
	if (getCookieDomain() != null) {
		cookie.setDomain(getCookieDomain());
	}
	cookie.setPath(getCookiePath());
	return cookie;
}