org.springframework.http.ResponseCookie Java Examples

The following examples show how to use org.springframework.http.ResponseCookie. 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: CookieWebSessionIdResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cookieInitializer() {
	this.resolver.addCookieInitializer(builder -> builder.domain("example.org"));
	this.resolver.addCookieInitializer(builder -> builder.sameSite("Strict"));
	this.resolver.addCookieInitializer(builder -> builder.secure(false));

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.org/path").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	this.resolver.setSessionId(exchange, "123");

	MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
	assertEquals(1, cookies.size());
	ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
	assertNotNull(cookie);
	assertEquals("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict", cookie.toString());
}
 
Example #2
Source File: CookieWebSessionIdResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
private ResponseCookie initSessionCookie(
		ServerWebExchange exchange, String id, Duration maxAge) {

	ResponseCookie.ResponseCookieBuilder cookieBuilder = ResponseCookie.from(this.cookieName, id)
			.path(exchange.getRequest().getPath().contextPath().value() + "/")
			.maxAge(maxAge)
			.httpOnly(true)
			.secure("https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme()))
			.sameSite("Lax");

	if (this.cookieInitializer != null) {
		this.cookieInitializer.accept(cookieBuilder);
	}

	return cookieBuilder.build();
}
 
Example #3
Source File: DefaultServerResponseBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void from() {
	ResponseCookie cookie = ResponseCookie.from("foo", "bar").build();
	ServerResponse other = ServerResponse.ok().header("foo", "bar")
			.cookie(cookie)
			.hint("foo", "bar")
			.build().block();

	Mono<ServerResponse> result = ServerResponse.from(other).build();
	StepVerifier.create(result)
			.expectNextMatches(response -> HttpStatus.OK.equals(response.statusCode()) &&
					"bar".equals(response.headers().getFirst("foo")) &&
					cookie.equals(response.cookies().getFirst("foo")))
			.expectComplete()
			.verify();
}
 
Example #4
Source File: DefaultServerResponseBuilderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void build() {
	ResponseCookie cookie = ResponseCookie.from("name", "value").build();
	Mono<ServerResponse>
			result = ServerResponse.status(HttpStatus.CREATED)
			.header("MyKey", "MyValue")
			.cookie(cookie).build();

	MockServerHttpRequest request = MockServerHttpRequest.get("http://example.com").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block();

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.CREATED, response.getStatusCode());
	assertEquals("MyValue", response.getHeaders().getFirst("MyKey"));
	assertEquals("value", response.getCookies().getFirst("name").getValue());
	StepVerifier.create(response.getBody()).expectComplete().verify();
}
 
Example #5
Source File: ServerHttpResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void beforeCommitWithComplete() throws Exception {
	ResponseCookie cookie = ResponseCookie.from("ID", "123").build();
	TestServerHttpResponse response = new TestServerHttpResponse();
	response.beforeCommit(() -> Mono.fromRunnable(() -> response.getCookies().add(cookie.getName(), cookie)));
	response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block();

	assertTrue(response.statusCodeWritten);
	assertTrue(response.headersWritten);
	assertTrue(response.cookiesWritten);
	assertSame(cookie, response.getCookies().getFirst("ID"));

	assertEquals(3, response.body.size());
	assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
	assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
	assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
}
 
Example #6
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieSetInResponse() {
    final String token = "test_token";
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            ResponseCookie cookie = filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME);
            assertThat(cookie).isNotNull();
            assertThat(cookie.getName()).isEqualTo(CSRF_COOKIE_NAME);
            assertThat(cookie.getValue()).isEqualTo(token);
            assertThat(cookie.getPath()).isEqualTo("/");
            assertThat(cookie.getMaxAge()).isEqualTo(Duration.ofSeconds(-1));
            assertThat(cookie.isHttpOnly()).isFalse();
            assertThat(cookie.isSecure()).isFalse();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.post(TEST_URL)
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", token)));
    this.filter.filter(exchange, filterChain).block();
}
 
