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

The following examples show how to use javax.servlet.http.Cookie#setHttpOnly() . 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: VertxVaadinResponseUT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void shouldDelegateAadCookie() throws Exception {
    Set<io.vertx.ext.web.Cookie> cookies = new LinkedHashSet<>();
    Cookie cookie = new Cookie("name", "value");
    cookie.setMaxAge(10);
    cookie.setSecure(true);
    cookie.setHttpOnly(true);
    cookie.setPath("path");
    cookie.setDomain("domain");
    vaadinResponse.addCookie(cookie);


    ArgumentCaptor<io.vertx.ext.web.Cookie> cookieCaptor = ArgumentCaptor.forClass(io.vertx.ext.web.Cookie.class);
    verify(routingContext).addCookie(cookieCaptor.capture());
    String expectedCookie = io.vertx.ext.web.Cookie.cookie(cookie.getName(), cookie.getValue())
        .setMaxAge(cookie.getMaxAge()).setSecure(cookie.getSecure())
        .setHttpOnly(cookie.isHttpOnly()).setPath(cookie.getPath())
        .setDomain(cookie.getDomain()).encode();
    assertThat(cookieCaptor.getValue().encode()).isEqualTo(expectedCookie);

}
 
Example 2
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 3
Source File: UserCurrentCookie.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
public static void setCurrentId(HttpServletResponse response, String currentId, String sessionId, 
		String account, String language) {
	try {
		String value = currentId + Constants.ID_DELIMITER + sessionId 
				+ Constants.ID_DELIMITER + account
				+ Constants.ID_DELIMITER + language;
		String encValue = EncryptorUtils.encrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(), value);
		encValue = SimpleUtils.toHex(encValue);
		Cookie cookie = new Cookie(Constants.APP_SITE_CURRENTID_COOKIE_NAME, encValue);		
		cookie.setPath("/");
		cookie.setValue(encValue);
		cookie.setMaxAge( 60*60*24 ); // 1-day
		//cookie.setHttpOnly(true); // 2018-07-04 rem
		cookie.setHttpOnly(false); // 2018-07-04 add
		response.addCookie(cookie);				
	} catch (Exception e) {
		e.printStackTrace();
	}					
}
 
Example 4
Source File: WebUtil.java    From Roothub with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void doSetCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds, String path, String domain, Boolean isHttpOnly) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAgeInSeconds);
    // set the default path value to "/"
    if (path == null) {
        path = "/";
    }
    cookie.setPath(path);

    if (domain != null) {
        cookie.setDomain(domain);
    }
    if (isHttpOnly != null) {
        cookie.setHttpOnly(isHttpOnly);
    }
    response.addCookie(cookie);
}
 
Example 5
Source File: JwtAuthenticationSuccessHandlerImpl.java    From quartz-manager with Apache License 2.0 6 votes vote down vote up
@Override
public void onLoginSuccess(Authentication authentication, HttpServletResponse response) throws IOException {
  log.debug("Login successed, generating jwtToken...");

  User user = (User) authentication.getPrincipal();
  String jwtToken = jwtTokenHelper.generateToken(user.getUsername());

  if(jwtSecurityProps.getCookieStrategy().isEnabled()) {
    Cookie authCookie = new Cookie(jwtSecurityProps.getCookieStrategy().getCookie(), jwtToken);
    authCookie.setHttpOnly(true);
    authCookie.setMaxAge((int) jwtSecurityProps.getExpirationInSec());
    authCookie.setPath(contextPath);
    response.addCookie(authCookie);
    log.debug("Set jwtToken into the cookie {}", jwtSecurityProps.getCookieStrategy().getCookie());
  }

  if(jwtSecurityProps.getHeaderStrategy().isEnabled()) {
    jwtTokenHelper.setHeader(response, jwtToken);
    log.debug("Set jwtToken into the response header {}", jwtSecurityProps.getHeaderStrategy().getHeader());
  }

  UserTokenState userTokenState = new UserTokenState(jwtToken, jwtSecurityProps.getExpirationInSec());
  String jwtResponse = objectMapper.writeValueAsString(userTokenState);
  response.setContentType("application/json");
  response.getWriter().write(jwtResponse);
}
 
Example 6
Source File: AppCookies.java    From cuba with Apache License 2.0 5 votes vote down vote up
public void removeCookie(String name) {
    if (isCookiesEnabled()) {
        Cookie cookie = getCookie(name);
        if (cookie != null) {
            cookie.setValue(null);
            cookie.setPath(getCookiePath());
            cookie.setMaxAge(0);
            cookie.setHttpOnly(this.httpOnly);
            addCookie(cookie);
        }
    }
}
 
Example 7
Source File: LogonImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setCookieHostId(String hostId) {
      Cookie cookie = new Cookie(hostIdCookieName, hostId);

      cookie.setMaxAge(MAX_COOKIE_AGE);
      cookie.setSecure(useSecureCookies);
cookie.setHttpOnly(true);

      response.addCookie(cookie);
  }
 
Example 8
Source File: SessAccess.java    From HongsCORE with MIT License 5 votes vote down vote up
protected final void delCookie() {
    if (rsp.isCommitted()) {
        CoreLogger.error("Can not DEL session id for Cookie {}={}; Path={}, the response is committed.",
                  flt.SSCN, xid, flt.SSCP);
        return;
    }

    Cookie cok = new Cookie(flt.SSCN, xid);
    cok.setHttpOnly  (true);
    cok.setPath  (flt.SSCP);
    cok.setMaxAge( 0 );
    rsp.addCookie(cok);
}
 
