Use ServerHttpSecurity Lambda DSL in Tests

Issue gh-13067
This commit is contained in:
Josh Cummings 2025-06-20 10:08:17 -06:00
parent 1a7b1fcc7c
commit 9fcfacf283
No known key found for this signature in database
GPG Key ID: 869B37A20E876129
14 changed files with 325 additions and 381 deletions

View File

@ -377,9 +377,7 @@ public class EnableWebFluxSecurityTests {
@Bean @Bean
SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) { SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**"))
.authorizeExchange() .authorizeExchange((exchange) -> exchange.anyExchange().denyAll());
.anyExchange()
.denyAll();
return http.build(); return http.build();
} }

View File

@ -35,13 +35,11 @@ public class AuthorizeExchangeSpecTests {
@Test @Test
public void antMatchersWhenMethodAndPatternsThenDiscriminatesByMethod() { public void antMatchersWhenMethodAndPatternsThenDiscriminatesByMethod() {
this.http.csrf() this.http.csrf((csrf) -> csrf.disable())
.disable() .authorizeExchange((authorize) -> authorize.pathMatchers(HttpMethod.POST, "/a", "/b")
.authorizeExchange() .denyAll()
.pathMatchers(HttpMethod.POST, "/a", "/b") .anyExchange()
.denyAll() .permitAll());
.anyExchange()
.permitAll();
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
client.get() client.get()
@ -65,7 +63,8 @@ public class AuthorizeExchangeSpecTests {
@Test @Test
public void antMatchersWhenPatternsThenAnyMethod() { public void antMatchersWhenPatternsThenAnyMethod() {
this.http.csrf().disable().authorizeExchange().pathMatchers("/a", "/b").denyAll().anyExchange().permitAll(); this.http.csrf((csrf) -> csrf.disable())
.authorizeExchange((authorize) -> authorize.pathMatchers("/a", "/b").denyAll().anyExchange().permitAll());
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
client.get() client.get()
@ -114,25 +113,25 @@ public class AuthorizeExchangeSpecTests {
@Test @Test
public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() { public void antMatchersWhenNoAccessAndAnotherMatcherThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete"); this.http.authorizeExchange((exchange) -> exchange.pathMatchers("/incomplete"));
assertThatIllegalStateException() assertThatIllegalStateException()
.isThrownBy(() -> this.http.authorizeExchange().pathMatchers("/throws-exception")); .isThrownBy(() -> this.http.authorizeExchange((exchange) -> exchange.pathMatchers("/throws-exception")));
} }
@Test @Test
public void anyExchangeWhenFollowedByMatcherThenThrowsException() { public void anyExchangeWhenFollowedByMatcherThenThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> assertThatIllegalStateException().isThrownBy(() ->
// @formatter:off // @formatter:off
this.http.authorizeExchange() this.http.authorizeExchange((exchange) -> exchange
.anyExchange().denyAll() .anyExchange().denyAll()
.pathMatchers("/never-reached") .pathMatchers("/never-reached"))
// @formatter:on // @formatter:on
); );
} }
@Test @Test
public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() { public void buildWhenMatcherDefinedWithNoAccessThenThrowsException() {
this.http.authorizeExchange().pathMatchers("/incomplete"); this.http.authorizeExchange((exchange) -> exchange.pathMatchers("/incomplete"));
assertThatIllegalStateException().isThrownBy(this.http::build); assertThatIllegalStateException().isThrownBy(this.http::build);
} }

View File

@ -73,7 +73,7 @@ public class CorsSpecTests {
@Test @Test
public void corsWhenEnabledThenAccessControlAllowOriginAndSecurityHeaders() { public void corsWhenEnabledThenAccessControlAllowOriginAndSecurityHeaders() {
givenGetCorsConfigurationWillReturnWildcard(); givenGetCorsConfigurationWillReturnWildcard();
this.http.cors().configurationSource(this.source); this.http.cors((cors) -> cors.configurationSource(this.source));
this.expectedHeaders.set("Access-Control-Allow-Origin", "*"); this.expectedHeaders.set("Access-Control-Allow-Origin", "*");
this.expectedHeaders.set("X-Frame-Options", "DENY"); this.expectedHeaders.set("X-Frame-Options", "DENY");
assertHeaders(); assertHeaders();

View File

@ -19,6 +19,7 @@ package org.springframework.security.config.web.server;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder; import org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.SecurityWebFilterChain;
@ -42,12 +43,11 @@ public class ExceptionHandlingSpecTests {
public void defaultAuthenticationEntryPoint() { public void defaultAuthenticationEntryPoint() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.csrf().disable() .csrf((csrf) -> csrf.disable())
.authorizeExchange() .authorizeExchange((authorize) -> authorize
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .exceptionHandling(withDefaults())
.exceptionHandling().and() .build();
.build();
WebTestClient client = WebTestClientBuilder WebTestClient client = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -83,14 +83,12 @@ public class ExceptionHandlingSpecTests {
public void customAuthenticationEntryPoint() { public void customAuthenticationEntryPoint() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.csrf().disable() .csrf((csrf) -> csrf.disable())
.authorizeExchange() .authorizeExchange((authorize) -> authorize
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .exceptionHandling((handling) -> handling
.exceptionHandling() .authenticationEntryPoint(redirectServerAuthenticationEntryPoint("/auth")))
.authenticationEntryPoint(redirectServerAuthenticationEntryPoint("/auth")) .build();
.and()
.build();
WebTestClient client = WebTestClientBuilder WebTestClient client = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -128,13 +126,12 @@ public class ExceptionHandlingSpecTests {
public void defaultAccessDeniedHandler() { public void defaultAccessDeniedHandler() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.csrf().disable() .csrf((csrf) -> csrf.disable())
.httpBasic().and() .httpBasic(Customizer.withDefaults())
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasRole("ADMIN") .anyExchange().hasRole("ADMIN"))
.and() .exceptionHandling(withDefaults())
.exceptionHandling().and() .build();
.build();
WebTestClient client = WebTestClientBuilder WebTestClient client = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -171,15 +168,13 @@ public class ExceptionHandlingSpecTests {
public void customAccessDeniedHandler() { public void customAccessDeniedHandler() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.csrf().disable() .csrf((csrf) -> csrf.disable())
.httpBasic().and() .httpBasic(Customizer.withDefaults())
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasRole("ADMIN") .anyExchange().hasRole("ADMIN"))
.and() .exceptionHandling((handling) -> handling
.exceptionHandling() .accessDeniedHandler(httpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST)))
.accessDeniedHandler(httpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST)) .build();
.and()
.build();
WebTestClient client = WebTestClientBuilder WebTestClient client = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();

View File

@ -69,12 +69,10 @@ public class FormLoginTests {
public void defaultLoginPage() { public void defaultLoginPage() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin() .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -129,14 +127,12 @@ public class FormLoginTests {
public void customLoginPage() { public void customLoginPage() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.pathMatchers("/login").permitAll() .pathMatchers("/login").permitAll()
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin((login) -> login
.formLogin() .loginPage("/login"))
.loginPage("/login") .build();
.and()
.build();
WebTestClient webTestClient = WebTestClient WebTestClient webTestClient = WebTestClient
.bindToController(new CustomLoginPageController(), new WebTestClientBuilder.Http200RestController()) .bindToController(new CustomLoginPageController(), new WebTestClientBuilder.Http200RestController())
.webFilter(new WebFilterChainProxy(securityWebFilter)) .webFilter(new WebFilterChainProxy(securityWebFilter))
@ -189,14 +185,12 @@ public class FormLoginTests {
public void formLoginWhenCustomAuthenticationFailureHandlerThenUsed() { public void formLoginWhenCustomAuthenticationFailureHandlerThenUsed() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.pathMatchers("/login", "/failure").permitAll() .pathMatchers("/login", "/failure").permitAll()
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin((login) -> login
.formLogin() .authenticationFailureHandler(new RedirectServerAuthenticationFailureHandler("/failure")))
.authenticationFailureHandler(new RedirectServerAuthenticationFailureHandler("/failure")) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -218,14 +212,12 @@ public class FormLoginTests {
public void formLoginWhenCustomRequiresAuthenticationMatcherThenUsed() { public void formLoginWhenCustomRequiresAuthenticationMatcherThenUsed() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.pathMatchers("/login", "/sign-in").permitAll() .pathMatchers("/login", "/sign-in").permitAll()
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin((login) -> login
.formLogin() .requiresAuthenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/sign-in")))
.requiresAuthenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/sign-in")) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -241,13 +233,11 @@ public class FormLoginTests {
public void authenticationSuccess() { public void authenticationSuccess() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin((login) -> login
.formLogin() .authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/custom")))
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/custom")) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -275,11 +265,10 @@ public class FormLoginTests {
.willReturn(Mono.just(new TestingAuthenticationToken("user", "password", "ROLE_USER", "ROLE_ADMIN"))); .willReturn(Mono.just(new TestingAuthenticationToken("user", "password", "ROLE_USER", "ROLE_ADMIN")));
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authenticationManager(defaultAuthenticationManager) .authenticationManager(defaultAuthenticationManager)
.formLogin() .formLogin((login) -> login
.authenticationManager(customAuthenticationManager) .authenticationManager(customAuthenticationManager))
.and() .build();
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -309,14 +298,12 @@ public class FormLoginTests {
given(formLoginSecContextRepository.load(any())).willReturn(authentication(token)); given(formLoginSecContextRepository.load(any())).willReturn(authentication(token));
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .securityContextRepository(defaultSecContextRepository)
.securityContextRepository(defaultSecContextRepository) .formLogin((login) -> login
.formLogin() .securityContextRepository(formLoginSecContextRepository))
.securityContextRepository(formLoginSecContextRepository) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();

View File

@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.security.config.Customizer;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter; import org.springframework.security.web.server.header.ContentSecurityPolicyServerHttpHeadersWriter;
import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter; import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter;
@ -79,7 +80,7 @@ public class HeaderSpecTests {
@Test @Test
public void headersWhenDisableThenNoSecurityHeaders() { public void headersWhenDisableThenNoSecurityHeaders() {
new HashSet<>(this.expectedHeaders.headerNames()).forEach(this::expectHeaderNamesNotPresent); new HashSet<>(this.expectedHeaders.headerNames()).forEach(this::expectHeaderNamesNotPresent);
this.http.headers().disable(); this.http.headers((headers) -> headers.disable());
assertHeaders(); assertHeaders();
} }
@ -92,13 +93,13 @@ public class HeaderSpecTests {
@Test @Test
public void headersWhenDisableAndInvokedExplicitlyThenDefautsUsed() { public void headersWhenDisableAndInvokedExplicitlyThenDefautsUsed() {
this.http.headers().disable().headers(); this.http.headers((headers) -> headers.disable().headers(Customizer.withDefaults()));
assertHeaders(); assertHeaders();
} }
@Test @Test
public void headersWhenDefaultsThenAllDefaultsWritten() { public void headersWhenDefaultsThenAllDefaultsWritten() {
this.http.headers(); this.http.headers(withDefaults());
assertHeaders(); assertHeaders();
} }
@ -111,7 +112,7 @@ public class HeaderSpecTests {
@Test @Test
public void headersWhenCacheDisableThenCacheNotWritten() { public void headersWhenCacheDisableThenCacheNotWritten() {
expectHeaderNamesNotPresent(HttpHeaders.CACHE_CONTROL, HttpHeaders.PRAGMA, HttpHeaders.EXPIRES); expectHeaderNamesNotPresent(HttpHeaders.CACHE_CONTROL, HttpHeaders.PRAGMA, HttpHeaders.EXPIRES);
this.http.headers().cache().disable(); this.http.headers((headers) -> headers.cache((cache) -> cache.disable()));
assertHeaders(); assertHeaders();
} }
@ -129,7 +130,7 @@ public class HeaderSpecTests {
@Test @Test
public void headersWhenContentOptionsDisableThenContentTypeOptionsNotWritten() { public void headersWhenContentOptionsDisableThenContentTypeOptionsNotWritten() {
expectHeaderNamesNotPresent(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS); expectHeaderNamesNotPresent(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS);
this.http.headers().contentTypeOptions().disable(); this.http.headers((headers) -> headers.contentTypeOptions((options) -> options.disable()));
assertHeaders(); assertHeaders();
} }
@ -148,7 +149,7 @@ public class HeaderSpecTests {
@Test @Test
public void headersWhenHstsDisableThenHstsNotWritten() { public void headersWhenHstsDisableThenHstsNotWritten() {
expectHeaderNamesNotPresent(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY); expectHeaderNamesNotPresent(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
this.http.headers().hsts().disable(); this.http.headers((headers) -> headers.hsts((hsts) -> hsts.disable()));
assertHeaders(); assertHeaders();
} }
@ -169,10 +170,10 @@ public class HeaderSpecTests {
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
"max-age=60"); "max-age=60");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.hsts() .hsts((hsts) -> hsts
.maxAge(Duration.ofSeconds(60)) .maxAge(Duration.ofSeconds(60))
.includeSubdomains(false); .includeSubdomains(false)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -200,10 +201,10 @@ public class HeaderSpecTests {
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY, this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
"max-age=60 ; includeSubDomains ; preload"); "max-age=60 ; includeSubDomains ; preload");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.hsts() .hsts((hsts) -> hsts
.maxAge(Duration.ofSeconds(60)) .maxAge(Duration.ofSeconds(60))
.preload(true); .preload(true)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -228,8 +229,8 @@ public class HeaderSpecTests {
public void headersWhenFrameOptionsDisableThenFrameOptionsNotWritten() { public void headersWhenFrameOptionsDisableThenFrameOptionsNotWritten() {
expectHeaderNamesNotPresent(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS); expectHeaderNamesNotPresent(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS);
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.frameOptions().disable(); .frameOptions((options) -> options.disable()));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -251,9 +252,9 @@ public class HeaderSpecTests {
public void headersWhenFrameOptionsModeThenFrameOptionsCustomMode() { public void headersWhenFrameOptionsModeThenFrameOptionsCustomMode() {
this.expectedHeaders.set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN"); this.expectedHeaders.set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.frameOptions() .frameOptions((frameOptions) -> frameOptions
.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN); .mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -275,8 +276,8 @@ public class HeaderSpecTests {
public void headersWhenXssProtectionDisableThenXssProtectionNotWritten() { public void headersWhenXssProtectionDisableThenXssProtectionNotWritten() {
expectHeaderNamesNotPresent("X-Xss-Protection"); expectHeaderNamesNotPresent("X-Xss-Protection");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.xssProtection().disable(); .xssProtection((xss) -> xss.disable()));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -298,9 +299,9 @@ public class HeaderSpecTests {
public void headersWhenXssProtectionValueDisabledThenXssProtectionWritten() { public void headersWhenXssProtectionValueDisabledThenXssProtectionWritten() {
this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "0"); this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "0");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.xssProtection() .xssProtection((xss) -> xss
.headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED); .headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -309,9 +310,9 @@ public class HeaderSpecTests {
public void headersWhenXssProtectionValueEnabledThenXssProtectionWritten() { public void headersWhenXssProtectionValueEnabledThenXssProtectionWritten() {
this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1"); this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.xssProtection() .xssProtection((xss) -> xss
.headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED); .headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -320,9 +321,9 @@ public class HeaderSpecTests {
public void headersWhenXssProtectionValueEnabledModeBlockThenXssProtectionWritten() { public void headersWhenXssProtectionValueEnabledModeBlockThenXssProtectionWritten() {
this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1; mode=block"); this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "1; mode=block");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.xssProtection() .xssProtection((xss) -> xss
.headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED_MODE_BLOCK); .headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED_MODE_BLOCK)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -331,10 +332,10 @@ public class HeaderSpecTests {
public void headersWhenXssProtectionValueDisabledInLambdaThenXssProtectionWritten() { public void headersWhenXssProtectionValueDisabledInLambdaThenXssProtectionWritten() {
this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "0"); this.expectedHeaders.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, "0");
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.xssProtection((xssProtection) -> .xssProtection((xssProtection) ->
xssProtection.headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED) xssProtection.headerValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED)
); ));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -344,8 +345,8 @@ public class HeaderSpecTests {
String policyDirectives = "Feature-Policy"; String policyDirectives = "Feature-Policy";
this.expectedHeaders.add(FeaturePolicyServerHttpHeadersWriter.FEATURE_POLICY, policyDirectives); this.expectedHeaders.add(FeaturePolicyServerHttpHeadersWriter.FEATURE_POLICY, policyDirectives);
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.featurePolicy(policyDirectives); .featurePolicy(policyDirectives));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -356,8 +357,8 @@ public class HeaderSpecTests {
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY, this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
policyDirectives); policyDirectives);
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.contentSecurityPolicy(policyDirectives); .contentSecurityPolicy((csp) -> csp.policyDirectives(policyDirectives)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -395,8 +396,8 @@ public class HeaderSpecTests {
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY, this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
ReferrerPolicy.NO_REFERRER.getPolicy()); ReferrerPolicy.NO_REFERRER.getPolicy());
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.referrerPolicy(); .referrerPolicy(Customizer.withDefaults()));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -419,8 +420,8 @@ public class HeaderSpecTests {
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY, this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE.getPolicy()); ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE.getPolicy());
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.referrerPolicy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE); .referrerPolicy((referrer) -> referrer.policy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE)));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -463,15 +464,13 @@ public class HeaderSpecTests {
this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY,
CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy()); CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy());
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.crossOriginOpenerPolicy() .crossOriginOpenerPolicy((opener) -> opener
.policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS) .policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS))
.and() .crossOriginEmbedderPolicy((embedder) -> embedder
.crossOriginEmbedderPolicy() .policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP))
.policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) .crossOriginResourcePolicy((resource) -> resource
.and() .policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN)));
.crossOriginResourcePolicy()
.policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN);
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }
@ -486,16 +485,16 @@ public class HeaderSpecTests {
this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY, this.expectedHeaders.add(CrossOriginResourcePolicyServerHttpHeadersWriter.RESOURCE_POLICY,
CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy()); CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN.getPolicy());
// @formatter:off // @formatter:off
this.http.headers() this.http.headers((headers) -> headers
.crossOriginOpenerPolicy((policy) -> policy .crossOriginOpenerPolicy((policy) -> policy
.policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS) .policy(CrossOriginOpenerPolicyServerHttpHeadersWriter.CrossOriginOpenerPolicy.SAME_ORIGIN_ALLOW_POPUPS)
) )
.crossOriginEmbedderPolicy((policy) -> policy .crossOriginEmbedderPolicy((policy) -> policy
.policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP) .policy(CrossOriginEmbedderPolicyServerHttpHeadersWriter.CrossOriginEmbedderPolicy.REQUIRE_CORP)
) )
.crossOriginResourcePolicy((policy) -> policy .crossOriginResourcePolicy((policy) -> policy
.policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN) .policy(CrossOriginResourcePolicyServerHttpHeadersWriter.CrossOriginResourcePolicy.SAME_ORIGIN)
); ));
// @formatter:on // @formatter:on
assertHeaders(); assertHeaders();
} }

View File

@ -162,7 +162,7 @@ public class HttpsRedirectSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.redirectToHttps(); .redirectToHttps(withDefaults());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -194,8 +194,8 @@ public class HttpsRedirectSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.redirectToHttps() .redirectToHttps((https) -> https
.httpsRedirectWhen(new PathPatternParserServerWebExchangeMatcher("/secure")); .httpsRedirectWhen(new PathPatternParserServerWebExchangeMatcher("/secure")));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -230,8 +230,8 @@ public class HttpsRedirectSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.redirectToHttps() .redirectToHttps((https) -> https
.portMapper(portMapper()); .portMapper(portMapper()));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }

View File

@ -44,12 +44,10 @@ public class LogoutSpecTests {
public void defaultLogout() { public void defaultLogout() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin() .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -80,14 +78,12 @@ public class LogoutSpecTests {
public void customLogout() { public void customLogout() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin().and() .logout((logout) -> logout
.logout() .requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")))
.requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();
@ -155,12 +151,11 @@ public class LogoutSpecTests {
public void logoutWhenDisabledThenDefaultLogoutPageDoesNotExist() { public void logoutWhenDisabledThenDefaultLogoutPageDoesNotExist() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin().and() .logout((logout) -> logout.disable())
.logout().disable() .build();
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToControllerAndWebFilters(HomeController.class, securityWebFilter) .bindToControllerAndWebFilters(HomeController.class, securityWebFilter)
.build(); .build();
@ -188,13 +183,12 @@ public class LogoutSpecTests {
repository.setSpringSecurityContextAttrName("CUSTOM_CONTEXT_ATTR"); repository.setSpringSecurityContextAttrName("CUSTOM_CONTEXT_ATTR");
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.securityContextRepository(repository) .securityContextRepository(repository)
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin().and() .logout(withDefaults())
.logout().and() .build();
.build();
WebTestClient webTestClient = WebTestClientBuilder WebTestClient webTestClient = WebTestClientBuilder
.bindToWebFilters(securityWebFilter) .bindToWebFilters(securityWebFilter)
.build(); .build();

View File

@ -73,6 +73,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.config.Customizer.withDefaults;
/** /**
* @author Rob Winch * @author Rob Winch
@ -289,7 +290,7 @@ public class OAuth2ClientSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.oauth2Client(); .oauth2Client(withDefaults());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -348,12 +349,11 @@ public class OAuth2ClientSpecTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.oauth2Client() .oauth2Client((client) -> client
.authenticationConverter(this.authenticationConverter) .authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager) .authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository) .authorizationRequestRepository(this.authorizationRequestRepository)
.authorizationRequestResolver(this.resolver) .authorizationRequestResolver(this.resolver))
.and()
.requestCache((c) -> c.requestCache(this.requestCache)); .requestCache((c) -> c.requestCache(this.requestCache));
// @formatter:on // @formatter:on
return http.build(); return http.build();

View File

@ -122,6 +122,7 @@ import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.springframework.security.config.Customizer.withDefaults;
/** /**
* @author Rob Winch * @author Rob Winch
@ -825,11 +826,10 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.requestCache() .requestCache((cache) -> cache
.requestCache(this.requestCache) .requestCache(this.requestCache))
.and() .oauth2Login((login) -> login
.oauth2Login() .authorizationRequestRepository(this.authorizationRequestRepository));
.authorizationRequestRepository(this.authorizationRequestRepository);
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -863,12 +863,10 @@ public class OAuth2LoginTests {
http.authenticationManager(authenticationManager); http.authenticationManager(authenticationManager);
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .oauth2Login(withDefaults())
.oauth2Login() .formLogin(withDefaults());
.and()
.formLogin();
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -887,12 +885,10 @@ public class OAuth2LoginTests {
http.authenticationManager(authenticationManager); http.authenticationManager(authenticationManager);
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .oauth2Login(withDefaults())
.oauth2Login() .httpBasic(withDefaults());
.and()
.httpBasic();
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -958,16 +954,15 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .oauth2Login((login) -> login
.oauth2Login()
.authenticationConverter(this.authenticationConverter) .authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager) .authenticationManager(this.manager)
.authenticationMatcher(this.matcher) .authenticationMatcher(this.matcher)
.authorizationRequestResolver(this.resolver) .authorizationRequestResolver(this.resolver)
.authenticationSuccessHandler(this.successHandler) .authenticationSuccessHandler(this.successHandler)
.authenticationFailureHandler(this.failureHandler); .authenticationFailureHandler(this.failureHandler));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -1031,13 +1026,12 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) { SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .oauth2Login((login) -> login
.oauth2Login()
.authenticationConverter(this.authenticationConverter) .authenticationConverter(this.authenticationConverter)
.authenticationManager(authenticationManager()) .authenticationManager(authenticationManager())
.securityContextRepository(this.securityContextRepository); .securityContextRepository(this.securityContextRepository));
return http.build(); return http.build();
// @formatter:on // @formatter:on
} }
@ -1102,14 +1096,13 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.csrf().disable() .csrf((csrf) -> csrf.disable())
.logout() .logout((logout) -> logout
// avoid using mock ServerSecurityContextRepository for logout // avoid using mock ServerSecurityContextRepository for logout
.logoutHandler(new SecurityContextServerLogoutHandler()) .logoutHandler(new SecurityContextServerLogoutHandler())
.logoutSuccessHandler( .logoutSuccessHandler(
new OidcClientInitiatedServerLogoutSuccessHandler( new OidcClientInitiatedServerLogoutSuccessHandler(
new InMemoryReactiveClientRegistrationRepository(this.withLogout))) new InMemoryReactiveClientRegistrationRepository(this.withLogout))))
.and()
.securityContextRepository(this.repository); .securityContextRepository(this.repository);
// @formatter:on // @formatter:on
return http.build(); return http.build();

View File

@ -55,6 +55,7 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.test.SpringTestContext; import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension; import org.springframework.security.config.test.SpringTestContextExtension;
@ -463,9 +464,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class); ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class); ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean(ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean(ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtDecoder(dslWiredJwtDecoder); jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder); assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}));
} }
@Test @Test
@ -477,9 +479,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class); ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtDecoder(dslWiredJwtDecoder); jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder); assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}));
} }
@Test @Test
@ -490,8 +493,9 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class); ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder); context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer(
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder()); (server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(jwt::getJwtDecoder)));
} }
@Test @Test
@ -499,8 +503,9 @@ public class OAuth2ResourceServerSpecTests {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext(); GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity(); ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context); http.setApplicationContext(context);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer(
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder()); (server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(jwt::getJwtDecoder)));
} }
@Test @Test
@ -511,9 +516,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtAuthenticationConverter beanWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter(); ReactiveJwtAuthenticationConverter beanWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
ReactiveJwtAuthenticationConverter dslWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter(); ReactiveJwtAuthenticationConverter dslWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
context.registerBean(ReactiveJwtAuthenticationConverter.class, () -> beanWiredJwtAuthenticationConverter); context.registerBean(ReactiveJwtAuthenticationConverter.class, () -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter); jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter); assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
}));
} }
@Test @Test
@ -527,9 +533,10 @@ public class OAuth2ResourceServerSpecTests {
() -> beanWiredJwtAuthenticationConverter); () -> beanWiredJwtAuthenticationConverter);
context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class, context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class,
() -> beanWiredJwtAuthenticationConverter); () -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter); jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter); assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
}));
} }
@Test @Test
@ -542,8 +549,9 @@ public class OAuth2ResourceServerSpecTests {
() -> beanWiredJwtAuthenticationConverter); () -> beanWiredJwtAuthenticationConverter);
context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class, context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class,
() -> beanWiredJwtAuthenticationConverter); () -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer(
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwt::getJwtAuthenticationConverter); (server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(jwt::getJwtAuthenticationConverter)));
} }
@Test @Test
@ -551,8 +559,8 @@ public class OAuth2ResourceServerSpecTests {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext(); GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity(); ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context); http.setApplicationContext(context);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt(); http.oauth2ResourceServer((server) -> server.jwt((jwt) -> assertThat(jwt.getJwtAuthenticationConverter())
assertThat(jwt.getJwtAuthenticationConverter()).isInstanceOf(ReactiveJwtAuthenticationConverter.class); .isInstanceOf(ReactiveJwtAuthenticationConverter.class)));
} }
@Test @Test
@ -674,12 +682,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read") .anyExchange().hasAuthority("SCOPE_message:read"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer() .jwt((jwt) -> jwt.publicKey(publicKey())));
.jwt()
.publicKey(publicKey());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -724,12 +730,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read") .anyExchange().hasAuthority("SCOPE_message:read"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer() .jwt((jwt) -> jwt.publicKey(this.key)));
.jwt()
.publicKey(this.key);
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -748,9 +752,8 @@ public class OAuth2ResourceServerSpecTests {
String jwkSetUri = mockWebServer().url("/.well-known/jwks.json").toString(); String jwkSetUri = mockWebServer().url("/.well-known/jwks.json").toString();
// @formatter:off // @formatter:off
http http
.oauth2ResourceServer() .oauth2ResourceServer((server) -> server
.jwt() .jwt((jwt) -> jwt.jwkSetUri(jwkSetUri)));
.jwkSetUri(jwkSetUri);
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -813,8 +816,8 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.oauth2ResourceServer() .oauth2ResourceServer((server) -> server
.jwt(); .jwt(Customizer.withDefaults()));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -835,12 +838,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain authorization(ServerHttpSecurity http) { SecurityWebFilterChain authorization(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().denyAll() .anyExchange().denyAll())
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer() .jwt((jwt) -> jwt.publicKey(publicKey())));
.jwt()
.publicKey(publicKey());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -856,9 +857,8 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.oauth2ResourceServer() .oauth2ResourceServer((server) -> server
.jwt() .jwt((jwt) -> jwt.authenticationManager(authenticationManager())));
.authenticationManager(authenticationManager());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -906,11 +906,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.pathMatchers("/*/message/**").hasAnyAuthority("SCOPE_message:read") .pathMatchers("/*/message/**").hasAnyAuthority("SCOPE_message:read"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer() .authenticationManagerResolver(authenticationManagerResolver()));
.authenticationManagerResolver(authenticationManagerResolver());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -965,13 +964,11 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read") .anyExchange().hasAuthority("SCOPE_message:read"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer()
.bearerTokenConverter(bearerTokenAuthenticationConverter()) .bearerTokenConverter(bearerTokenAuthenticationConverter())
.jwt() .jwt((jwt) -> jwt.publicKey(publicKey())));
.publicKey(publicKey());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -993,13 +990,12 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("message:read") .anyExchange().hasAuthority("message:read"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer() .jwt((jwt) -> jwt
.jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter()) .jwtAuthenticationConverter(jwtAuthenticationConverter())
.publicKey(publicKey()); .publicKey(publicKey())));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -1025,15 +1021,13 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.pathMatchers("/authenticated").authenticated() .pathMatchers("/authenticated").authenticated()
.pathMatchers("/unobtainable").hasAuthority("unobtainable") .pathMatchers("/unobtainable").hasAuthority("unobtainable"))
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer()
.accessDeniedHandler(new HttpStatusServerAccessDeniedHandler(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED)) .accessDeniedHandler(new HttpStatusServerAccessDeniedHandler(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED))
.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.I_AM_A_TEAPOT)) .authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.I_AM_A_TEAPOT))
.jwt() .jwt((jwt) -> jwt.publicKey(publicKey())));
.publicKey(publicKey());
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -1052,10 +1046,10 @@ public class OAuth2ResourceServerSpecTests {
String introspectionUri = mockWebServer().url("/introspect").toString(); String introspectionUri = mockWebServer().url("/introspect").toString();
// @formatter:off // @formatter:off
http http
.oauth2ResourceServer() .oauth2ResourceServer((server) -> server
.opaqueToken() .opaqueToken((opaqueToken) -> opaqueToken
.introspectionUri(introspectionUri) .introspectionUri(introspectionUri)
.introspectionClientCredentials("client", "secret"); .introspectionClientCredentials("client", "secret")));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -1117,12 +1111,11 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) { SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off // @formatter:off
http http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .oauth2ResourceServer((server) -> server
.oauth2ResourceServer()
.authenticationManagerResolver(mock(ReactiveAuthenticationManagerResolver.class)) .authenticationManagerResolver(mock(ReactiveAuthenticationManagerResolver.class))
.opaqueToken(); .opaqueToken(Customizer.withDefaults()));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }
@ -1141,11 +1134,11 @@ public class OAuth2ResourceServerSpecTests {
String introspectionUri = mockWebServer().url("/introspect").toString(); String introspectionUri = mockWebServer().url("/introspect").toString();
// @formatter:off // @formatter:off
http http
.oauth2ResourceServer() .oauth2ResourceServer((server) -> server
.opaqueToken() .opaqueToken((opaqueToken) -> opaqueToken
.introspectionUri(introspectionUri) .introspectionUri(introspectionUri)
.introspectionClientCredentials("client", "secret") .introspectionClientCredentials("client", "secret")
.authenticationConverter(authenticationConverter()); .authenticationConverter(authenticationConverter())));
// @formatter:on // @formatter:on
return http.build(); return http.build();
} }

View File

@ -19,6 +19,7 @@ package org.springframework.security.config.web.server;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder; import org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder;
import org.springframework.security.config.web.server.ServerHttpSecurity.PasswordManagementSpec; import org.springframework.security.config.web.server.ServerHttpSecurity.PasswordManagementSpec;
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
@ -37,7 +38,7 @@ public class PasswordManagementSpecTests {
@Test @Test
public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() { public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() {
this.http.passwordManagement(); this.http.passwordManagement(Customizer.withDefaults());
WebTestClient client = buildClient(); WebTestClient client = buildClient();
client.get() client.get()
@ -70,19 +71,22 @@ public class PasswordManagementSpecTests {
@Test @Test
public void whenSettingNullChangePasswordPage() { public void whenSettingNullChangePasswordPage() {
assertThatIllegalArgumentException().isThrownBy(() -> this.http.passwordManagement().changePasswordPage(null)) assertThatIllegalArgumentException()
.isThrownBy(() -> this.http.passwordManagement((password) -> password.changePasswordPage(null)))
.withMessage("changePasswordPage cannot be empty"); .withMessage("changePasswordPage cannot be empty");
} }
@Test @Test
public void whenSettingEmptyChangePasswordPage() { public void whenSettingEmptyChangePasswordPage() {
assertThatIllegalArgumentException().isThrownBy(() -> this.http.passwordManagement().changePasswordPage("")) assertThatIllegalArgumentException()
.isThrownBy(() -> this.http.passwordManagement((password) -> password.changePasswordPage("")))
.withMessage("changePasswordPage cannot be empty"); .withMessage("changePasswordPage cannot be empty");
} }
@Test @Test
public void whenSettingBlankChangePasswordPage() { public void whenSettingBlankChangePasswordPage() {
assertThatIllegalArgumentException().isThrownBy(() -> this.http.passwordManagement().changePasswordPage(" ")) assertThatIllegalArgumentException()
.isThrownBy(() -> this.http.passwordManagement((password) -> password.changePasswordPage(" ")))
.withMessage("changePasswordPage cannot be empty"); .withMessage("changePasswordPage cannot be empty");
} }

View File

@ -49,11 +49,10 @@ public class RequestCacheTests {
public void defaultFormLoginRequestCache() { public void defaultFormLoginRequestCache() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin().and() .build();
.build();
WebTestClient webTestClient = WebTestClient WebTestClient webTestClient = WebTestClient
.bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController()) .bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController())
.webFilter(new WebFilterChainProxy(securityWebFilter)) .webFilter(new WebFilterChainProxy(securityWebFilter))
@ -76,14 +75,12 @@ public class RequestCacheTests {
public void requestCacheNoOp() { public void requestCacheNoOp() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityWebFilter = this.http SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange() .authorizeExchange((exchange) -> exchange
.anyExchange().authenticated() .anyExchange().authenticated())
.and() .formLogin(withDefaults())
.formLogin().and() .requestCache((cache) -> cache
.requestCache() .requestCache(NoOpServerRequestCache.getInstance()))
.requestCache(NoOpServerRequestCache.getInstance()) .build();
.and()
.build();
WebTestClient webTestClient = WebTestClient WebTestClient webTestClient = WebTestClient
.bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController()) .bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController())
.webFilter(new WebFilterChainProxy(securityWebFilter)) .webFilter(new WebFilterChainProxy(securityWebFilter))

View File

@ -146,10 +146,9 @@ public class ServerHttpSecurityTests {
public void basic() { public void basic() {
given(this.authenticationManager.authenticate(any())) given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN"))); .willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.httpBasic(); this.http.httpBasic(withDefaults());
this.http.authenticationManager(this.authenticationManager); this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange(); this.http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated());
authorize.anyExchange().authenticated();
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
EntityExchangeResult<String> result = client.get() EntityExchangeResult<String> result = client.get()
@ -171,10 +170,9 @@ public class ServerHttpSecurityTests {
given(this.authenticationManager.authenticate(any())) given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN"))); .willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.securityContextRepository(new WebSessionServerSecurityContextRepository()); this.http.securityContextRepository(new WebSessionServerSecurityContextRepository());
this.http.httpBasic(); this.http.httpBasic(withDefaults());
this.http.authenticationManager(this.authenticationManager); this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange(); this.http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated());
authorize.anyExchange().authenticated();
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
EntityExchangeResult<String> result = client.get() EntityExchangeResult<String> result = client.get()
@ -193,7 +191,7 @@ public class ServerHttpSecurityTests {
@Test @Test
public void basicWhenNoCredentialsThenUnauthorized() { public void basicWhenNoCredentialsThenUnauthorized() {
this.http.authorizeExchange().anyExchange().authenticated(); this.http.authorizeExchange((exchange) -> exchange.anyExchange().authenticated());
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
client.get().uri("/") client.get().uri("/")
@ -208,8 +206,8 @@ public class ServerHttpSecurityTests {
public void basicWhenXHRRequestThenUnauthorized() { public void basicWhenXHRRequestThenUnauthorized() {
ServerAuthenticationEntryPoint authenticationEntryPoint = spy( ServerAuthenticationEntryPoint authenticationEntryPoint = spy(
new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)); new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED));
this.http.httpBasic().authenticationEntryPoint(authenticationEntryPoint); this.http.httpBasic((basic) -> basic.authenticationEntryPoint(authenticationEntryPoint));
this.http.authorizeExchange().anyExchange().authenticated(); this.http.authorizeExchange((exchange) -> exchange.anyExchange().authenticated());
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
client.get().uri("/") client.get().uri("/")
@ -228,9 +226,9 @@ public class ServerHttpSecurityTests {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
ServerAuthenticationFailureHandler authenticationFailureHandler = mock( ServerAuthenticationFailureHandler authenticationFailureHandler = mock(
ServerAuthenticationFailureHandler.class); ServerAuthenticationFailureHandler.class);
this.http.httpBasic().authenticationFailureHandler(authenticationFailureHandler); this.http.httpBasic((basic) -> basic.authenticationFailureHandler(authenticationFailureHandler));
this.http.httpBasic().authenticationManager(authenticationManager); this.http.httpBasic((basic) -> basic.authenticationManager(authenticationManager));
this.http.authorizeExchange().anyExchange().authenticated(); this.http.authorizeExchange((exchange) -> exchange.anyExchange().authenticated());
given(authenticationManager.authenticate(any())) given(authenticationManager.authenticate(any()))
.willReturn(Mono.error(() -> new BadCredentialsException("bad"))); .willReturn(Mono.error(() -> new BadCredentialsException("bad")));
given(authenticationFailureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty()); given(authenticationFailureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty());
@ -261,7 +259,7 @@ public class ServerHttpSecurityTests {
@Test @Test
public void csrfServerLogoutHandlerNotAppliedIfCsrfIsntEnabled() { public void csrfServerLogoutHandlerNotAppliedIfCsrfIsntEnabled() {
SecurityWebFilterChain securityWebFilterChain = this.http.csrf().disable().build(); SecurityWebFilterChain securityWebFilterChain = this.http.csrf((csrf) -> csrf.disable()).build();
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).isNotPresent(); assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).isNotPresent();
Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class) Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class)
.map((logoutWebFilter) -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter, .map((logoutWebFilter) -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
@ -271,9 +269,8 @@ public class ServerHttpSecurityTests {
@Test @Test
public void csrfServerLogoutHandlerAppliedIfCsrfIsEnabled() { public void csrfServerLogoutHandlerAppliedIfCsrfIsEnabled() {
SecurityWebFilterChain securityWebFilterChain = this.http.csrf() SecurityWebFilterChain securityWebFilterChain = this.http
.csrfTokenRepository(this.csrfTokenRepository) .csrf((csrf) -> csrf.csrfTokenRepository(this.csrfTokenRepository))
.and()
.build(); .build();
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).get() assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).get()
.extracting((csrfWebFilter) -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository")) .extracting((csrfWebFilter) -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository"))
@ -328,8 +325,8 @@ public class ServerHttpSecurityTests {
public void anonymous() { public void anonymous() {
// @formatter:off // @formatter:off
SecurityWebFilterChain securityFilterChain = this.http SecurityWebFilterChain securityFilterChain = this.http
.anonymous().and() .anonymous(withDefaults())
.build(); .build();
WebTestClient client = WebTestClientBuilder WebTestClient client = WebTestClientBuilder
.bindToControllerAndWebFilters(AnonymousAuthenticationWebFilterTests.HttpMeController.class, securityFilterChain) .bindToControllerAndWebFilters(AnonymousAuthenticationWebFilterTests.HttpMeController.class, securityFilterChain)
.build(); .build();
@ -360,10 +357,9 @@ public class ServerHttpSecurityTests {
public void basicWithAnonymous() { public void basicWithAnonymous() {
given(this.authenticationManager.authenticate(any())) given(this.authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN"))); .willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.httpBasic().and().anonymous(); this.http.httpBasic(withDefaults()).anonymous(withDefaults());
this.http.authenticationManager(this.authenticationManager); this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange(); this.http.authorizeExchange((authorize) -> authorize.anyExchange().hasAuthority("ROLE_ADMIN"));
authorize.anyExchange().hasAuthority("ROLE_ADMIN");
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
EntityExchangeResult<String> result = client.get() EntityExchangeResult<String> result = client.get()
@ -384,10 +380,9 @@ public class ServerHttpSecurityTests {
this.http.securityContextRepository(new WebSessionServerSecurityContextRepository()); this.http.securityContextRepository(new WebSessionServerSecurityContextRepository());
HttpBasicServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint(); HttpBasicServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();
authenticationEntryPoint.setRealm("myrealm"); authenticationEntryPoint.setRealm("myrealm");
this.http.httpBasic().authenticationEntryPoint(authenticationEntryPoint); this.http.httpBasic((basic) -> basic.authenticationEntryPoint(authenticationEntryPoint));
this.http.authenticationManager(this.authenticationManager); this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange(); this.http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated());
authorize.anyExchange().authenticated();
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
EntityExchangeResult<String> result = client.get() EntityExchangeResult<String> result = client.get()
@ -408,8 +403,7 @@ public class ServerHttpSecurityTests {
authenticationEntryPoint.setRealm("myrealm"); authenticationEntryPoint.setRealm("myrealm");
this.http.httpBasic((httpBasic) -> httpBasic.authenticationEntryPoint(authenticationEntryPoint)); this.http.httpBasic((httpBasic) -> httpBasic.authenticationEntryPoint(authenticationEntryPoint));
this.http.authenticationManager(this.authenticationManager); this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange(); this.http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated());
authorize.anyExchange().authenticated();
WebTestClient client = buildClient(); WebTestClient client = buildClient();
// @formatter:off // @formatter:off
EntityExchangeResult<String> result = client.get() EntityExchangeResult<String> result = client.get()
@ -430,10 +424,9 @@ public class ServerHttpSecurityTests {
.willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN"))); .willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
// @formatter:off // @formatter:off
SecurityWebFilterChain securityFilterChain = this.http SecurityWebFilterChain securityFilterChain = this.http
.httpBasic() .httpBasic((basic) -> basic
.authenticationManager(customAuthenticationManager) .authenticationManager(customAuthenticationManager))
.and() .build();
.build();
// @formatter:on // @formatter:on
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain); WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
// @formatter:off // @formatter:off
@ -486,7 +479,8 @@ public class ServerHttpSecurityTests {
public void addsX509FilterWhenX509AuthenticationIsConfigured() { public void addsX509FilterWhenX509AuthenticationIsConfigured() {
X509PrincipalExtractor mockExtractor = mock(X509PrincipalExtractor.class); X509PrincipalExtractor mockExtractor = mock(X509PrincipalExtractor.class);
ReactiveAuthenticationManager mockAuthenticationManager = mock(ReactiveAuthenticationManager.class); ReactiveAuthenticationManager mockAuthenticationManager = mock(ReactiveAuthenticationManager.class);
this.http.x509().principalExtractor(mockExtractor).authenticationManager(mockAuthenticationManager).and(); this.http
.x509((x509) -> x509.principalExtractor(mockExtractor).authenticationManager(mockAuthenticationManager));
SecurityWebFilterChain securityWebFilterChain = this.http.build(); SecurityWebFilterChain securityWebFilterChain = this.http.build();
WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst(); WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst();
assertThat(x509WebFilter).isNotNull(); assertThat(x509WebFilter).isNotNull();
@ -505,7 +499,7 @@ public class ServerHttpSecurityTests {
@Test @Test
public void addsX509FilterWhenX509AuthenticationIsConfiguredWithDefaults() { public void addsX509FilterWhenX509AuthenticationIsConfiguredWithDefaults() {
this.http.x509(); this.http.x509(withDefaults());
SecurityWebFilterChain securityWebFilterChain = this.http.build(); SecurityWebFilterChain securityWebFilterChain = this.http.build();
WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst(); WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst();
assertThat(x509WebFilter).isNotNull(); assertThat(x509WebFilter).isNotNull();
@ -600,13 +594,9 @@ public class ServerHttpSecurityTests {
ServerRequestCache requestCache = spy(new WebSessionServerRequestCache()); ServerRequestCache requestCache = spy(new WebSessionServerRequestCache());
ReactiveClientRegistrationRepository clientRegistrationRepository = mock( ReactiveClientRegistrationRepository clientRegistrationRepository = mock(
ReactiveClientRegistrationRepository.class); ReactiveClientRegistrationRepository.class);
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Login((login) -> login.clientRegistrationRepository(clientRegistrationRepository))
.and() .authorizeExchange((exchange) -> exchange.anyExchange().authenticated())
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.requestCache((c) -> c.requestCache(requestCache)) .requestCache((c) -> c.requestCache(requestCache))
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
@ -633,10 +623,9 @@ public class ServerHttpSecurityTests {
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build(); OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
given(authorizationRequestRepository.removeAuthorizationRequest(any())) given(authorizationRequestRepository.removeAuthorizationRequest(any()))
.willReturn(Mono.just(authorizationRequest)); .willReturn(Mono.just(authorizationRequest));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Login((login) -> login.clientRegistrationRepository(clientRegistrationRepository)
.authorizationRequestRepository(authorizationRequestRepository) .authorizationRequestRepository(authorizationRequestRepository))
.and()
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/login/oauth2/code/registration-id").exchange(); client.get().uri("/login/oauth2/code/registration-id").exchange();
@ -650,9 +639,8 @@ public class ServerHttpSecurityTests {
given(clientRegistrationRepository.findByRegistrationId(anyString())) given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build())); .willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Login((login) -> login.clientRegistrationRepository(clientRegistrationRepository))
.and()
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
@ -674,10 +662,9 @@ public class ServerHttpSecurityTests {
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build())); .willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty()); given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Login((login) -> login.clientRegistrationRepository(clientRegistrationRepository)
.authorizationRedirectStrategy(authorizationRedirectStrategy) .authorizationRedirectStrategy(authorizationRedirectStrategy))
.and()
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
@ -698,9 +685,8 @@ public class ServerHttpSecurityTests {
given(clientRegistrationRepository.findByRegistrationId(anyString())) given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build())); .willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Client((client) -> client.clientRegistrationRepository(clientRegistrationRepository))
.and()
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
@ -722,10 +708,9 @@ public class ServerHttpSecurityTests {
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build())); .willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty()); given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client() SecurityWebFilterChain securityFilterChain = this.http
.clientRegistrationRepository(clientRegistrationRepository) .oauth2Client((client) -> client.clientRegistrationRepository(clientRegistrationRepository)
.authorizationRedirectStrategy(authorizationRedirectStrategy) .authorizationRedirectStrategy(authorizationRedirectStrategy))
.and()
.build(); .build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build(); WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();