Example #7
Source File: ServletServerHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new Cookie(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.response.addCookie(cookie);
		}
	}
}
 
Example #8
Source File: UndertowServerHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new CookieImpl(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.exchange.getResponseCookies().putIfAbsent(name, cookie);
		}
	}
}
 
Example #9
Source File: CookieWebSessionIdResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private ResponseCookie initSessionCookie(
		ServerWebExchange exchange, String id, Duration maxAge) {

	ResponseCookie.ResponseCookieBuilder cookieBuilder = ResponseCookie.from(this.cookieName, id)
			.path(exchange.getRequest().getPath().contextPath().value() + "/")
			.maxAge(maxAge)
			.httpOnly(true)
			.secure("https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme()))
			.sameSite("Lax");

	if (this.cookieInitializer != null) {
		this.cookieInitializer.accept(cookieBuilder);
	}

	return cookieBuilder.build();
}
 
Example #10
Source File: MockServerHttpResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cookieHeaderSet() throws Exception {

	ResponseCookie foo11 = ResponseCookie.from("foo1", "bar1").build();
	ResponseCookie foo12 = ResponseCookie.from("foo1", "bar2").build();
	ResponseCookie foo21 = ResponseCookie.from("foo2", "baz1").build();
	ResponseCookie foo22 = ResponseCookie.from("foo2", "baz2").build();

	MockServerHttpResponse response = new MockServerHttpResponse();
	response.addCookie(foo11);
	response.addCookie(foo12);
	response.addCookie(foo21);
	response.addCookie(foo22);

	response.applyCookies();

	assertEquals(Arrays.asList("foo1=bar1", "foo1=bar2", "foo2=baz1", "foo2=baz2"),
			response.getHeaders().get(HttpHeaders.SET_COOKIE));
}
 
Example #11
Source File: ArmeriaServerHttpResponse.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@link ResponseCookie} to Netty's {@link Cookie} interface.
 */
private static Cookie toArmeriaCookie(ResponseCookie resCookie) {
    final CookieBuilder builder = Cookie.builder(resCookie.getName(), resCookie.getValue());
    if (!resCookie.getMaxAge().isNegative()) {
        builder.maxAge(resCookie.getMaxAge().getSeconds());
    }
    if (resCookie.getDomain() != null) {
        builder.domain(resCookie.getDomain());
    }
    if (resCookie.getPath() != null) {
        builder.path(resCookie.getPath());
    }
    builder.secure(resCookie.isSecure());
    builder.httpOnly(resCookie.isHttpOnly());
    if (resCookie.getSameSite() != null) {
        builder.sameSite(resCookie.getSameSite());
    }
    return builder.build();
}
 
Example #12
Source File: DefaultServerResponseBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void build() {
	ResponseCookie cookie = ResponseCookie.from("name", "value").build();
	Mono<ServerResponse>
			result = ServerResponse.status(HttpStatus.CREATED)
			.header("MyKey", "MyValue")
			.cookie(cookie).build();

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	result.flatMap(res -> res.writeTo(exchange, EMPTY_CONTEXT)).block();

	MockServerHttpResponse response = exchange.getResponse();
	assertEquals(HttpStatus.CREATED, response.getStatusCode());
	assertEquals("MyValue", response.getHeaders().getFirst("MyKey"));
	assertEquals("value", response.getCookies().getFirst("name").getValue());
	StepVerifier.create(response.getBody()).expectComplete().verify();
}
 
Example #13
Source File: JettyClientHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public MultiValueMap<String, ResponseCookie> getCookies() {
	MultiValueMap<String, ResponseCookie> result = new LinkedMultiValueMap<>();
	List<String> cookieHeader = getHeaders().get(HttpHeaders.SET_COOKIE);
	if (cookieHeader != null) {
		cookieHeader.forEach(header -> {
			HttpCookie.parse(header)
					.forEach(cookie -> result.add(cookie.getName(),
							ResponseCookie.from(cookie.getName(), cookie.getValue())
					.domain(cookie.getDomain())
					.path(cookie.getPath())
					.maxAge(cookie.getMaxAge())
					.secure(cookie.getSecure())
					.httpOnly(cookie.isHttpOnly())
					.build()));
		});
	}
	return CollectionUtils.unmodifiableMultiValueMap(result);
}
 
