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
SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**"))
.authorizeExchange()
.anyExchange()
.denyAll();
.authorizeExchange((exchange) -> exchange.anyExchange().denyAll());
return http.build();
}

View File

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

View File

@ -73,7 +73,7 @@ public class CorsSpecTests {
@Test
public void corsWhenEnabledThenAccessControlAllowOriginAndSecurityHeaders() {
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("X-Frame-Options", "DENY");
assertHeaders();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -73,6 +73,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.config.Customizer.withDefaults;
/**
* @author Rob Winch
@ -289,7 +290,7 @@ public class OAuth2ClientSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2Client();
.oauth2Client(withDefaults());
// @formatter:on
return http.build();
}
@ -348,12 +349,11 @@ public class OAuth2ClientSpecTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2Client()
.oauth2Client((client) -> client
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository)
.authorizationRequestResolver(this.resolver)
.and()
.authorizationRequestResolver(this.resolver))
.requestCache((c) -> c.requestCache(this.requestCache));
// @formatter:on
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.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.security.config.Customizer.withDefaults;
/**
* @author Rob Winch
@ -825,11 +826,10 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.requestCache()
.requestCache(this.requestCache)
.and()
.oauth2Login()
.authorizationRequestRepository(this.authorizationRequestRepository);
.requestCache((cache) -> cache
.requestCache(this.requestCache))
.oauth2Login((login) -> login
.authorizationRequestRepository(this.authorizationRequestRepository));
// @formatter:on
return http.build();
}
@ -863,12 +863,10 @@ public class OAuth2LoginTests {
http.authenticationManager(authenticationManager);
// @formatter:off
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2Login()
.and()
.formLogin();
.authorizeExchange((exchange) -> exchange
.anyExchange().authenticated())
.oauth2Login(withDefaults())
.formLogin(withDefaults());
// @formatter:on
return http.build();
}
@ -887,12 +885,10 @@ public class OAuth2LoginTests {
http.authenticationManager(authenticationManager);
// @formatter:off
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2Login()
.and()
.httpBasic();
.authorizeExchange((exchange) -> exchange
.anyExchange().authenticated())
.oauth2Login(withDefaults())
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@ -958,16 +954,15 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2Login()
.authorizeExchange((exchange) -> exchange
.anyExchange().authenticated())
.oauth2Login((login) -> login
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authenticationMatcher(this.matcher)
.authorizationRequestResolver(this.resolver)
.authenticationSuccessHandler(this.successHandler)
.authenticationFailureHandler(this.failureHandler);
.authenticationFailureHandler(this.failureHandler));
// @formatter:on
return http.build();
}
@ -1031,13 +1026,12 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2Login()
.authorizeExchange((exchange) -> exchange
.anyExchange().authenticated())
.oauth2Login((login) -> login
.authenticationConverter(this.authenticationConverter)
.authenticationManager(authenticationManager())
.securityContextRepository(this.securityContextRepository);
.securityContextRepository(this.securityContextRepository));
return http.build();
// @formatter:on
}
@ -1102,14 +1096,13 @@ public class OAuth2LoginTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.csrf().disable()
.logout()
.csrf((csrf) -> csrf.disable())
.logout((logout) -> logout
// avoid using mock ServerSecurityContextRepository for logout
.logoutHandler(new SecurityContextServerLogoutHandler())
.logoutSuccessHandler(
new OidcClientInitiatedServerLogoutSuccessHandler(
new InMemoryReactiveClientRegistrationRepository(this.withLogout)))
.and()
new OidcClientInitiatedServerLogoutSuccessHandler(
new InMemoryReactiveClientRegistrationRepository(this.withLogout))))
.securityContextRepository(this.repository);
// @formatter:on
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.ReactiveAuthenticationManagerResolver;
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.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
@ -463,9 +464,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean(ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}));
}
@Test
@ -477,9 +479,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}));
}
@Test
@ -490,8 +493,9 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
http.oauth2ResourceServer(
(server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(jwt::getJwtDecoder)));
}
@Test
@ -499,8 +503,9 @@ public class OAuth2ResourceServerSpecTests {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
http.oauth2ResourceServer(
(server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(jwt::getJwtDecoder)));
}
@Test
@ -511,9 +516,10 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtAuthenticationConverter beanWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
ReactiveJwtAuthenticationConverter dslWiredJwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
context.registerBean(ReactiveJwtAuthenticationConverter.class, () -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
}));
}
@Test
@ -527,9 +533,10 @@ public class OAuth2ResourceServerSpecTests {
() -> beanWiredJwtAuthenticationConverter);
context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class,
() -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
http.oauth2ResourceServer((server) -> server.jwt((jwt) -> {
jwt.jwtAuthenticationConverter(dslWiredJwtAuthenticationConverter);
assertThat(jwt.getJwtAuthenticationConverter()).isEqualTo(dslWiredJwtAuthenticationConverter);
}));
}
@Test
@ -542,8 +549,9 @@ public class OAuth2ResourceServerSpecTests {
() -> beanWiredJwtAuthenticationConverter);
context.registerBean("secondJwtAuthenticationConverter", ReactiveJwtAuthenticationConverter.class,
() -> beanWiredJwtAuthenticationConverter);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwt::getJwtAuthenticationConverter);
http.oauth2ResourceServer(
(server) -> server.jwt((jwt) -> assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(jwt::getJwtAuthenticationConverter)));
}
@Test
@ -551,8 +559,8 @@ public class OAuth2ResourceServerSpecTests {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThat(jwt.getJwtAuthenticationConverter()).isInstanceOf(ReactiveJwtAuthenticationConverter.class);
http.oauth2ResourceServer((server) -> server.jwt((jwt) -> assertThat(jwt.getJwtAuthenticationConverter())
.isInstanceOf(ReactiveJwtAuthenticationConverter.class)));
}
@Test
@ -674,12 +682,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().hasAuthority("SCOPE_message:read")
.and()
.oauth2ResourceServer()
.jwt()
.publicKey(publicKey());
.authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read"))
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt.publicKey(publicKey())));
// @formatter:on
return http.build();
}
@ -724,12 +730,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().hasAuthority("SCOPE_message:read")
.and()
.oauth2ResourceServer()
.jwt()
.publicKey(this.key);
.authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read"))
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt.publicKey(this.key)));
// @formatter:on
return http.build();
}
@ -748,9 +752,8 @@ public class OAuth2ResourceServerSpecTests {
String jwkSetUri = mockWebServer().url("/.well-known/jwks.json").toString();
// @formatter:off
http
.oauth2ResourceServer()
.jwt()
.jwkSetUri(jwkSetUri);
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt.jwkSetUri(jwkSetUri)));
// @formatter:on
return http.build();
}
@ -813,8 +816,8 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2ResourceServer()
.jwt();
.oauth2ResourceServer((server) -> server
.jwt(Customizer.withDefaults()));
// @formatter:on
return http.build();
}
@ -835,12 +838,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain authorization(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().denyAll()
.and()
.oauth2ResourceServer()
.jwt()
.publicKey(publicKey());
.authorizeExchange((exchange) -> exchange
.anyExchange().denyAll())
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt.publicKey(publicKey())));
// @formatter:on
return http.build();
}
@ -856,9 +857,8 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2ResourceServer()
.jwt()
.authenticationManager(authenticationManager());
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt.authenticationManager(authenticationManager())));
// @formatter:on
return http.build();
}
@ -906,11 +906,10 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.pathMatchers("/*/message/**").hasAnyAuthority("SCOPE_message:read")
.and()
.oauth2ResourceServer()
.authenticationManagerResolver(authenticationManagerResolver());
.authorizeExchange((exchange) -> exchange
.pathMatchers("/*/message/**").hasAnyAuthority("SCOPE_message:read"))
.oauth2ResourceServer((server) -> server
.authenticationManagerResolver(authenticationManagerResolver()));
// @formatter:on
return http.build();
}
@ -965,13 +964,11 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().hasAuthority("SCOPE_message:read")
.and()
.oauth2ResourceServer()
.authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("SCOPE_message:read"))
.oauth2ResourceServer((server) -> server
.bearerTokenConverter(bearerTokenAuthenticationConverter())
.jwt()
.publicKey(publicKey());
.jwt((jwt) -> jwt.publicKey(publicKey())));
// @formatter:on
return http.build();
}
@ -993,13 +990,12 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().hasAuthority("message:read")
.and()
.oauth2ResourceServer()
.jwt()
.authorizeExchange((exchange) -> exchange
.anyExchange().hasAuthority("message:read"))
.oauth2ResourceServer((server) -> server
.jwt((jwt) -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
.publicKey(publicKey());
.publicKey(publicKey())));
// @formatter:on
return http.build();
}
@ -1025,15 +1021,13 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.authorizeExchange((exchange) -> exchange
.pathMatchers("/authenticated").authenticated()
.pathMatchers("/unobtainable").hasAuthority("unobtainable")
.and()
.oauth2ResourceServer()
.pathMatchers("/unobtainable").hasAuthority("unobtainable"))
.oauth2ResourceServer((server) -> server
.accessDeniedHandler(new HttpStatusServerAccessDeniedHandler(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED))
.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.I_AM_A_TEAPOT))
.jwt()
.publicKey(publicKey());
.jwt((jwt) -> jwt.publicKey(publicKey())));
// @formatter:on
return http.build();
}
@ -1052,10 +1046,10 @@ public class OAuth2ResourceServerSpecTests {
String introspectionUri = mockWebServer().url("/introspect").toString();
// @formatter:off
http
.oauth2ResourceServer()
.opaqueToken()
.oauth2ResourceServer((server) -> server
.opaqueToken((opaqueToken) -> opaqueToken
.introspectionUri(introspectionUri)
.introspectionClientCredentials("client", "secret");
.introspectionClientCredentials("client", "secret")));
// @formatter:on
return http.build();
}
@ -1117,12 +1111,11 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange()
.anyExchange().authenticated()
.and()
.oauth2ResourceServer()
.authorizeExchange((exchange) -> exchange
.anyExchange().authenticated())
.oauth2ResourceServer((server) -> server
.authenticationManagerResolver(mock(ReactiveAuthenticationManagerResolver.class))
.opaqueToken();
.opaqueToken(Customizer.withDefaults()));
// @formatter:on
return http.build();
}
@ -1141,11 +1134,11 @@ public class OAuth2ResourceServerSpecTests {
String introspectionUri = mockWebServer().url("/introspect").toString();
// @formatter:off
http
.oauth2ResourceServer()
.opaqueToken()
.oauth2ResourceServer((server) -> server
.opaqueToken((opaqueToken) -> opaqueToken
.introspectionUri(introspectionUri)
.introspectionClientCredentials("client", "secret")
.authenticationConverter(authenticationConverter());
.authenticationConverter(authenticationConverter())));
// @formatter:on
return http.build();
}

View File

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

View File

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

View File

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