Example 9
Source File: CookieUtil.java    From hello-sso-jwt-auth with MIT License 5 votes vote down vote up
public static void clear(HttpServletResponse httpServletResponse, String name) {
    Cookie cookie = new Cookie(name, null);
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0);
    httpServletResponse.addCookie(cookie);
}
 
Example 10
Source File: CookieUtil.java    From hello-sso-jwt-resource 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 11
Source File: CookieUtil.java    From hellokoding-courses with MIT License 5 votes vote down vote up
public static void clear(HttpServletResponse httpServletResponse, String name) {
    Cookie cookie = new Cookie(name, null);
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0);
    httpServletResponse.addCookie(cookie);
}
 
Example 12
Source File: CookieService.java    From NLIDB with Apache License 2.0 5 votes vote down vote up
public void expireUserIdCookie(HttpServletResponse res, String userId) {
    Cookie cookie = new Cookie(COOKIE_NAME, userId);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    res.addCookie(cookie);
}
 
Example 13
Source File: ProxyServlet.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
protected void addCookie(final HttpServletResponse resp, final Map.Entry<String, NewCookie> cookie) {
    final NewCookie nc = cookie.getValue();
    final Cookie servletCookie = new Cookie(cookie.getKey(), nc.getValue());
    servletCookie.setComment(nc.getComment());
    if (nc.getDomain() != null) {
        servletCookie.setDomain(nc.getDomain());
    }
    servletCookie.setHttpOnly(nc.isHttpOnly());
    servletCookie.setSecure(nc.isSecure());
    servletCookie.setMaxAge(nc.getMaxAge());
    servletCookie.setPath(nc.getPath());
    servletCookie.setVersion(nc.getVersion());
    resp.addCookie(servletCookie);
}
 
Example 14
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 15
Source File: SessAccess.java    From HongsCORE with MIT License 5 votes vote down vote up
protected final void setCookie() {
    if (rsp.isCommitted()) {
        CoreLogger.error("Can not SET session id for Cookie {}={}; Path={}, the response is committed.",
                  flt.SSCN, xid, flt.SSCP);
        return;
    }

    Cookie cok = new Cookie(flt.SSCN, xid);
    cok.setHttpOnly  (true);
    cok.setPath  (flt.SSCP);
    if (flt.SSCX > 0 ) {
    cok.setMaxAge(flt.SSCX);
    }
    rsp.addCookie(cok);
}
 
Example 16
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 17
Source File: HttpOnlyCookieSamples.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
void unsafeCookie3(Cookie cookieOther) {
    Cookie newCookie = new Cookie("test1","1234");
    cookieOther.setHttpOnly(true); //Unrelated
}
 
Example 18
Source File: PrintingResultHandlerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void printResponse() throws Exception {
	Cookie enigmaCookie = new Cookie("enigma", "42");
	enigmaCookie.setComment("This is a comment");
	enigmaCookie.setHttpOnly(true);
	enigmaCookie.setMaxAge(1234);
	enigmaCookie.setDomain(".example.com");
	enigmaCookie.setPath("/crumbs");
	enigmaCookie.setSecure(true);

	this.response.setStatus(400, "error");
	this.response.addHeader("header", "headerValue");
	this.response.setContentType("text/plain");
	this.response.getWriter().print("content");
	this.response.setForwardedUrl("redirectFoo");
	this.response.sendRedirect("/redirectFoo");
	this.response.addCookie(new Cookie("cookie", "cookieValue"));
	this.response.addCookie(enigmaCookie);

	this.handler.handle(this.mvcResult);

	HttpHeaders headers = new HttpHeaders();
	headers.set("header", "headerValue");
	headers.setContentType(MediaType.TEXT_PLAIN);
	headers.setLocation(new URI("/redirectFoo"));

	String heading = "MockHttpServletResponse";
	assertValue(heading, "Status", this.response.getStatus());
	assertValue(heading, "Error message", response.getErrorMessage());
	assertValue(heading, "Headers", headers);
	assertValue(heading, "Content type", this.response.getContentType());
	assertValue(heading, "Body", this.response.getContentAsString());
	assertValue(heading, "Forwarded URL", this.response.getForwardedUrl());
	assertValue(heading, "Redirected URL", this.response.getRedirectedUrl());

	Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues;
	String[] cookies = (String[]) printedValues.get(heading).get("Cookies");
	assertEquals(2, cookies.length);
	String cookie1 = cookies[0];
	String cookie2 = cookies[1];
	assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName()));
	assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'"));
	assertTrue(cookie1.endsWith("]"));
	assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName()));
	assertTrue(cookie2.contains("name = 'enigma', value = '42', comment = 'This is a comment', domain = '.example.com', maxAge = 1234, path = '/crumbs', secure = true, version = 0, httpOnly = true"));
	assertTrue(cookie2.endsWith("]"));
}
 
Example 19
Source File: SingleSignOn.java    From Tomcat7.0.67 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 20
Source File: HttpOnlyCookieSamples.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
void unsafeCookie1() {
    Cookie newCookie = new Cookie("test1","1234");
    newCookie.setHttpOnly(false);
}