Example #14
Source File: ServerHttpResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void beforeCommitWithComplete() throws Exception {
	ResponseCookie cookie = ResponseCookie.from("ID", "123").build();
	TestServerHttpResponse response = new TestServerHttpResponse();
	response.beforeCommit(() -> Mono.fromRunnable(() -> response.getCookies().add(cookie.getName(), cookie)));
	response.writeWith(Flux.just(wrap("a"), wrap("b"), wrap("c"))).block();

	assertTrue(response.statusCodeWritten);
	assertTrue(response.headersWritten);
	assertTrue(response.cookiesWritten);
	assertSame(cookie, response.getCookies().getFirst("ID"));

	assertEquals(3, response.body.size());
	assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
	assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
	assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
}
 
Example #15
Source File: ServletServerHttpResponse.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new Cookie(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.response.addCookie(cookie);
		}
	}
}
 
Example #16
Source File: UndertowServerHttpResponse.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new CookieImpl(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.exchange.getResponseCookies().putIfAbsent(name, cookie);
		}
	}
}
 
Example #17
Source File: VertxClientHttpResponseTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetCookies() {
    ResponseCookie simpleCookie = ResponseCookie.from("key2", "value2")
        .build();
    ResponseCookie complexCookie = ResponseCookie.from("key1", "value1")
        .domain("domain")
        .httpOnly(true)
        .maxAge(1)
        .path("path")
        .secure(true)
        .build();

    given(mockDelegate.cookies()).willReturn(
        Arrays.asList(simpleCookie.toString(), complexCookie.toString()));

    MultiValueMap<String, ResponseCookie> expectedCookies = new LinkedMultiValueMap<>();
    expectedCookies.add(simpleCookie.getName(), simpleCookie);
    expectedCookies.add(complexCookie.getName(), complexCookie);

    VertxClientHttpResponse response = new VertxClientHttpResponse(mockDelegate, Flux.empty());
    MultiValueMap<String, ResponseCookie> actualCookies = response.getCookies();

    assertThat(actualCookies).isEqualTo(expectedCookies);
}
 
Example #18
Source File: CookieWebSessionIdResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cookieInitializer() {
	this.resolver.addCookieInitializer(builder -> builder.domain("example.org"));
	this.resolver.addCookieInitializer(builder -> builder.sameSite("Strict"));
	this.resolver.addCookieInitializer(builder -> builder.secure(false));

	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.org/path").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	this.resolver.setSessionId(exchange, "123");

	MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
	assertEquals(1, cookies.size());
	ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
	assertNotNull(cookie);
	assertEquals("SESSION=123; Path=/; Domain=example.org; HttpOnly; SameSite=Strict", cookie.toString());
}
 
Example #19
Source File: JettyClientHttpResponse.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public MultiValueMap<String, ResponseCookie> getCookies() {
	MultiValueMap<String, ResponseCookie> result = new LinkedMultiValueMap<>();
	List<String> cookieHeader = getHeaders().get(HttpHeaders.SET_COOKIE);
	if (cookieHeader != null) {
		cookieHeader.forEach(header ->
			HttpCookie.parse(header)
					.forEach(cookie -> result.add(cookie.getName(),
							ResponseCookie.from(cookie.getName(), cookie.getValue())
					.domain(cookie.getDomain())
					.path(cookie.getPath())
					.maxAge(cookie.getMaxAge())
					.secure(cookie.getSecure())
					.httpOnly(cookie.isHttpOnly())
					.build()))
		);
	}
	return CollectionUtils.unmodifiableMultiValueMap(result);
}
 
