Java Code Examples for javax.servlet.http.Cookie#setDomain()

The following examples show how to use javax.servlet.http.Cookie#setDomain() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CookieUtils.java    From yyblog with MIT License 6 votes vote down vote up
/**
 * 设置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();
    }
}
 
Example 2
Source File: ResponseUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
/**
 * 删除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);
}
 
Example 3
Source File: CookieHelper.java    From kisso with Apache License 2.0 6 votes vote down vote up
/**
 * <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;
}
 
Example 4
Source File: MockHttpServletResponseAssert.java    From gocd with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: NettyHttpServletRequest.java    From Jinx with Apache License 2.0 6 votes vote down vote up
@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];
}
 
Example 6
Source File: CookieUtil.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 删除指定名称的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]");
}
 
Example 7
Source File: MockCaasService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: CookieUtil.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 保存
 *
 * @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);
}
 
Example 9
Source File: CookieUtil.java    From hellokoding-courses with MIT License 5 votes vote down vote up
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);
}
 
Example 10
Source File: MockHttpServletResponseTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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));
}
 
Example 11
Source File: JWTAuthenticationFilter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 12
Source File: CookieUtil.java    From xxl-mq with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 保存
 *
 * @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);
}
 
Example 13
Source File: ContextResource.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: CredentialFlowStateHelperTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 15
Source File: CookieUtil.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 保存
 *
 * @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);
}
 
Example 16
Source File: OAuth2CookieHelper.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 17
Source File: SessionUtil.java    From two-token-sw with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 18
Source File: SingleSignOn.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example 19
Source File: SakaiLogin.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * 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");
}
 
Example 20
Source File: CookieGenerator.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * 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;
}