Skip to content

Commit 4bf5509

Browse files
Add Support ServerFormPostRedirectStrategy
Closes gh-16542 Signed-off-by: Max Batischev <mblancer@mail.ru>
1 parent 8e2a4bf commit 4bf5509

File tree

3 files changed

+247
-0
lines changed

3 files changed

+247
-0
lines changed

docs/modules/ROOT/pages/reactive/oauth2/login/logout.adoc

+6
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,12 @@ class OAuth2LoginSecurityConfig {
123123
If used, the application's base URL, such as `https://app.example.org`, replaces it at request time.
124124
====
125125

126+
[NOTE]
127+
====
128+
By default, `OidcClientInitiatedServerLogoutSuccessHandler` redirects to the logout URL using a standard HTTP redirect with the `GET` method.
129+
To perform the logout using a `POST` request, set the redirect strategy to `ServerFormPostRedirectStrategy`, for example with `OidcClientInitiatedServerLogoutSuccessHandler.setRedirectStrategy(new ServerFormPostRedirectStrategy())`.
130+
====
131+
126132
[[configure-provider-initiated-oidc-logout]]
127133
== OpenID Connect 1.0 Back-Channel Logout
128134

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* Copyright 2002-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.web.server;
18+
19+
import java.net.URI;
20+
import java.nio.charset.StandardCharsets;
21+
import java.util.Base64;
22+
import java.util.List;
23+
import java.util.Map;
24+
25+
import reactor.core.publisher.Mono;
26+
27+
import org.springframework.core.io.buffer.DataBuffer;
28+
import org.springframework.core.io.buffer.DataBufferFactory;
29+
import org.springframework.http.HttpStatus;
30+
import org.springframework.http.MediaType;
31+
import org.springframework.http.server.reactive.ServerHttpResponse;
32+
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
33+
import org.springframework.security.crypto.keygen.StringKeyGenerator;
34+
import org.springframework.web.server.ServerWebExchange;
35+
import org.springframework.web.util.HtmlUtils;
36+
import org.springframework.web.util.UriComponentsBuilder;
37+
38+
/**
39+
* Redirect using an auto-submitting HTML form using the POST method. All query params
40+
* provided in the URL are changed to inputs in the form so they are submitted as POST
41+
* data instead of query string data.
42+
*
43+
* @author Max Batischev
44+
* @since 6.5
45+
*/
46+
public final class ServerFormPostRedirectStrategy implements ServerRedirectStrategy {
47+
48+
private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy";
49+
50+
private static final StringKeyGenerator DEFAULT_NONCE_GENERATOR = new Base64StringKeyGenerator(
51+
Base64.getUrlEncoder().withoutPadding(), 96);
52+
53+
private static final String REDIRECT_PAGE_TEMPLATE = """
54+
<!DOCTYPE html>
55+
<html lang="en">
56+
<head>
57+
<meta charset="utf-8">
58+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
59+
<meta name="description" content="">
60+
<meta name="author" content="">
61+
<title>Redirect</title>
62+
</head>
63+
<body>
64+
<form id="redirect-form" method="POST" action="{{action}}">
65+
{{params}}
66+
<noscript>
67+
<p>JavaScript is not enabled for this page.</p>
68+
<button type="submit">Click to continue</button>
69+
</noscript>
70+
</form>
71+
<script nonce="{{nonce}}">
72+
document.getElementById("redirect-form").submit();
73+
</script>
74+
</body>
75+
</html>
76+
""";
77+
78+
private static final String HIDDEN_INPUT_TEMPLATE = """
79+
<input name="{{name}}" type="hidden" value="{{value}}" />
80+
""";
81+
82+
@Override
83+
public Mono<Void> sendRedirect(ServerWebExchange exchange, URI location) {
84+
String nonce = DEFAULT_NONCE_GENERATOR.generateKey();
85+
String policyDirective = "script-src 'nonce-%s'".formatted(nonce);
86+
87+
ServerHttpResponse response = exchange.getResponse();
88+
response.setStatusCode(HttpStatus.OK);
89+
response.getHeaders().setContentType(MediaType.TEXT_HTML);
90+
response.getHeaders().add(CONTENT_SECURITY_POLICY_HEADER, policyDirective);
91+
return response.writeWith(createBuffer(exchange, location, nonce));
92+
}
93+
94+
private Mono<DataBuffer> createBuffer(ServerWebExchange exchange, URI location, String nonce) {
95+
byte[] bytes = createPage(location, nonce);
96+
DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
97+
return Mono.just(bufferFactory.wrap(bytes));
98+
}
99+
100+
private byte[] createPage(URI location, String nonce) {
101+
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(location);
102+
103+
StringBuilder hiddenInputsHtmlBuilder = new StringBuilder();
104+
for (final Map.Entry<String, List<String>> entry : uriComponentsBuilder.build().getQueryParams().entrySet()) {
105+
final String name = entry.getKey();
106+
for (final String value : entry.getValue()) {
107+
// @formatter:off
108+
final String hiddenInput = HIDDEN_INPUT_TEMPLATE
109+
.replace("{{name}}", HtmlUtils.htmlEscape(name))
110+
.replace("{{value}}", HtmlUtils.htmlEscape(value));
111+
// @formatter:on
112+
hiddenInputsHtmlBuilder.append(hiddenInput.trim());
113+
}
114+
}
115+
// @formatter:off
116+
return REDIRECT_PAGE_TEMPLATE
117+
.replace("{{action}}", HtmlUtils.htmlEscape(uriComponentsBuilder.query(null).build().toUriString()))
118+
.replace("{{params}}", hiddenInputsHtmlBuilder.toString())
119+
.replace("{{nonce}}", HtmlUtils.htmlEscape(nonce))
120+
.getBytes(StandardCharsets.UTF_8);
121+
// @formatter:on
122+
}
123+
124+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
/*
2+
* Copyright 2002-2025 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.web.server;
18+
19+
import java.net.URI;
20+
21+
import org.assertj.core.api.ThrowingConsumer;
22+
import org.junit.jupiter.api.Test;
23+
24+
import org.springframework.http.HttpStatus;
25+
import org.springframework.http.MediaType;
26+
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
27+
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
28+
import org.springframework.mock.web.server.MockServerWebExchange;
29+
30+
import static org.assertj.core.api.Assertions.assertThat;
31+
32+
/**
33+
* Tests for {@link ServerFormPostRedirectStrategy}.
34+
*
35+
* @author Max Batischev
36+
*/
37+
public class ServerFormPostRedirectStrategyTests {
38+
39+
private static final String POLICY_DIRECTIVE_PATTERN = "script-src 'nonce-(.+)'";
40+
41+
private final ServerRedirectStrategy redirectStrategy = new ServerFormPostRedirectStrategy();
42+
43+
private final MockServerHttpRequest request = MockServerHttpRequest.get("https://localhost").build();
44+
45+
private final MockServerWebExchange webExchange = MockServerWebExchange.from(this.request);
46+
47+
@Test
48+
public void redirectWhetLocationAbsoluteUriIsPresentThenRedirect() {
49+
this.redirectStrategy.sendRedirect(this.webExchange, URI.create("https://example.com")).block();
50+
51+
MockServerHttpResponse response = this.webExchange.getResponse();
52+
assertThat(response.getBodyAsString().block()).contains("action=\"https://example.com\"");
53+
assertThat(this.webExchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK);
54+
assertThat(this.webExchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
55+
assertThat(this.webExchange.getResponse()).satisfies(hasScriptSrcNonce());
56+
}
57+
58+
@Test
59+
public void redirectWhetLocationRootRelativeUriIsPresentThenRedirect() {
60+
this.redirectStrategy.sendRedirect(this.webExchange, URI.create("/test")).block();
61+
62+
MockServerHttpResponse response = this.webExchange.getResponse();
63+
assertThat(response.getBodyAsString().block()).contains("action=\"/test\"");
64+
assertThat(this.webExchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK);
65+
assertThat(this.webExchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
66+
assertThat(this.webExchange.getResponse()).satisfies(hasScriptSrcNonce());
67+
}
68+
69+
@Test
70+
public void redirectWhetLocationRelativeUriIsPresentThenRedirect() {
71+
this.redirectStrategy.sendRedirect(this.webExchange, URI.create("test")).block();
72+
73+
MockServerHttpResponse response = this.webExchange.getResponse();
74+
assertThat(response.getBodyAsString().block()).contains("action=\"test\"");
75+
assertThat(this.webExchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK);
76+
assertThat(this.webExchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
77+
assertThat(this.webExchange.getResponse()).satisfies(hasScriptSrcNonce());
78+
}
79+
80+
@Test
81+
public void redirectWhenLocationAbsoluteUriWithFragmentIsPresentThenRedirect() {
82+
this.redirectStrategy.sendRedirect(this.webExchange, URI.create("https://example.com/path#fragment")).block();
83+
84+
MockServerHttpResponse response = this.webExchange.getResponse();
85+
assertThat(response.getBodyAsString().block()).contains("action=\"https://example.com/path#fragment\"");
86+
assertThat(this.webExchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK);
87+
assertThat(this.webExchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
88+
assertThat(this.webExchange.getResponse()).satisfies(hasScriptSrcNonce());
89+
}
90+
91+
@Test
92+
public void redirectWhenLocationAbsoluteUilWithQueryParamsIsPresentThenRedirect() {
93+
this.redirectStrategy
94+
.sendRedirect(this.webExchange, URI.create("https://example.com/path?param1=one&param2=two#fragment"))
95+
.block();
96+
97+
MockServerHttpResponse response = this.webExchange.getResponse();
98+
String content = response.getBodyAsString().block();
99+
assertThat(this.webExchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.OK);
100+
assertThat(this.webExchange.getResponse().getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
101+
assertThat(content).contains("action=\"https://example.com/path#fragment\"");
102+
assertThat(content).contains("<input name=\"param1\" type=\"hidden\" value=\"one\" />");
103+
assertThat(content).contains("<input name=\"param2\" type=\"hidden\" value=\"two\" />");
104+
}
105+
106+
private ThrowingConsumer<MockServerHttpResponse> hasScriptSrcNonce() {
107+
return (response) -> {
108+
final String policyDirective = response.getHeaders().get("Content-Security-Policy").get(0);
109+
assertThat(policyDirective).isNotEmpty();
110+
assertThat(policyDirective).matches(POLICY_DIRECTIVE_PATTERN);
111+
112+
final String nonce = policyDirective.replaceFirst(POLICY_DIRECTIVE_PATTERN, "$1");
113+
assertThat(response.getBodyAsString().block()).contains("<script nonce=\"%s\">".formatted(nonce));
114+
};
115+
}
116+
117+
}

0 commit comments

Comments
 (0)