Example #20
Source File: AbstractServerHttpResponse.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void addCookie(ResponseCookie cookie) {
	Assert.notNull(cookie, "ResponseCookie must not be null");

	if (this.state.get() == State.COMMITTED) {
		throw new IllegalStateException("Can't add the cookie " + cookie +
				"because the HTTP response has already been committed");
	}
	else {
		getCookies().add(cookie.getName(), cookie);
	}
}
 
Example #21
Source File: DefaultServerResponseBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public WriterFunctionResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies,
		BiFunction<ServerWebExchange, Context, Mono<Void>> writeFunction) {

	super(statusCode, headers, cookies, Collections.emptyMap());
	Assert.notNull(writeFunction, "BiFunction must not be null");
	this.writeFunction = writeFunction;
}
 
Example #22
Source File: DefaultClientResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public DefaultClientResponseBuilder cookie(String name, String... values) {
	for (String value : values) {
		this.cookies.add(name, ResponseCookie.from(name, value).build());
	}
	return this;
}
 
Example #23
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected AbstractServerResponse(
		int statusCode, HttpHeaders headers, MultiValueMap<String, ResponseCookie> cookies) {

	this.statusCode = statusCode;
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
	this.cookies = CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(cookies));
}
 
Example #24
Source File: DefaultServerResponseBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected AbstractServerResponse(
		int statusCode, HttpHeaders headers, MultiValueMap<String, ResponseCookie> cookies,
		Map<String, Object> hints) {

	this.statusCode = statusCode;
	this.headers = HttpHeaders.readOnlyHttpHeaders(headers);
	this.cookies = CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(cookies));
	this.hints = hints;
}
 
Example #25
Source File: CookieConverter.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
private static ResponseCookie toResponseCookie(java.net.HttpCookie cookie) {
    return ResponseCookie.from(cookie.getName(), cookie.getValue())
        .domain(cookie.getDomain())
        .httpOnly(cookie.isHttpOnly())
        .maxAge(cookie.getMaxAge())
        .path(cookie.getPath())
        .secure(cookie.getSecure())
        .build();
}
 
Example #26
Source File: ArmeriaClientHttpResponse.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public MultiValueMap<String, ResponseCookie> getCookies() {
    final MultiValueMap<String, ResponseCookie> cookies = this.cookies;
    if (cookies != null) {
        return cookies;
    }
    this.cookies = initCookies();
    return this.cookies;
}
 
Example #27
Source File: DefaultRenderingResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
public DefaultRenderingResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies, String name, Map<String, Object> model) {

	super(statusCode, headers, cookies);
	this.name = name;
	this.model = Collections.unmodifiableMap(new LinkedHashMap<>(model));
}
 
Example #28
Source File: DefaultEntityResponseBuilderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void cookies() {
	MultiValueMap<String, ResponseCookie> newCookies = new LinkedMultiValueMap<>();
	newCookies.add("name", ResponseCookie.from("name", "value").build());
	Mono<EntityResponse<String>> result =
			EntityResponse.fromObject("foo").cookies(cookies -> cookies.addAll(newCookies)).build();
	StepVerifier.create(result)
			.expectNextMatches(response -> newCookies.equals(response.cookies()))
			.expectComplete()
			.verify();
}
 
Example #29
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
public BodyInserterResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies,
		BodyInserter<T, ? super ServerHttpResponse> body, Map<String, Object> hints) {

	super(statusCode, headers, cookies);
	Assert.notNull(body, "BodyInserter must not be null");
	this.inserter = body;
	this.hints = hints;
}
 
Example #30
Source File: DefaultEntityResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
public DefaultEntityResponse(int statusCode, HttpHeaders headers,
		MultiValueMap<String, ResponseCookie> cookies, T entity,
		BodyInserter<T, ? super ServerHttpResponse> inserter, Map<String, Object> hints) {

	super(statusCode, headers, cookies);
	this.entity = entity;
	this.inserter = inserter;
	this.hints = hints;
}