ソースを参照

Custom ServerHttpHeadersWriter to HeaderSpec

Add the ability to have a custom ServerHttpHeadersWriter to HeaderSpec
Fixes gh-7636
Ankur Pathak 5 年 前
コミット
480c5bc87e

+ 14 - 0
config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java

@@ -3284,6 +3284,20 @@ public class ServerHttpSecurity {
 			return this;
 		}
 
+		/**
+		 * Configures custom headers writer
+		 *
+		 * @param serverHttpHeadersWriter the {@link ServerHttpHeadersWriter} to provide custom headers writer
+		 * @return the {@link HeaderSpec} to customize
+		 * @since 5.3.0
+		 * @author Ankur Pathak
+		 */
+		public HeaderSpec writer(ServerHttpHeadersWriter serverHttpHeadersWriter) {
+			Assert.notNull(serverHttpHeadersWriter, () -> "serverHttpHeadersWriter cannot be null");
+			this.writers.add(serverHttpHeadersWriter);
+			return this;
+		}
+
 		/**
 		 * Configures the Strict Transport Security response headers
 		 * @return the {@link HstsSpec} to configure

+ 18 - 0
config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java

@@ -24,6 +24,7 @@ import java.util.Set;
 
 import org.junit.Before;
 import org.junit.Test;
+import reactor.core.publisher.Mono;
 
 import org.springframework.http.HttpHeaders;
 import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
@@ -46,9 +47,12 @@ import static org.springframework.security.config.Customizer.withDefaults;
  *
  * @author Rob Winch
  * @author Vedran Pavic
+ * @author Ankur Pathak
  * @since 5.0
  */
 public class HeaderSpecTests {
+	private final static String CUSTOM_HEADER = "CUSTOM-HEADER";
+	private final static String CUSTOM_VALUE = "CUSTOM-VALUE";
 
 	private ServerHttpSecurity http = ServerHttpSecurity.http();
 
@@ -387,6 +391,20 @@ public class HeaderSpecTests {
 		assertHeaders();
 	}
 
+	@Test
+	public void headersWhenCustomHeadersWriter() {
+		this.expectedHeaders.add(CUSTOM_HEADER, CUSTOM_VALUE);
+		this.http.headers(headers -> headers.writer(exchange -> {
+			return Mono.just(exchange)
+					.doOnNext(it -> {
+						it.getResponse().getHeaders().add(CUSTOM_HEADER, CUSTOM_VALUE);
+					}).then();
+
+		}));
+
+		assertHeaders();
+	}
+
 	private void expectHeaderNamesNotPresent(String... headerNames) {
 		for (String headerName : headerNames) {
 			this.expectedHeaders.remove(headerName);