Custom ServerHttpHeadersWriter to HeaderSpec

Add the ability to have a custom ServerHttpHeadersWriter to HeaderSpec
Fixes gh-7636
This commit is contained in:
Ankur Pathak 2020-02-27 15:09:11 +05:30 committed by Rob Winch
parent bb72206eef
commit 480c5bc87e
2 changed files with 32 additions and 0 deletions

View File

@ -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

View File

@ -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);