Skip to content

Commit ee465bd

Browse files
authored
Merge branch 'spring-projects:main' into main
2 parents e741225 + 7fc5d50 commit ee465bd

File tree

5 files changed

+285
-3
lines changed

5 files changed

+285
-3
lines changed

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

Lines changed: 6 additions & 0 deletions
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 `FormPostServerRedirectStrategy`, for example with `OidcClientInitiatedServerLogoutSuccessHandler.setRedirectStrategy(new ServerFormPostRedirectStrategy())`.
130+
====
131+
126132
[[configure-provider-initiated-oidc-logout]]
127133
== OpenID Connect 1.0 Back-Channel Logout
128134

oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandler.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2024 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -51,7 +51,7 @@
5151
*/
5252
public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogoutSuccessHandler {
5353

54-
private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
54+
private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
5555

5656
private final RedirectServerLogoutSuccessHandler serverLogoutSuccessHandler = new RedirectServerLogoutSuccessHandler();
5757

@@ -199,6 +199,17 @@ public void setRedirectUriResolver(Converter<RedirectUriParameters, Mono<String>
199199
this.redirectUriResolver = redirectUriResolver;
200200
}
201201

202+
/**
203+
* Set the {@link ServerRedirectStrategy} to use, default
204+
* {@link DefaultServerRedirectStrategy}
205+
* @param redirectStrategy {@link ServerRedirectStrategy}
206+
* @since 6.5
207+
*/
208+
public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) {
209+
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
210+
this.redirectStrategy = redirectStrategy;
211+
}
212+
202213
/**
203214
* Parameters, required for redirect URI resolving.
204215
*

oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandlerTests.java

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2024 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -37,14 +37,18 @@
3737
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
3838
import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
3939
import org.springframework.security.oauth2.core.user.TestOAuth2Users;
40+
import org.springframework.security.web.server.ServerRedirectStrategy;
4041
import org.springframework.security.web.server.WebFilterExchange;
4142
import org.springframework.web.server.ServerWebExchange;
4243
import org.springframework.web.server.WebFilterChain;
4344

4445
import static org.assertj.core.api.Assertions.assertThat;
4546
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
47+
import static org.mockito.ArgumentMatchers.any;
4648
import static org.mockito.BDDMockito.given;
4749
import static org.mockito.Mockito.mock;
50+
import static org.mockito.Mockito.times;
51+
import static org.mockito.Mockito.verify;
4852

4953
/**
5054
* Tests for {@link OidcClientInitiatedServerLogoutSuccessHandler}
@@ -219,6 +223,27 @@ public void logoutWhenCustomRedirectUriResolverSetThenRedirects() {
219223
assertThat(redirectedUrl(this.exchange)).isEqualTo("https://test.com");
220224
}
221225

226+
@Test
227+
public void setRedirectStrategyWhenGivenNullThenThrowsException() {
228+
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setRedirectStrategy(null));
229+
}
230+
231+
@Test
232+
public void logoutWhenCustomRedirectStrategySetThenCustomRedirectStrategyUsed() {
233+
ServerRedirectStrategy redirectStrategy = mock(ServerRedirectStrategy.class);
234+
given(redirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
235+
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
236+
AuthorityUtils.NO_AUTHORITIES, this.registration.getRegistrationId());
237+
WebFilterExchange filterExchange = new WebFilterExchange(this.exchange, this.chain);
238+
given(this.exchange.getRequest())
239+
.willReturn(MockServerHttpRequest.get("/").queryParam("location", "https://test.com").build());
240+
this.handler.setRedirectStrategy(redirectStrategy);
241+
242+
this.handler.onLogoutSuccess(filterExchange, token).block();
243+
244+
verify(redirectStrategy, times(1)).sendRedirect(any(), any());
245+
}
246+
222247
private String redirectedUrl(ServerWebExchange exchange) {
223248
return exchange.getResponse().getHeaders().getFirst("Location");
224249
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
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.core.io.buffer.DataBufferUtils;
30+
import org.springframework.http.HttpStatus;
31+
import org.springframework.http.MediaType;
32+
import org.springframework.http.server.reactive.ServerHttpResponse;
33+
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
34+
import org.springframework.security.crypto.keygen.StringKeyGenerator;
35+
import org.springframework.web.server.ServerWebExchange;
36+
import org.springframework.web.util.HtmlUtils;
37+
import org.springframework.web.util.UriComponentsBuilder;
38+
39+
/**
40+
* Redirect using an auto-submitting HTML form using the POST method. All query params
41+
* provided in the URL are changed to inputs in the form so they are submitted as POST
42+
* data instead of query string data.
43+
*
44+
* @author Max Batischev
45+
* @author Steve Riesenberg
46+
* @since 6.5
47+
*/
48+
public final class FormPostServerRedirectStrategy implements ServerRedirectStrategy {
49+
50+
private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy";
51+
52+
private static final String REDIRECT_PAGE_TEMPLATE = """
53+
<!DOCTYPE html>
54+
<html lang="en">
55+
<head>
56+
<meta charset="utf-8">
57+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
58+
<meta name="description" content="">
59+
<meta name="author" content="">
60+
<title>Redirect</title>
61+
</head>
62+
<body>
63+
<form id="redirect-form" method="POST" action="{{action}}">
64+
{{params}}
65+
<noscript>
66+
<p>JavaScript is not enabled for this page.</p>
67+
<button type="submit">Click to continue</button>
68+
</noscript>
69+
</form>
70+
<script nonce="{{nonce}}">
71+
document.getElementById("redirect-form").submit();
72+
</script>
73+
</body>
74+
</html>
75+
""";
76+
77+
private static final String HIDDEN_INPUT_TEMPLATE = """
78+
<input name="{{name}}" type="hidden" value="{{value}}" />
79+
""";
80+
81+
private static final StringKeyGenerator DEFAULT_NONCE_GENERATOR = new Base64StringKeyGenerator(
82+
Base64.getUrlEncoder().withoutPadding(), 96);
83+
84+
@Override
85+
public Mono<Void> sendRedirect(ServerWebExchange exchange, URI location) {
86+
final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(location);
87+
88+
final StringBuilder hiddenInputsHtmlBuilder = new StringBuilder();
89+
for (final Map.Entry<String, List<String>> entry : uriComponentsBuilder.build().getQueryParams().entrySet()) {
90+
final String name = entry.getKey();
91+
for (final String value : entry.getValue()) {
92+
// @formatter:off
93+
final String hiddenInput = HIDDEN_INPUT_TEMPLATE
94+
.replace("{{name}}", HtmlUtils.htmlEscape(name))
95+
.replace("{{value}}", HtmlUtils.htmlEscape(value));
96+
// @formatter:on
97+
hiddenInputsHtmlBuilder.append(hiddenInput.trim());
98+
}
99+
}
100+
101+
// Create the script-src policy directive for the Content-Security-Policy header
102+
final String nonce = DEFAULT_NONCE_GENERATOR.generateKey();
103+
final String policyDirective = "script-src 'nonce-%s'".formatted(nonce);
104+
105+
// @formatter:off
106+
final String html = REDIRECT_PAGE_TEMPLATE
107+
// Clear the query string as we don't want that to be part of the form action URL
108+
.replace("{{action}}", HtmlUtils.htmlEscape(uriComponentsBuilder.query(null).build().toUriString()))
109+
.replace("{{params}}", hiddenInputsHtmlBuilder.toString())
110+
.replace("{{nonce}}", HtmlUtils.htmlEscape(nonce));
111+
// @formatter:on
112+
113+
final ServerHttpResponse response = exchange.getResponse();
114+
response.setStatusCode(HttpStatus.OK);
115+
response.getHeaders().setContentType(MediaType.TEXT_HTML);
116+
response.getHeaders().set(CONTENT_SECURITY_POLICY_HEADER, policyDirective);
117+
118+
final DataBufferFactory bufferFactory = response.bufferFactory();
119+
final DataBuffer buffer = bufferFactory.wrap(html.getBytes(StandardCharsets.UTF_8));
120+
return response.writeWith(Mono.just(buffer)).doOnError((error) -> DataBufferUtils.release(buffer));
121+
}
122+
123+
}
Lines changed: 117 additions & 0 deletions
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 FormPostServerRedirectStrategy}.
34+
*
35+
* @author Max Batischev
36+
*/
37+
public class FormPostServerRedirectStrategyTests {
38+
39+
private static final String POLICY_DIRECTIVE_PATTERN = "script-src 'nonce-(.+)'";
40+
41+
private final ServerRedirectStrategy redirectStrategy = new FormPostServerRedirectStrategy();
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 redirectWhenLocationAbsoluteUriWithQueryParamsIsPresentThenRedirect() {
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().getFirst("Content-Security-Policy");
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)