Use parenthesis with single-arg lambdas

Use regular expression search/replace to ensure all single-arg
lambdas have parenthesis. This aligns with the style used in Spring
Boot and ensure that single-arg and multi-arg lambdas are consistent.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-29 18:18:05 -07:00
committed by Rob Winch
parent 01d90c9881
commit 52f20b5281
426 changed files with 1668 additions and 1617 deletions

View File

@@ -89,7 +89,7 @@ public class AuthenticationManagerBuilderTests {
public void customAuthenticationEventPublisherWithWeb() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.class);
given(opp.postProcess(any())).willAnswer(a -> a.getArgument(0));
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();

View File

@@ -49,10 +49,10 @@ public class NamespaceAuthenticationManagerTests {
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNull()));
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNull()));
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
// no exception due to username being cleared out
}
@@ -61,10 +61,10 @@ public class NamespaceAuthenticationManagerTests {
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
// no exception due to username being cleared out
}
@@ -74,7 +74,7 @@ public class NamespaceAuthenticationManagerTests {
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
.authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
.authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
}
@EnableWebSecurity

View File

@@ -197,7 +197,7 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationManagerWhenPostProcessThenUsesBeanClassLoaderOnProxyFactoryBean() throws Exception {
this.spring.register(Sec2531Config.class).autowire();
ObjectPostProcessor<Object> opp = this.spring.getContext().getBean(ObjectPostProcessor.class);
given(opp.postProcess(any())).willAnswer(a -> a.getArgument(0));
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.getAuthenticationManager();

View File

@@ -224,7 +224,7 @@ public class EnableReactiveMethodSecurityTests {
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
.verifyComplete();
}
@@ -349,7 +349,7 @@ public class EnableReactiveMethodSecurityTests {
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
.verifyComplete();
}
@@ -457,7 +457,7 @@ public class EnableReactiveMethodSecurityTests {
}
static <T> Publisher<T> publisher(Flux<T> flux) {
return subscriber -> flux.subscribe(subscriber);
return (subscriber) -> flux.subscribe(subscriber);
}
static <T> Publisher<T> publisherJust(T... data) {

View File

@@ -221,7 +221,7 @@ public class GlobalMethodSecurityConfigurationTests {
public void globalSecurityProxiesSecurity() {
this.spring.register(Sec3005Config.class).autowire();
assertThat(this.service.getClass()).matches(c -> !Proxy.isProxyClass(c), "is not proxy class");
assertThat(this.service.getClass()).matches((c) -> !Proxy.isProxyClass(c), "is not proxy class");
}
//
// // gh-3797

View File

@@ -241,7 +241,7 @@ public class NamespaceGlobalMethodSecurityTests {
this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.service.runAs().getAuthorities())
.anyMatch(authority -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
.anyMatch((authority) -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
}
@Test

View File

@@ -106,7 +106,7 @@ public class WebSecurityConfigurerAdapterPowermockTests {
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
.getAllValues().stream()
.filter(e -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
.findFirst().orElse(null);
assertThat(callableProcessingInterceptor).isNotNull();

View File

@@ -189,7 +189,7 @@ public class HttpSecurityConfigurationTests {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests(authorize -> authorize.anyRequest().permitAll()).build();
return http.authorizeRequests((authorize) -> authorize.anyRequest().permitAll()).build();
}
}
@@ -199,8 +199,8 @@ public class HttpSecurityConfigurationTests {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests(authorize -> authorize.anyRequest().authenticated()).formLogin(withDefaults())
.build();
return http.authorizeRequests((authorize) -> authorize.anyRequest().authenticated())
.formLogin(withDefaults()).build();
}
}

View File

@@ -123,7 +123,7 @@ public class SecurityReactorContextConfigurationResourceServerTests {
@GetMapping("/token")
public String token() {
return this.rest.get().uri(this.uri).retrieve().bodyToMono(String.class)
.flatMap(result -> this.rest.get().uri(this.uri).retrieve().bodyToMono(String.class)).block();
.flatMap((result) -> this.rest.get().uri(this.uri).retrieve().bodyToMono(String.class)).block();
}
}

View File

@@ -209,9 +209,9 @@ public class SecurityReactorContextConfigurationTests {
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
.filter(ctx -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
.map(ctx -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
.map(attributes -> {
.filter((ctx) -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
.map((ctx) -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
.map((attributes) -> {
if (attributes.containsKey(HttpServletRequest.class)
&& attributes.containsKey(HttpServletResponse.class)
&& attributes.containsKey(Authentication.class)) {
@@ -231,7 +231,7 @@ public class SecurityReactorContextConfigurationTests {
expectedContextAttributes.put(Authentication.class, this.authentication);
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
.flatMap(response -> filter.filter(clientRequest, exchange));
.flatMap((response) -> filter.filter(clientRequest, exchange));
StepVerifier.create(clientResponseMono).expectAccessibleContext()
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)

View File

@@ -368,27 +368,27 @@ public class WebSecurityConfigurationTests {
@Order(1)
@Bean
SecurityFilterChain filterChain1(HttpSecurity http) throws Exception {
return http.antMatcher("/role1/**").authorizeRequests(authorize -> authorize.anyRequest().hasRole("1"))
return http.antMatcher("/role1/**").authorizeRequests((authorize) -> authorize.anyRequest().hasRole("1"))
.build();
}
@Order(2)
@Bean
SecurityFilterChain filterChain2(HttpSecurity http) throws Exception {
return http.antMatcher("/role2/**").authorizeRequests(authorize -> authorize.anyRequest().hasRole("2"))
return http.antMatcher("/role2/**").authorizeRequests((authorize) -> authorize.anyRequest().hasRole("2"))
.build();
}
@Order(3)
@Bean
SecurityFilterChain filterChain3(HttpSecurity http) throws Exception {
return http.antMatcher("/role3/**").authorizeRequests(authorize -> authorize.anyRequest().hasRole("3"))
return http.antMatcher("/role3/**").authorizeRequests((authorize) -> authorize.anyRequest().hasRole("3"))
.build();
}
@Bean
SecurityFilterChain filterChain4(HttpSecurity http) throws Exception {
return http.authorizeRequests(authorize -> authorize.anyRequest().hasRole("4")).build();
return http.authorizeRequests((authorize) -> authorize.anyRequest().hasRole("4")).build();
}
}
@@ -541,7 +541,7 @@ public class WebSecurityConfigurationTests {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeRequests(authorize -> authorize.anyRequest().authenticated()).build();
return http.authorizeRequests((authorize) -> authorize.anyRequest().authenticated()).build();
}
}
@@ -655,8 +655,8 @@ public class WebSecurityConfigurationTests {
@Order(2)
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.antMatcher("/filter/**").authorizeRequests(authorize -> authorize.anyRequest().authenticated())
.build();
return http.antMatcher("/filter/**")
.authorizeRequests((authorize) -> authorize.anyRequest().authenticated()).build();
}
@Order(1)
@@ -665,7 +665,7 @@ public class WebSecurityConfigurationTests {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/config/**").authorizeRequests(authorize -> authorize.anyRequest().permitAll());
http.antMatcher("/config/**").authorizeRequests((authorize) -> authorize.anyRequest().permitAll());
}
}

View File

@@ -103,7 +103,7 @@ public class AnonymousConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous(anonymous ->
.anonymous((anonymous) ->
anonymous
.principal("principal")
);
@@ -119,7 +119,7 @@ public class AnonymousConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().permitAll()
)
@@ -145,7 +145,7 @@ public class AnonymousConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().permitAll()
)

View File

@@ -393,7 +393,7 @@ public class AuthorizeRequestsTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.antMatchers(HttpMethod.POST).denyAll()
);
@@ -533,7 +533,7 @@ public class AuthorizeRequestsTests {
// @formatter:off
http
.httpBasic(withDefaults())
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.mvcMatchers("/path").denyAll()
);
@@ -605,7 +605,7 @@ public class AuthorizeRequestsTests {
// @formatter:off
http
.httpBasic(withDefaults())
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.mvcMatchers("/path").servletPath("/spring").denyAll()
);
@@ -677,7 +677,7 @@ public class AuthorizeRequestsTests {
// @formatter:off
http
.httpBasic(withDefaults())
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.mvcMatchers("/user/{userName}").access("#userName == 'user'")
);

View File

@@ -151,7 +151,7 @@ public class ChannelSecurityConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel(requiresChannel ->
.requiresChannel((requiresChannel) ->
requiresChannel
.anyRequest().requiresSecure()
);

View File

@@ -244,7 +244,7 @@ public class CorsConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
@@ -298,7 +298,7 @@ public class CorsConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
@@ -351,7 +351,7 @@ public class CorsConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)

View File

@@ -93,7 +93,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@EnableWebSecurity
static class IgnoringRequestMatchers extends WebSecurityConfigurerAdapter {
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@@ -110,13 +110,13 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@EnableWebSecurity
static class IgnoringRequestInLambdaMatchers extends WebSecurityConfigurerAdapter {
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf(csrf ->
.csrf((csrf) ->
csrf
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/path"))
.ignoringRequestMatchers(this.requestMatcher)
@@ -129,7 +129,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@EnableWebSecurity
static class IgnoringPathsAndMatchers extends WebSecurityConfigurerAdapter {
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
@@ -146,13 +146,13 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@EnableWebSecurity
static class IgnoringPathsAndMatchersInLambdaConfig extends WebSecurityConfigurerAdapter {
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf(csrf ->
.csrf((csrf) ->
csrf
.ignoringAntMatchers("/no-csrf")
.ignoringRequestMatchers(this.requestMatcher)

View File

@@ -558,7 +558,7 @@ public class CsrfConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf(csrf -> csrf.requireCsrfProtectionMatcher(MATCHER));
.csrf((csrf) -> csrf.requireCsrfProtectionMatcher(MATCHER));
// @formatter:on
}
@@ -601,7 +601,7 @@ public class CsrfConfigurerTests {
// @formatter:off
http
.formLogin(withDefaults())
.csrf(csrf -> csrf.csrfTokenRepository(REPO));
.csrf((csrf) -> csrf.csrfTokenRepository(REPO));
// @formatter:on
}

View File

@@ -87,8 +87,8 @@ public class DefaultFiltersTests {
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
assertThat(filterChain.getFilters().size()).isEqualTo(1);
long filter = filterChain.getFilters().stream().filter(it -> it instanceof UsernamePasswordAuthenticationFilter)
.count();
long filter = filterChain.getFilters().stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
assertThat(filter).isEqualTo(1);
}

View File

@@ -325,7 +325,7 @@ public class DefaultLoginPageConfigurerTests {
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChain.getFilterChains().get(0).getFilters().stream()
.filter(filter -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())
.isZero();
}

View File

@@ -116,11 +116,11 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
)
.exceptionHandling(exceptionHandling ->
.exceptionHandling((exceptionHandling) ->
exceptionHandling
.defaultAccessDeniedHandlerFor(
this.teapotDeniedHandler,

View File

@@ -229,7 +229,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasIpAddressConfiguredAndIpAddressMatchesThenRespondsWithOk() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(request -> {
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.0");
return request;
})).andExpect(status().isOk());
@@ -239,7 +239,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasIpAddressConfiguredAndIpAddressDoesNotMatchThenRespondsWithUnauthorized() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(request -> {
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.1");
return request;
})).andExpect(status().isUnauthorized());

View File

@@ -392,7 +392,7 @@ public class FormLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
@@ -456,11 +456,11 @@ public class FormLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.formLogin(formLogin ->
.formLogin((formLogin) ->
formLogin
.loginPage("/authenticate")
.permitAll()
@@ -514,18 +514,18 @@ public class FormLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.formLogin(formLogin ->
.formLogin((formLogin) ->
formLogin
.loginProcessingUrl("/loginCheck")
.loginPage("/login")
.defaultSuccessUrl("/", true)
.permitAll()
)
.logout(logout ->
.logout((logout) ->
logout
.logoutSuccessUrl("/login")
.logoutUrl("/logout")

View File

@@ -486,7 +486,7 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.contentTypeOptions(withDefaults())
@@ -548,7 +548,7 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.cacheControl(withDefaults())
@@ -580,7 +580,7 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.xssProtection(withDefaults())
@@ -611,9 +611,9 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.frameOptions(frameOptionsConfig -> frameOptionsConfig.sameOrigin())
.frameOptions((frameOptionsConfig) -> frameOptionsConfig.sameOrigin())
);
// @formatter:on
}
@@ -763,10 +763,10 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.httpPublicKeyPinning(hpkp ->
.httpPublicKeyPinning((hpkp) ->
hpkp
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
.reportUri("https://example.net/pkp-report")
@@ -815,10 +815,10 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.contentSecurityPolicy(csp ->
.contentSecurityPolicy((csp) ->
csp
.policyDirectives("default-src 'self'; script-src trustedscripts.example.com")
.reportOnly()
@@ -851,10 +851,10 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.contentSecurityPolicy(csp ->
.contentSecurityPolicy((csp) ->
csp.policyDirectives("")
)
);
@@ -870,7 +870,7 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.contentSecurityPolicy(withDefaults())
@@ -902,7 +902,7 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.referrerPolicy()
@@ -934,10 +934,10 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.referrerPolicy(referrerPolicy ->
.referrerPolicy((referrerPolicy) ->
referrerPolicy.policy(ReferrerPolicy.SAME_ORIGIN)
)
);
@@ -999,10 +999,10 @@ public class HeadersConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers(headers ->
.headers((headers) ->
headers
.defaultsDisabled()
.httpStrictTransportSecurity(hstsConfig -> hstsConfig.preload(true))
.httpStrictTransportSecurity((hstsConfig) -> hstsConfig.preload(true))
);
// @formatter:on
}

View File

@@ -153,7 +153,7 @@ public class HttpBasicConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)

View File

@@ -302,12 +302,12 @@ public class HttpSecurityRequestMatchersTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers(requestMatchers ->
.requestMatchers((requestMatchers) ->
requestMatchers
.mvcMatchers("/path")
)
.httpBasic(withDefaults())
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
);
@@ -374,13 +374,13 @@ public class HttpSecurityRequestMatchersTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers(requestMatchers ->
.requestMatchers((requestMatchers) ->
requestMatchers
.mvcMatchers("/path").servletPath("/spring")
.mvcMatchers("/never-match")
)
.httpBasic(withDefaults())
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
);

View File

@@ -81,7 +81,7 @@ public class JeeConfigurerTests {
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
@@ -94,7 +94,7 @@ public class JeeConfigurerTests {
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
@@ -107,7 +107,7 @@ public class JeeConfigurerTests {
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with(request -> {
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
@@ -125,7 +125,7 @@ public class JeeConfigurerTests {
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
.willReturn(userDetails);
this.mvc.perform(get("/").principal(user).with(request -> {
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
@@ -184,11 +184,11 @@ public class JeeConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.jee(jee ->
.jee((jee) ->
jee
.mappableRoles("USER")
);
@@ -204,11 +204,11 @@ public class JeeConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.jee(jee ->
.jee((jee) ->
jee
.mappableAuthorities("ROLE_USER")
);
@@ -227,11 +227,11 @@ public class JeeConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.jee(jee ->
.jee((jee) ->
jee
.authenticatedUserDetailsService(authenticationUserDetailsService)
);

View File

@@ -267,7 +267,7 @@ public class LogoutConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout(logout ->
.logout((logout) ->
logout.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class))
);
// @formatter:on
@@ -296,7 +296,7 @@ public class LogoutConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout(logout ->
.logout((logout) ->
logout.defaultLogoutSuccessHandlerFor(mock(LogoutSuccessHandler.class), null)
);
// @formatter:on
@@ -397,7 +397,7 @@ public class LogoutConfigurerTests {
http
.csrf()
.disable()
.logout(logout -> logout.logoutUrl("/custom/logout"));
.logout((logout) -> logout.logoutUrl("/custom/logout"));
// @formatter:on
}
@@ -424,7 +424,7 @@ public class LogoutConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout(logout -> logout.addLogoutHandler(null));
.logout((logout) -> logout.addLogoutHandler(null));
// @formatter:on
}

View File

@@ -198,7 +198,7 @@ public class NamespaceHttpAnonymousTests {
Optional<AnonymousAuthenticationToken> anonymousToken() {
return Optional.of(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication)
.filter(a -> a instanceof AnonymousAuthenticationToken)
.filter((a) -> a instanceof AnonymousAuthenticationToken)
.map(AnonymousAuthenticationToken.class::cast);
}

View File

@@ -199,7 +199,7 @@ public class NamespaceHttpBasicTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
@@ -232,11 +232,11 @@ public class NamespaceHttpBasicTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.httpBasic(httpBasicConfig -> httpBasicConfig.realmName("Custom Realm"));
.httpBasic((httpBasicConfig) -> httpBasicConfig.realmName("Custom Realm"));
// @formatter:on
}
@@ -274,7 +274,7 @@ public class NamespaceHttpBasicTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic(httpBasicConfig ->
.httpBasic((httpBasicConfig) ->
httpBasicConfig.authenticationDetailsSource(this.authenticationDetailsSource));
// @formatter:on
}
@@ -314,11 +314,11 @@ public class NamespaceHttpBasicTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.httpBasic(httpBasicConfig ->
.httpBasic((httpBasicConfig) ->
httpBasicConfig.authenticationEntryPoint(this.authenticationEntryPoint));
// @formatter:on
}

View File

@@ -153,7 +153,7 @@ public class NamespaceHttpHeadersTests {
}
private static ResultMatcher includes(Map<String, String> headers, String... headerNames) {
return result -> {
return (result) -> {
assertThat(result.getResponse().getHeaderNames()).hasSameSizeAs(headerNames);
for (String headerName : headerNames) {
header().string(headerName, headers.get(headerName)).match(result);

View File

@@ -66,7 +66,7 @@ public class NamespaceHttpJeeTests {
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with(request -> {
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("ROLE_admin");
request.addUserRole("ROLE_user");
request.addUserRole("ROLE_unmapped");

View File

@@ -95,7 +95,7 @@ public class NamespaceHttpLogoutTests {
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/logout-success"))
.andExpect(result -> assertThat(result.getResponse().getCookies()).hasSize(1))
.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
.andExpect(cookie().maxAge("remove", 0)).andExpect(session(Objects::nonNull));
}
@@ -106,7 +106,7 @@ public class NamespaceHttpLogoutTests {
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/logout-success"))
.andExpect(result -> assertThat(result.getResponse().getCookies()).hasSize(1))
.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
.andExpect(cookie().maxAge("remove", 0)).andExpect(session(Objects::nonNull));
}
@@ -134,16 +134,16 @@ public class NamespaceHttpLogoutTests {
}
ResultMatcher authenticated(boolean authenticated) {
return result -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
return (result) -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(Authentication::isAuthenticated).orElse(false)).isEqualTo(authenticated);
}
ResultMatcher noCookies() {
return result -> assertThat(result.getResponse().getCookies()).isEmpty();
return (result) -> assertThat(result.getResponse().getCookies()).isEmpty();
}
ResultMatcher session(Predicate<HttpSession> sessionPredicate) {
return result -> assertThat(result.getRequest().getSession(false))
return (result) -> assertThat(result.getRequest().getSession(false))
.is(new Condition<>(sessionPredicate, "sessionPredicate failed"));
}
@@ -190,7 +190,7 @@ public class NamespaceHttpLogoutTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.logout(logout ->
.logout((logout) ->
logout.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutUrl("/custom-logout")
@@ -227,7 +227,7 @@ public class NamespaceHttpLogoutTests {
// @formatter:off
http
.logout(logout -> logout.logoutSuccessHandler(logoutSuccessHandler));
.logout((logout) -> logout.logoutSuccessHandler(logoutSuccessHandler));
// @formatter:on
}

View File

@@ -120,13 +120,13 @@ public class NamespaceHttpOpenIDLoginTests {
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
assertThat(attributeObject).isInstanceOf(List.class);
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
assertThat(attributeList.stream().anyMatch(attribute -> "firstname".equals(attribute.getName())
assertThat(attributeList.stream().anyMatch((attribute) -> "firstname".equals(attribute.getName())
&& "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired()))
.isTrue();
assertThat(attributeList.stream().anyMatch(attribute -> "lastname".equals(attribute.getName())
assertThat(attributeList.stream().anyMatch((attribute) -> "lastname".equals(attribute.getName())
&& "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired()))
.isTrue();
assertThat(attributeList.stream().anyMatch(attribute -> "email".equals(attribute.getName())
assertThat(attributeList.stream().anyMatch((attribute) -> "email".equals(attribute.getName())
&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
.isTrue();
}

View File

@@ -124,11 +124,11 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
)
.exceptionHandling(exceptionHandling ->
.exceptionHandling((exceptionHandling) ->
exceptionHandling.accessDeniedPage("/AccessDeniedPageConfig")
);
// @formatter:on
@@ -167,11 +167,11 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
)
.exceptionHandling(exceptionHandling ->
.exceptionHandling((exceptionHandling) ->
exceptionHandling.accessDeniedHandler(accessDeniedHandler())
);
// @formatter:on

View File

@@ -273,7 +273,7 @@ public class NamespaceHttpX509Tests {
.anyRequest().hasRole("USER")
.and()
.x509()
.userDetailsService(username -> USER);
.userDetailsService((username) -> USER);
// @formatter:on
}
@@ -296,7 +296,7 @@ public class NamespaceHttpX509Tests {
.anyRequest().hasRole("USER")
.and()
.x509()
.authenticationUserDetailsService(authentication -> USER);
.authenticationUserDetailsService((authentication) -> USER);
// @formatter:on
}

View File

@@ -244,7 +244,7 @@ public class NamespaceRememberMeTests {
}
static RequestPostProcessor rememberMeLogin(String parameterName, boolean parameterValue) {
return request -> {
return (request) -> {
csrf().postProcessRequest(request);
request.setParameter("username", "user");
request.setParameter("password", "password");

View File

@@ -96,7 +96,7 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingInvalidSessionUrlThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class).autowire();
this.mvc.perform(get("/auth").with(request -> {
this.mvc.perform(get("/auth").with((request) -> {
request.setRequestedSessionIdValid(false);
request.setRequestedSessionId("id");
return request;
@@ -137,7 +137,7 @@ public class NamespaceSessionManagementTests {
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
mock.setMethod("GET");
this.mvc.perform(get("/auth").with(request -> mock).with(httpBasic("user", "password")))
this.mvc.perform(get("/auth").with((request) -> mock).with(httpBasic("user", "password")))
.andExpect(redirectedUrl("/session-auth-error"));
}
@@ -158,7 +158,7 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingCustomInvalidSessionStrategyThenMatchesNamespace() throws Exception {
this.spring.register(InvalidSessionStrategyConfig.class).autowire();
this.mvc.perform(get("/auth").with(request -> {
this.mvc.perform(get("/auth").with((request) -> {
request.setRequestedSessionIdValid(false);
request.setRequestedSessionId("id");
return request;

View File

@@ -91,11 +91,11 @@ public class PortMapperConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requiresChannel(requiresChannel ->
.requiresChannel((requiresChannel) ->
requiresChannel
.anyRequest().requiresSecure()
)
.portMapper(portMapper ->
.portMapper((portMapper) ->
portMapper
.http(543).mapsTo(123)
);
@@ -113,11 +113,11 @@ public class PortMapperConfigurerTests {
customPortMapper.setPortMappings(Collections.singletonMap("543", "123"));
// @formatter:off
http
.requiresChannel(requiresChannel ->
.requiresChannel((requiresChannel) ->
requiresChannel
.anyRequest().requiresSecure()
)
.portMapper(portMapper ->
.portMapper((portMapper) ->
portMapper
.portMapper(customPortMapper)
);

View File

@@ -121,7 +121,7 @@ public class RememberMeConfigurerTests {
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
.withAuthentication(auth -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
}
@Test
@@ -196,7 +196,7 @@ public class RememberMeConfigurerTests {
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
.withAuthentication(auth -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
}
@EnableWebSecurity
@@ -334,7 +334,7 @@ public class RememberMeConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
@@ -389,12 +389,12 @@ public class RememberMeConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().hasRole("USER")
)
.formLogin(withDefaults())
.rememberMe(rememberMe ->
.rememberMe((rememberMe) ->
rememberMe
.rememberMeCookieDomain("spring.io")
);

View File

@@ -333,7 +333,7 @@ public class RequestCacheConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
@@ -351,7 +351,7 @@ public class RequestCacheConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
@@ -369,12 +369,12 @@ public class RequestCacheConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.requestCache(requestCache ->
.requestCache((requestCache) ->
requestCache
.requestCache(new NullRequestCache())
);

View File

@@ -87,15 +87,15 @@ public class RequestMatcherConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.requestMatchers(requestMatchers ->
.requestMatchers((requestMatchers) ->
requestMatchers
.antMatchers("/api/**")
)
.requestMatchers(requestMatchers ->
.requestMatchers((requestMatchers) ->
requestMatchers
.antMatchers("/oauth/**")
)
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().denyAll()
);

View File

@@ -252,7 +252,7 @@ public class SecurityContextConfigurerTests {
// @formatter:off
http
.formLogin(withDefaults())
.securityContext(securityContext ->
.securityContext((securityContext) ->
securityContext
.securityContextRepository(new NullSecurityContextRepository())
);

View File

@@ -343,7 +343,7 @@ public class ServletApiConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi(servletApi ->
.servletApi((servletApi) ->
servletApi
.rolePrefix("PERMISSION_")
);

View File

@@ -362,9 +362,9 @@ public class SessionManagementConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement(sessionManagement ->
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionFixation(sessionFixation ->
.sessionFixation((sessionFixation) ->
sessionFixation.newSession()
)
)
@@ -417,9 +417,9 @@ public class SessionManagementConfigurerTests {
// @formatter:off
http
.formLogin(withDefaults())
.sessionManagement(sessionManagement ->
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionConcurrency(sessionConcurrency ->
.sessionConcurrency((sessionConcurrency) ->
sessionConcurrency
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
@@ -446,7 +446,7 @@ public class SessionManagementConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement(sessionManagement ->
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);

View File

@@ -182,7 +182,7 @@ public class X509ConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.x509(x509 ->
.x509((x509) ->
x509
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)")
);

View File

@@ -233,7 +233,7 @@ public class OAuth2ClientConfigurerTests {
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver;
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
given(authorizationRequestResolver.resolve(any()))
.willAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
.willAnswer((invocation) -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
this.spring.register(OAuth2ClientConfig.class).autowire();
@@ -295,7 +295,7 @@ public class OAuth2ClientConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)

View File

@@ -586,7 +586,7 @@ public class OAuth2LoginConfigurerTests {
}
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createOauth2AccessTokenResponseClient() {
return request -> {
return (request) -> {
Map<String, Object> additionalParameters = new HashMap<>();
if (request.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
additionalParameters.put(OidcParameterNames.ID_TOKEN, "token123");
@@ -598,17 +598,17 @@ public class OAuth2LoginConfigurerTests {
private static OAuth2UserService<OAuth2UserRequest, OAuth2User> createOauth2UserService() {
Map<String, Object> userAttributes = Collections.singletonMap("name", "spring");
return request -> new DefaultOAuth2User(Collections.singleton(new OAuth2UserAuthority(userAttributes)),
return (request) -> new DefaultOAuth2User(Collections.singleton(new OAuth2UserAuthority(userAttributes)),
userAttributes, "name");
}
private static OAuth2UserService<OidcUserRequest, OidcUser> createOidcUserService() {
OidcIdToken idToken = TestOidcIdTokens.idToken().build();
return request -> new DefaultOidcUser(Collections.singleton(new OidcUserAuthority(idToken)), idToken);
return (request) -> new DefaultOidcUser(Collections.singleton(new OidcUserAuthority(idToken)), idToken);
}
private static GrantedAuthoritiesMapper createGrantedAuthoritiesMapper() {
return authorities -> {
return (authorities) -> {
boolean isOidc = OidcUserAuthority.class.isInstance(authorities.iterator().next());
List<GrantedAuthority> mappedAuthorities = new ArrayList<>(authorities);
mappedAuthorities.add(new SimpleGrantedAuthority(isOidc ? "ROLE_OIDC_USER" : "ROLE_OAUTH2_USER"));
@@ -650,7 +650,7 @@ public class OAuth2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login(oauth2Login ->
.oauth2Login((oauth2Login) ->
oauth2Login
.clientRegistrationRepository(
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
@@ -811,10 +811,10 @@ public class OAuth2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login(oauth2Login ->
.oauth2Login((oauth2Login) ->
oauth2Login
.clientRegistrationRepository(this.clientRegistrationRepository)
.authorizationEndpoint(authorizationEndpoint ->
.authorizationEndpoint((authorizationEndpoint) ->
authorizationEndpoint
.authorizationRequestResolver(this.resolver)
)
@@ -866,7 +866,7 @@ public class OAuth2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.oauth2Login(oauth2Login ->
.oauth2Login((oauth2Login) ->
oauth2Login
.clientRegistrationRepository(
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
@@ -945,21 +945,21 @@ public class OAuth2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.securityContext(securityContext ->
.securityContext((securityContext) ->
securityContext
.securityContextRepository(securityContextRepository())
)
.oauth2Login(oauth2Login ->
.oauth2Login((oauth2Login) ->
oauth2Login
.tokenEndpoint(tokenEndpoint ->
.tokenEndpoint((tokenEndpoint) ->
tokenEndpoint
.accessTokenResponseClient(createOauth2AccessTokenResponseClient())
)
.userInfoEndpoint(userInfoEndpoint ->
.userInfoEndpoint((userInfoEndpoint) ->
userInfoEndpoint
.userService(createOauth2UserService())
.oidcUserService(createOidcUserService())
@@ -985,7 +985,7 @@ public class OAuth2LoginConfigurerTests {
@Bean
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory() {
return clientRegistration -> getJwtDecoder();
return (clientRegistration) -> getJwtDecoder();
}
private static JwtDecoder getJwtDecoder() {
@@ -994,7 +994,7 @@ public class OAuth2LoginConfigurerTests {
claims.put(IdTokenClaimNames.ISS, "http://localhost/iss");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("clientId", "a", "u", "d"));
claims.put(IdTokenClaimNames.AZP, "clientId");
Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
Jwt jwt = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
given(jwtDecoder.decode(any())).willReturn(jwt);
return jwtDecoder;
@@ -1007,12 +1007,12 @@ public class OAuth2LoginConfigurerTests {
@Bean
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory1() {
return clientRegistration -> JwtDecoderFactoryConfig.getJwtDecoder();
return (clientRegistration) -> JwtDecoderFactoryConfig.getJwtDecoder();
}
@Bean
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory2() {
return clientRegistration -> JwtDecoderFactoryConfig.getJwtDecoder();
return (clientRegistration) -> JwtDecoderFactoryConfig.getJwtDecoder();
}
}

View File

@@ -1404,12 +1404,12 @@ public class OAuth2ResourceServerConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(withDefaults())
);
@@ -1450,14 +1450,14 @@ public class OAuth2ResourceServerConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(jwt ->
.jwt((jwt) ->
jwt
.jwkSetUri(this.jwkSetUri)
)
@@ -1601,7 +1601,7 @@ public class OAuth2ResourceServerConfigurerTests {
.anyRequest().denyAll()
.and()
.exceptionHandling()
.defaultAccessDeniedHandlerFor(new AccessDeniedHandlerImpl(), request -> false)
.defaultAccessDeniedHandlerFor(new AccessDeniedHandlerImpl(), (request) -> false)
.and()
.httpBasic()
.and()
@@ -1668,7 +1668,7 @@ public class OAuth2ResourceServerConfigurerTests {
Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(
jwt -> Collections.singletonList(new SimpleGrantedAuthority("message:read")));
(jwt) -> Collections.singletonList(new SimpleGrantedAuthority("message:read")));
return converter;
}
@@ -1871,13 +1871,13 @@ public class OAuth2ResourceServerConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(jwt ->
.jwt((jwt) ->
jwt
.decoder(decoder())
)
@@ -2091,12 +2091,12 @@ public class OAuth2ResourceServerConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.antMatchers("/requires-read-scope").hasAuthority("SCOPE_message:read")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.opaqueToken(withDefaults())
);
@@ -2135,13 +2135,13 @@ public class OAuth2ResourceServerConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.opaqueToken(opaqueToken ->
.opaqueToken((opaqueToken) ->
opaqueToken
.authenticationManager(authenticationProvider()::authenticate)
)

View File

@@ -127,11 +127,11 @@ public class OpenIDLoginConfigurerTests {
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
assertThat(
attributeList.stream()
.anyMatch(attribute -> "nickname".equals(attribute.getName())
.anyMatch((attribute) -> "nickname".equals(attribute.getName())
&& "https://schema.openid.net/namePerson/friendly".equals(attribute.getType())))
.isTrue();
assertThat(attributeList.stream()
.anyMatch(attribute -> "email".equals(attribute.getName())
.anyMatch((attribute) -> "email".equals(attribute.getName())
&& "https://schema.openid.net/contact/email".equals(attribute.getType())
&& attribute.isRequired() && attribute.getCount() == 2)).isTrue();
}
@@ -231,11 +231,11 @@ public class OpenIDLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().authenticated()
)
.openidLogin(openIdLogin ->
.openidLogin((openIdLogin) ->
openIdLogin
.loginPage("/login/custom")
);
@@ -253,22 +253,22 @@ public class OpenIDLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().permitAll()
)
.openidLogin(openIdLogin ->
.openidLogin((openIdLogin) ->
openIdLogin
.consumerManager(CONSUMER_MANAGER)
.attributeExchange(attributeExchange ->
.attributeExchange((attributeExchange) ->
attributeExchange
.identifierPattern(".*")
.attribute(nicknameAttribute ->
.attribute((nicknameAttribute) ->
nicknameAttribute
.name("nickname")
.type("https://schema.openid.net/namePerson/friendly")
)
.attribute(emailAttribute ->
.attribute((emailAttribute) ->
emailAttribute
.name("email")
.type("https://schema.openid.net/contact/email")
@@ -291,14 +291,14 @@ public class OpenIDLoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authorizeRequests ->
.authorizeRequests((authorizeRequests) ->
authorizeRequests
.anyRequest().permitAll()
)
.openidLogin(openIdLogin ->
.openidLogin((openIdLogin) ->
openIdLogin
.consumerManager(CONSUMER_MANAGER)
.attributeExchange(attributeExchange ->
.attributeExchange((attributeExchange) ->
attributeExchange
.identifierPattern(".*")
.attribute(withDefaults())

View File

@@ -102,10 +102,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
*/
public class Saml2LoginConfigurerTests {
private static final Converter<Assertion, Collection<? extends GrantedAuthority>> AUTHORITIES_EXTRACTOR = a -> Arrays
.asList(new SimpleGrantedAuthority("TEST"));
private static final Converter<Assertion, Collection<? extends GrantedAuthority>> AUTHORITIES_EXTRACTOR = (
a) -> Arrays.asList(new SimpleGrantedAuthority("TEST"));
private static final GrantedAuthoritiesMapper AUTHORITIES_MAPPER = authorities -> Arrays
private static final GrantedAuthoritiesMapper AUTHORITIES_MAPPER = (authorities) -> Arrays
.asList(new SimpleGrantedAuthority("TEST CONVERTED"));
private static final Duration RESPONSE_TIME_VALIDATION_SKEW = Duration.ZERO;
@@ -194,8 +194,8 @@ public class Saml2LoginConfigurerTests {
public void authenticateWhenCustomAuthenticationConverterThenUses() throws Exception {
this.spring.register(CustomAuthenticationConverter.class).autowire();
RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials()
.assertingPartyDetails(party -> party.verificationX509Credentials(
c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
.assertingPartyDetails((party) -> party.verificationX509Credentials(
(c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
.build();
String response = new String(samlDecode(SIGNED_RESPONSE));
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
@@ -212,7 +212,7 @@ public class Saml2LoginConfigurerTests {
"authenticationManager");
ProviderManager pm = (ProviderManager) manager;
AuthenticationProvider provider = pm.getProviders().stream()
.filter(p -> p instanceof OpenSamlAuthenticationProvider).findFirst().get();
.filter((p) -> p instanceof OpenSamlAuthenticationProvider).findFirst().get();
Assert.assertSame(AUTHORITIES_EXTRACTOR, ReflectionTestUtils.getField(provider, "authoritiesExtractor"));
Assert.assertSame(AUTHORITIES_MAPPER, ReflectionTestUtils.getField(provider, "authoritiesMapper"));
Assert.assertSame(RESPONSE_TIME_VALIDATION_SKEW,
@@ -221,7 +221,7 @@ public class Saml2LoginConfigurerTests {
private Saml2WebSsoAuthenticationFilter getSaml2SsoFilter(FilterChainProxy chain) {
return (Saml2WebSsoAuthenticationFilter) chain.getFilters("/login/saml2/sso/test").stream()
.filter(f -> f instanceof Saml2WebSsoAuthenticationFilter).findFirst().get();
.filter((f) -> f instanceof Saml2WebSsoAuthenticationFilter).findFirst().get();
}
private void performSaml2Login(String expected) throws IOException, ServletException {
@@ -324,7 +324,7 @@ public class Saml2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authz -> authz
.authorizeRequests((authz) -> authz
.anyRequest().authenticated()
)
.saml2Login(withDefaults());
@@ -346,10 +346,10 @@ public class Saml2LoginConfigurerTests {
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests(authz -> authz
.authorizeRequests((authz) -> authz
.anyRequest().authenticated()
)
.saml2Login(saml2 -> {});
.saml2Login((saml2) -> {});
// @formatter:on
}
@@ -357,7 +357,7 @@ public class Saml2LoginConfigurerTests {
Saml2AuthenticationRequestFactory authenticationRequestFactory() {
OpenSamlAuthenticationRequestFactory authenticationRequestFactory = new OpenSamlAuthenticationRequestFactory();
authenticationRequestFactory
.setAuthnRequestConsumerResolver(context -> authnRequest -> authnRequest.setForceAuthn(true));
.setAuthnRequestConsumerResolver((context) -> (authnRequest) -> authnRequest.setForceAuthn(true));
return authenticationRequestFactory;
}
@@ -371,8 +371,8 @@ public class Saml2LoginConfigurerTests {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(authz -> authz.anyRequest().authenticated())
.saml2Login(saml2 -> saml2.authenticationConverter(authenticationConverter));
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
}
}

View File

@@ -112,7 +112,7 @@ public class EnableWebFluxSecurityTests {
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain).build();
FluxExchangeResult<String> result = client.get().headers(headers -> headers.setBasicAuth("user", "password"))
FluxExchangeResult<String> result = client.get().headers((headers) -> headers.setBasicAuth("user", "password"))
.exchange().expectStatus().isOk().returnResult(String.class);
result.assertWithDiagnostics(() -> assertThat(result.getResponseCookies().isEmpty()));
}
@@ -126,16 +126,16 @@ public class EnableWebFluxSecurityTests {
WebTestClient client = WebTestClientBuilder
.bindToWebFilters(
(exchange, chain) -> contextRepository.save(exchange, context)
.switchIfEmpty(chain.filter(exchange)).flatMap(e -> chain.filter(exchange)),
.switchIfEmpty(chain.filter(exchange)).flatMap((e) -> chain.filter(exchange)),
this.springSecurityFilterChain,
(exchange,
chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
.build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class)
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo(currentPrincipal.getName()));
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo(currentPrincipal.getName()));
}
@Test
@@ -145,13 +145,13 @@ public class EnableWebFluxSecurityTests {
.bindToWebFilters(this.springSecurityFilterChain,
(exchange,
chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
.build();
client.get().uri("/").headers(headers -> headers.setBasicAuth("user", "password")).exchange().expectStatus()
client.get().uri("/").headers((headers) -> headers.setBasicAuth("user", "password")).exchange().expectStatus()
.isOk().expectBody(String.class)
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("user"));
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
}
@Test
@@ -171,13 +171,13 @@ public class EnableWebFluxSecurityTests {
.bindToWebFilters(this.springSecurityFilterChain,
(exchange,
chain) -> ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
.build();
client.get().uri("/").headers(headers -> headers.setBasicAuth("user", "password")).exchange().expectStatus()
client.get().uri("/").headers((headers) -> headers.setBasicAuth("user", "password")).exchange().expectStatus()
.isOk().expectBody(String.class)
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("user"));
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
}
@Test
@@ -185,7 +185,7 @@ public class EnableWebFluxSecurityTests {
this.spring.register(MapReactiveUserDetailsServiceConfig.class).autowire();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain).build();
client.get().uri("/").headers(h -> h.setBasicAuth("user", "password")).exchange().expectStatus().isOk();
client.get().uri("/").headers((h) -> h.setBasicAuth("user", "password")).exchange().expectStatus().isOk();
ReactiveUserDetailsService users = this.spring.getContext().getBean(ReactiveUserDetailsService.class);
assertThat(users.findByUsername("user").block().getPassword()).startsWith("{bcrypt}");
@@ -195,8 +195,8 @@ public class EnableWebFluxSecurityTests {
public void formLoginWorks() {
this.spring.register(Config.class).autowire();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain, (exchange,
chain) -> Mono.subscriberContext().flatMap(c -> c.<Mono<Principal>>get(Authentication.class)).flatMap(
principal -> exchange.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
chain) -> Mono.subscriberContext().flatMap((c) -> c.<Mono<Principal>>get(Authentication.class)).flatMap(
(principal) -> exchange.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
.build();
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();

View File

@@ -146,7 +146,7 @@ public class RsaKeyConversionServicePostProcessorTests {
@Bean
BeanFactoryPostProcessor conversionServiceCustomizer() {
return beanFactory -> beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
return (beanFactory) -> beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
.setResourceLoader(new CustomResourceLoader());
}
@@ -158,7 +158,7 @@ public class RsaKeyConversionServicePostProcessorTests {
@Bean
ConversionService conversionService() {
GenericConversionService service = new GenericConversionService();
service.addConverter(String.class, RSAPublicKey.class, source -> {
service.addConverter(String.class, RSAPublicKey.class, (source) -> {
throw new IllegalArgumentException("unsupported");
});
return service;

View File

@@ -130,9 +130,9 @@ public class Element {
Collection<String> ids = new ArrayList<>();
ids.add(getId());
this.childElmts.values().forEach(elmt -> ids.add(elmt.getId()));
this.childElmts.values().forEach((elmt) -> ids.add(elmt.getId()));
this.attrs.forEach(attr -> ids.add(attr.getId()));
this.attrs.forEach((attr) -> ids.add(attr.getId()));
if (!this.childElmts.isEmpty()) {
ids.add(getId() + "-children");
@@ -152,7 +152,8 @@ public class Element {
public Map<String, Element> getAllChildElmts() {
Map<String, Element> result = new HashMap<>();
this.childElmts.values().forEach(elmt -> elmt.subGrps.forEach(subElmt -> result.put(subElmt.name, subElmt)));
this.childElmts.values()
.forEach((elmt) -> elmt.subGrps.forEach((subElmt) -> result.put(subElmt.name, subElmt)));
result.putAll(this.childElmts);
@@ -162,7 +163,8 @@ public class Element {
public Map<String, Element> getAllParentElmts() {
Map<String, Element> result = new HashMap<>();
this.parentElmts.values().forEach(elmt -> elmt.subGrps.forEach(subElmt -> result.put(subElmt.name, subElmt)));
this.parentElmts.values()
.forEach((elmt) -> elmt.subGrps.forEach((subElmt) -> result.put(subElmt.name, subElmt)));
result.putAll(this.parentElmts);

View File

@@ -61,7 +61,7 @@ public class SpringSecurityXsdParser {
private Map<String, Element> elements(XmlNode node) {
Map<String, Element> elementNameToElement = new HashMap<>();
node.children().forEach(child -> {
node.children().forEach((child) -> {
if ("element".equals(child.simpleName())) {
Element e = elmt(child);
elementNameToElement.put(e.getName(), e);
@@ -81,7 +81,7 @@ public class SpringSecurityXsdParser {
*/
private Collection<Attribute> attrs(XmlNode element) {
Collection<Attribute> attrs = new ArrayList<>();
element.children().forEach(c -> {
element.children().forEach((c) -> {
String name = c.simpleName();
if ("attribute".equals(name)) {
attrs.add(attr(c));
@@ -103,7 +103,7 @@ public class SpringSecurityXsdParser {
private Collection<Attribute> attrgrps(XmlNode element) {
Collection<Attribute> attrgrp = new ArrayList<>();
element.children().forEach(c -> {
element.children().forEach((c) -> {
if (!"element".equals(c.simpleName())) {
if ("attributeGroup".equals(c.simpleName())) {
if (c.attribute("name") != null) {
@@ -130,7 +130,7 @@ public class SpringSecurityXsdParser {
root = root.parent().get();
}
return expand(root).filter(node -> name.equals(node.attribute("name"))).findFirst()
return expand(root).filter((node) -> name.equals(node.attribute("name"))).findFirst()
.orElseThrow(IllegalArgumentException::new);
}
@@ -157,8 +157,8 @@ public class SpringSecurityXsdParser {
* @return
*/
private String desc(XmlNode element) {
return element.child("annotation").flatMap(annotation -> annotation.child("documentation"))
.map(documentation -> documentation.text()).orElse(null);
return element.child("annotation").flatMap((annotation) -> annotation.child("documentation"))
.map((documentation) -> documentation.text()).orElse(null);
}
/**
@@ -197,8 +197,8 @@ public class SpringSecurityXsdParser {
e.setChildElmts(elements(n));
e.setAttrs(attrs(n));
e.getAttrs().addAll(attrgrps(n));
e.getAttrs().forEach(attr -> attr.setElmt(e));
e.getChildElmts().values().forEach(element -> element.getParentElmts().put(e.getName(), e));
e.getAttrs().forEach((attr) -> attr.setElmt(e));
e.getChildElmts().values().forEach((element) -> element.getParentElmts().put(e.getName(), e));
String subGrpName = n.attribute("substitutionGroup");
if (!StringUtils.isEmpty(subGrpName)) {

View File

@@ -50,16 +50,16 @@ public class XmlNode {
}
public Optional<XmlNode> child(String name) {
return this.children().filter(child -> name.equals(child.simpleName())).findFirst();
return this.children().filter((child) -> name.equals(child.simpleName())).findFirst();
}
public Optional<XmlNode> parent() {
return Optional.ofNullable(this.node.getParentNode()).map(parent -> new XmlNode(parent));
return Optional.ofNullable(this.node.getParentNode()).map((parent) -> new XmlNode(parent));
}
public String attribute(String name) {
return Optional.ofNullable(this.node.getAttributes()).map(attrs -> attrs.getNamedItem(name))
.map(attr -> attr.getTextContent()).orElse(null);
return Optional.ofNullable(this.node.getAttributes()).map((attrs) -> attrs.getNamedItem(name))
.map((attr) -> attr.getTextContent()).orElse(null);
}
public Node node() {

View File

@@ -70,9 +70,9 @@ public class XsdDocumentedTests {
XmlNode root = this.xml.parse(this.schemaDocumentLocation);
List<String> nodes = root.child("schema").map(XmlNode::children).orElse(Stream.empty())
.filter(node -> "simpleType".equals(node.simpleName())
.filter((node) -> "simpleType".equals(node.simpleName())
&& "named-security-filter".equals(node.attribute("name")))
.flatMap(XmlNode::children).flatMap(XmlNode::children).map(node -> node.attribute("value"))
.flatMap(XmlNode::children).flatMap(XmlNode::children).map((node) -> node.attribute("value"))
.filter(StringUtils::isNotEmpty).collect(Collectors.toList());
SecurityFiltersAssertions.assertEquals(nodes);
@@ -91,9 +91,9 @@ public class XsdDocumentedTests {
XmlNode root = this.xml.parse(this.schema31xDocumentLocation);
List<String> nodes = root.child("schema").map(XmlNode::children).orElse(Stream.empty())
.filter(node -> "simpleType".equals(node.simpleName())
.filter((node) -> "simpleType".equals(node.simpleName())
&& "named-security-filter".equals(node.attribute("name")))
.flatMap(XmlNode::children).flatMap(XmlNode::children).map(node -> node.attribute("value"))
.flatMap(XmlNode::children).flatMap(XmlNode::children).map((node) -> node.attribute("value"))
.filter(StringUtils::isNotEmpty).collect(Collectors.toList());
assertThat(nodes).isEqualTo(expected);
@@ -129,11 +129,11 @@ public class XsdDocumentedTests {
Map<String, Element> elementsByElementName = this.xml.elementsByElementName(this.schemaDocumentLocation);
List<String> documentIds = Files.lines(Paths.get(this.referenceLocation))
.filter(line -> line.matches("\\[\\[(nsa-.*)\\]\\]")).map(line -> line.substring(2, line.length() - 2))
.collect(Collectors.toList());
.filter((line) -> line.matches("\\[\\[(nsa-.*)\\]\\]"))
.map((line) -> line.substring(2, line.length() - 2)).collect(Collectors.toList());
Set<String> expectedIds = elementsByElementName.values().stream().flatMap(element -> element.getIds().stream())
.collect(Collectors.toSet());
Set<String> expectedIds = elementsByElementName.values().stream()
.flatMap((element) -> element.getIds().stream()).collect(Collectors.toSet());
documentIds.removeAll(this.ignoredIds);
expectedIds.removeAll(this.ignoredIds);
@@ -179,7 +179,7 @@ public class XsdDocumentedTests {
String expression = "^\\* <<(nsa-.*),.*>>$";
if (line.matches(expression)) {
String elmtId = line.replaceAll(expression, "$1");
currentDocAttrNameToElmt.computeIfAbsent(docAttrName, key -> new ArrayList<>()).add(elmtId);
currentDocAttrNameToElmt.computeIfAbsent(docAttrName, (key) -> new ArrayList<>()).add(elmtId);
}
}
}
@@ -189,21 +189,21 @@ public class XsdDocumentedTests {
Map<String, List<String>> schemaAttrNameToChildren = new HashMap<>();
Map<String, List<String>> schemaAttrNameToParents = new HashMap<>();
elementNameToElement.entrySet().stream().forEach(entry -> {
elementNameToElement.entrySet().stream().forEach((entry) -> {
String key = "nsa-" + entry.getKey();
if (this.ignoredIds.contains(key)) {
return;
}
List<String> parentIds = entry.getValue().getAllParentElmts().values().stream()
.filter(element -> !this.ignoredIds.contains(element.getId())).map(element -> element.getId())
.filter((element) -> !this.ignoredIds.contains(element.getId())).map((element) -> element.getId())
.sorted().collect(Collectors.toList());
if (!parentIds.isEmpty()) {
schemaAttrNameToParents.put(key, parentIds);
}
List<String> childIds = entry.getValue().getAllChildElmts().values().stream()
.filter(element -> !this.ignoredIds.contains(element.getId())).map(element -> element.getId())
.filter((element) -> !this.ignoredIds.contains(element.getId())).map((element) -> element.getId())
.sorted().collect(Collectors.toList());
if (!childIds.isEmpty()) {
schemaAttrNameToChildren.put(key, childIds);
@@ -224,12 +224,14 @@ public class XsdDocumentedTests {
Map<String, Element> elementNameToElement = this.xml.elementsByElementName(this.schemaDocumentLocation);
String notDocElmtIds = elementNameToElement.values().stream()
.filter(element -> StringUtils.isEmpty(element.getDesc()) && !this.ignoredIds.contains(element.getId()))
.map(element -> element.getId()).sorted().collect(Collectors.joining("\n"));
.filter((element) -> StringUtils.isEmpty(element.getDesc())
&& !this.ignoredIds.contains(element.getId()))
.map((element) -> element.getId()).sorted().collect(Collectors.joining("\n"));
String notDocAttrIds = elementNameToElement.values().stream().flatMap(element -> element.getAttrs().stream())
.filter(element -> StringUtils.isEmpty(element.getDesc()) && !this.ignoredIds.contains(element.getId()))
.map(element -> element.getId()).sorted().collect(Collectors.joining("\n"));
String notDocAttrIds = elementNameToElement.values().stream().flatMap((element) -> element.getAttrs().stream())
.filter((element) -> StringUtils.isEmpty(element.getDesc())
&& !this.ignoredIds.contains(element.getId()))
.map((element) -> element.getId()).sorted().collect(Collectors.joining("\n"));
assertThat(notDocElmtIds).isEmpty();
assertThat(notDocAttrIds).isEmpty();

View File

@@ -142,7 +142,7 @@ public class CsrfConfigTests {
this.spring.configLocations(this.xml("shared-controllers"), this.xml("AutoConfig")).autowire();
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
.addDispatcherServletCustomizer(dispatcherServlet -> dispatcherServlet.setDispatchTraceRequest(true))
.addDispatcherServletCustomizer((dispatcherServlet) -> dispatcherServlet.setDispatchTraceRequest(true))
.build();
traceEnabled.perform(request(HttpMethod.TRACE, "/csrf-in-header")).andExpect(csrfInHeader());
@@ -219,7 +219,7 @@ public class CsrfConfigTests {
this.spring.configLocations(this.xml("shared-controllers"), this.xml("CsrfEnabled")).autowire();
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
.addDispatcherServletCustomizer(dispatcherServlet -> dispatcherServlet.setDispatchTraceRequest(true))
.addDispatcherServletCustomizer((dispatcherServlet) -> dispatcherServlet.setDispatchTraceRequest(true))
.build();
traceEnabled.perform(request(HttpMethod.TRACE, "/csrf-in-header")).andExpect(csrfInHeader());
@@ -425,11 +425,11 @@ public class CsrfConfigTests {
}
ResultMatcher csrfInHeader() {
return new CsrfReturnedResultMatcher(result -> result.getResponse().getHeader("X-CSRF-TOKEN"));
return new CsrfReturnedResultMatcher((result) -> result.getResponse().getHeader("X-CSRF-TOKEN"));
}
ResultMatcher csrfInBody() {
return new CsrfReturnedResultMatcher(result -> result.getResponse().getContentAsString());
return new CsrfReturnedResultMatcher((result) -> result.getResponse().getContentAsString());
}
@Controller

View File

@@ -126,7 +126,7 @@ public class HttpCorsConfigTests {
}
private ResultMatcher corsResponseHeaders() {
return result -> {
return (result) -> {
header().exists("Access-Control-Allow-Origin").match(result);
header().exists("X-Content-Type-Options").match(result);
};

View File

@@ -659,7 +659,7 @@ public class HttpHeadersConfigTests {
}
private static ResultMatcher includes(Map<String, String> headers) {
return result -> {
return (result) -> {
for (Map.Entry<String, String> header : headers.entrySet()) {
header().string(header.getKey(), header.getValue()).match(result);
}
@@ -671,7 +671,7 @@ public class HttpHeadersConfigTests {
}
private static ResultMatcher excludes(Collection<String> headers) {
return result -> {
return (result) -> {
for (String name : headers) {
header().doesNotExist(name).match(result);
}

View File

@@ -214,7 +214,7 @@ public class InterceptUrlConfigTests {
MockServletContext servletContext = spy(new MockServletContext());
final ServletRegistration registration = mock(ServletRegistration.class);
given(registration.getMappings()).willReturn(Collections.singleton(servletPath));
Answer<Map<String, ? extends ServletRegistration>> answer = invocation -> Collections.singletonMap("spring",
Answer<Map<String, ? extends ServletRegistration>> answer = (invocation) -> Collections.singletonMap("spring",
registration);
given(servletContext.getServletRegistrations()).willAnswer(answer);
return servletContext;

View File

@@ -340,7 +340,7 @@ public class MiscHttpConfigTests {
Class<?> userFilterClass = this.spring.getContext().getBean("userFilter").getClass();
assertThat(filters).extracting((Extractor<Filter, Class<?>>) filter -> filter.getClass()).containsSubsequence(
assertThat(filters).extracting((Extractor<Filter, Class<?>>) (filter) -> filter.getClass()).containsSubsequence(
userFilterClass, userFilterClass, SecurityContextPersistenceFilter.class, LogoutFilter.class,
userFilterClass);
}
@@ -355,7 +355,7 @@ public class MiscHttpConfigTests {
public void configureWhenUsingX509ThenAddsX509FilterCorrectly() {
this.spring.configLocations(xml("X509")).autowire();
assertThat(getFilters("/")).extracting((Extractor<Filter, Class<?>>) filter -> filter.getClass())
assertThat(getFilters("/")).extracting((Extractor<Filter, Class<?>>) (filter) -> filter.getClass())
.containsSubsequence(CsrfFilter.class, X509AuthenticationFilter.class,
ExceptionTranslationFilter.class);
}
@@ -384,7 +384,7 @@ public class MiscHttpConfigTests {
List<String> values = result.getResponse().getHeaders("Set-Cookie");
assertThat(values.size()).isEqualTo(2);
assertThat(values).extracting(value -> value.split("=")[0]).contains("JSESSIONID", "mycookie");
assertThat(values).extracting((value) -> value.split("=")[0]).contains("JSESSIONID", "mycookie");
}
@Test
@@ -587,7 +587,7 @@ public class MiscHttpConfigTests {
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with(request -> {
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("admin");
request.addUserRole("user");
request.addUserRole("unmapped");
@@ -703,7 +703,7 @@ public class MiscHttpConfigTests {
}
private Answer<ILoggingEvent> writeTo(OutputStream os) {
return invocation -> {
return (invocation) -> {
os.write(invocation.getArgument(0).toString().getBytes());
return null;
};

View File

@@ -274,7 +274,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Jwt jwt = TestJwts.user();
given(this.jwtDecoderFactory.createDecoder(any())).willReturn(token -> jwt);
given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", "code123");
@@ -331,7 +331,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Jwt jwt = TestJwts.user();
given(this.jwtDecoderFactory.createDecoder(any())).willReturn(token -> jwt);
given(this.jwtDecoderFactory.createDecoder(any())).willReturn((token) -> jwt);
given(this.userAuthoritiesMapper.mapAuthorities(any()))
.willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));

View File

@@ -678,7 +678,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver = this.spring.getContext()
.getBean(AuthenticationManagerResolver.class);
given(authenticationManagerResolver.resolve(any(HttpServletRequest.class))).willReturn(
authentication -> new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
(authentication) -> new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());

View File

@@ -118,7 +118,7 @@ public class OpenIDConfigTests {
OpenIDConsumer consumer = mock(OpenIDConsumer.class);
given(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString()))
.will(invocation -> openIdEndpointUrl + invocation.getArgument(2));
.will((invocation) -> openIdEndpointUrl + invocation.getArgument(2));
openIDFilter.setConsumer(consumer);
String expectedReturnTo = new StringBuilder("http://localhost/login/openid").append("?")
@@ -155,7 +155,7 @@ public class OpenIDConfigTests {
this.mvc.perform(
get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint))
.andExpect(status().isFound())
.andExpect(result -> result.getResponse().getRedirectedUrl().endsWith(
.andExpect((result) -> result.getResponse().getRedirectedUrl().endsWith(
"openid.ext1.type.nickname=http%3A%2F%2Fschema.openid.net%2FnamePerson%2Ffriendly&"
+ "openid.ext1.if_available=nickname&"
+ "openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&"

View File

@@ -378,7 +378,7 @@ public class SessionManagementConfigTests {
this.spring.configLocations(this.xml("SessionFixationProtectionNoneWithInvalidSessionUrl")).autowire();
this.mvc.perform(get("/auth").with(request -> {
this.mvc.perform(get("/auth").with((request) -> {
request.setRequestedSessionId("1");
request.setRequestedSessionIdValid(false);
return request;

View File

@@ -64,8 +64,8 @@ public class AuthorizeExchangeSpecTests {
@Test
public void antMatchersWhenPatternsInLambdaThenAnyMethod() {
this.http.csrf(ServerHttpSecurity.CsrfSpec::disable)
.authorizeExchange(exchanges -> exchanges.pathMatchers("/a", "/b").denyAll().anyExchange().permitAll());
this.http.csrf(ServerHttpSecurity.CsrfSpec::disable).authorizeExchange(
(exchanges) -> exchanges.pathMatchers("/a", "/b").denyAll().anyExchange().permitAll());
WebTestClient client = buildClient();
@@ -97,7 +97,7 @@ public class AuthorizeExchangeSpecTests {
@Test(expected = IllegalStateException.class)
public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() {
this.http.authorizeExchange(exchanges -> exchanges.pathMatchers("/incomplete"));
this.http.authorizeExchange((exchanges) -> exchanges.pathMatchers("/incomplete"));
this.http.build();
}

View File

@@ -78,7 +78,7 @@ public class CorsSpecTests {
@Test
public void corsWhenEnabledInLambdaThenAccessControlAllowOriginAndSecurityHeaders() {
this.http.cors(cors -> 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();
@@ -104,7 +104,7 @@ public class CorsSpecTests {
private void assertHeaders() {
WebTestClient client = buildClient();
FluxExchangeResult<String> response = client.get().uri("https://example.com/")
.headers(h -> h.setOrigin("https://origin.example.com")).exchange().returnResult(String.class);
.headers((h) -> h.setOrigin("https://origin.example.com")).exchange().returnResult(String.class);
Map<String, List<String>> responseHeaders = response.getResponseHeaders();

View File

@@ -52,7 +52,7 @@ public class ExceptionHandlingSpecTests {
@Test
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAuthenticationEntryPointUsed() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated())
.exceptionHandling(withDefaults()).build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
@@ -75,8 +75,8 @@ public class ExceptionHandlingSpecTests {
@Test
public void requestWhenCustomAuthenticationEntryPointInLambdaThenCustomAuthenticationEntryPointUsed() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
.exceptionHandling(exceptionHandling -> exceptionHandling
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated())
.exceptionHandling((exceptionHandling) -> exceptionHandling
.authenticationEntryPoint(redirectServerAuthenticationEntryPoint("/auth")))
.build();
@@ -92,19 +92,19 @@ public class ExceptionHandlingSpecTests {
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
client.get().uri("/admin").headers(headers -> headers.setBasicAuth("user", "password")).exchange()
client.get().uri("/admin").headers((headers) -> headers.setBasicAuth("user", "password")).exchange()
.expectStatus().isForbidden();
}
@Test
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAccessDeniedHandlerUsed() {
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
.authorizeExchange(exchanges -> exchanges.anyExchange().hasRole("ADMIN"))
.authorizeExchange((exchanges) -> exchanges.anyExchange().hasRole("ADMIN"))
.exceptionHandling(withDefaults()).build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
client.get().uri("/admin").headers(headers -> headers.setBasicAuth("user", "password")).exchange()
client.get().uri("/admin").headers((headers) -> headers.setBasicAuth("user", "password")).exchange()
.expectStatus().isForbidden();
}
@@ -116,21 +116,21 @@ public class ExceptionHandlingSpecTests {
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
client.get().uri("/admin").headers(headers -> headers.setBasicAuth("user", "password")).exchange()
client.get().uri("/admin").headers((headers) -> headers.setBasicAuth("user", "password")).exchange()
.expectStatus().isBadRequest();
}
@Test
public void requestWhenCustomAccessDeniedHandlerInLambdaThenCustomAccessDeniedHandlerUsed() {
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
.authorizeExchange(exchanges -> exchanges.anyExchange().hasRole("ADMIN"))
.exceptionHandling(exceptionHandling -> exceptionHandling
.authorizeExchange((exchanges) -> exchanges.anyExchange().hasRole("ADMIN"))
.exceptionHandling((exceptionHandling) -> exceptionHandling
.accessDeniedHandler(httpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST)))
.build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
client.get().uri("/admin").headers(headers -> headers.setBasicAuth("user", "password")).exchange()
client.get().uri("/admin").headers((headers) -> headers.setBasicAuth("user", "password")).exchange()
.expectStatus().isBadRequest();
}

View File

@@ -92,7 +92,7 @@ public class FormLoginTests {
@Test
public void formLoginWhenDefaultsInLambdaThenCreatesDefaultLoginPage() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()).formLogin(withDefaults())
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated()).formLogin(withDefaults())
.build();
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
@@ -135,8 +135,8 @@ public class FormLoginTests {
public void formLoginWhenCustomLoginPageInLambdaThenUsed() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(
exchanges -> exchanges.pathMatchers("/login").permitAll().anyExchange().authenticated())
.formLogin(formLogin -> formLogin.loginPage("/login")).build();
(exchanges) -> exchanges.pathMatchers("/login").permitAll().anyExchange().authenticated())
.formLogin((formLogin) -> formLogin.loginPage("/login")).build();
WebTestClient webTestClient = WebTestClient
.bindToController(new CustomLoginPageController(), new WebTestClientBuilder.Http200RestController())
@@ -479,7 +479,7 @@ public class FormLoginTests {
@GetMapping("/login")
public Mono<String> login(ServerWebExchange exchange) {
Mono<CsrfToken> token = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty());
return token.map(t -> "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
return token.map((t) -> "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"

View File

@@ -87,7 +87,7 @@ public class HeaderSpecTests {
public void headersWhenDisableInLambdaThenNoSecurityHeaders() {
new HashSet<>(this.expectedHeaders.keySet()).forEach(this::expectHeaderNamesNotPresent);
this.http.headers(headers -> headers.disable());
this.http.headers((headers) -> headers.disable());
assertHeaders();
}
@@ -124,7 +124,7 @@ public class HeaderSpecTests {
@Test
public void headersWhenCacheDisableInLambdaThenCacheNotWritten() {
expectHeaderNamesNotPresent(HttpHeaders.CACHE_CONTROL, HttpHeaders.PRAGMA, HttpHeaders.EXPIRES);
this.http.headers(headers -> headers.cache(cache -> cache.disable()));
this.http.headers((headers) -> headers.cache((cache) -> cache.disable()));
assertHeaders();
}
@@ -140,7 +140,8 @@ public class HeaderSpecTests {
@Test
public void headersWhenContentOptionsDisableInLambdaThenContentTypeOptionsNotWritten() {
expectHeaderNamesNotPresent(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS);
this.http.headers(headers -> headers.contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable()));
this.http
.headers((headers) -> headers.contentTypeOptions((contentTypeOptions) -> contentTypeOptions.disable()));
assertHeaders();
}
@@ -156,7 +157,7 @@ public class HeaderSpecTests {
@Test
public void headersWhenHstsDisableInLambdaThenHstsNotWritten() {
expectHeaderNamesNotPresent(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
this.http.headers(headers -> headers.hsts(hsts -> hsts.disable()));
this.http.headers((headers) -> headers.hsts((hsts) -> hsts.disable()));
assertHeaders();
}
@@ -176,8 +177,8 @@ public class HeaderSpecTests {
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
"max-age=60");
this.http
.headers(headers -> headers.hsts(hsts -> hsts.maxAge(Duration.ofSeconds(60)).includeSubdomains(false)));
this.http.headers(
(headers) -> headers.hsts((hsts) -> hsts.maxAge(Duration.ofSeconds(60)).includeSubdomains(false)));
assertHeaders();
}
@@ -197,7 +198,7 @@ public class HeaderSpecTests {
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
"max-age=60 ; includeSubDomains ; preload");
this.http.headers(headers -> headers.hsts(hsts -> hsts.maxAge(Duration.ofSeconds(60)).preload(true)));
this.http.headers((headers) -> headers.hsts((hsts) -> hsts.maxAge(Duration.ofSeconds(60)).preload(true)));
assertHeaders();
}
@@ -213,7 +214,7 @@ public class HeaderSpecTests {
@Test
public void headersWhenFrameOptionsDisableInLambdaThenFrameOptionsNotWritten() {
expectHeaderNamesNotPresent(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS);
this.http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.disable()));
this.http.headers((headers) -> headers.frameOptions((frameOptions) -> frameOptions.disable()));
assertHeaders();
}
@@ -229,8 +230,8 @@ public class HeaderSpecTests {
@Test
public void headersWhenFrameOptionsModeInLambdaThenFrameOptionsCustomMode() {
this.expectedHeaders.set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN");
this.http.headers(headers -> headers
.frameOptions(frameOptions -> frameOptions.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)));
this.http.headers((headers) -> headers.frameOptions(
(frameOptions) -> frameOptions.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)));
assertHeaders();
}
@@ -246,7 +247,7 @@ public class HeaderSpecTests {
@Test
public void headersWhenXssProtectionDisableInLambdaThenXssProtectionNotWritten() {
expectHeaderNamesNotPresent("X-Xss-Protection");
this.http.headers(headers -> headers.xssProtection(xssProtection -> xssProtection.disable()));
this.http.headers((headers) -> headers.xssProtection((xssProtection) -> xssProtection.disable()));
assertHeaders();
}
@@ -278,7 +279,7 @@ public class HeaderSpecTests {
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
expectedPolicyDirectives);
this.http.headers(headers -> headers.contentSecurityPolicy(withDefaults()));
this.http.headers((headers) -> headers.contentSecurityPolicy(withDefaults()));
assertHeaders();
}
@@ -289,8 +290,8 @@ public class HeaderSpecTests {
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
policyDirectives);
this.http.headers(headers -> headers.contentSecurityPolicy(
contentSecurityPolicy -> contentSecurityPolicy.policyDirectives(policyDirectives)));
this.http.headers((headers) -> headers.contentSecurityPolicy(
(contentSecurityPolicy) -> contentSecurityPolicy.policyDirectives(policyDirectives)));
assertHeaders();
}
@@ -308,7 +309,7 @@ public class HeaderSpecTests {
public void headersWhenReferrerPolicyEnabledInLambdaThenReferrerPolicyWritten() {
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
ReferrerPolicy.NO_REFERRER.getPolicy());
this.http.headers(headers -> headers.referrerPolicy(withDefaults()));
this.http.headers((headers) -> headers.referrerPolicy(withDefaults()));
assertHeaders();
}
@@ -326,8 +327,8 @@ public class HeaderSpecTests {
public void headersWhenReferrerPolicyCustomEnabledInLambdaThenCustomReferrerPolicyWritten() {
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE.getPolicy());
this.http.headers(headers -> headers
.referrerPolicy(referrerPolicy -> referrerPolicy.policy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE)));
this.http.headers((headers) -> headers
.referrerPolicy((referrerPolicy) -> referrerPolicy.policy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE)));
assertHeaders();
}
@@ -335,8 +336,8 @@ public class HeaderSpecTests {
@Test
public void headersWhenCustomHeadersWriter() {
this.expectedHeaders.add(CUSTOM_HEADER, CUSTOM_VALUE);
this.http.headers(headers -> headers.writer(exchange -> {
return Mono.just(exchange).doOnNext(it -> {
this.http.headers((headers) -> headers.writer((exchange) -> {
return Mono.just(exchange).doOnNext((it) -> {
it.getResponse().getHeaders().add(CUSTOM_HEADER, CUSTOM_VALUE);
}).then();

View File

@@ -174,7 +174,7 @@ public class HttpsRedirectSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.redirectToHttps(redirectToHttps ->
.redirectToHttps((redirectToHttps) ->
redirectToHttps
.httpsRedirectWhen(new PathPatternParserServerWebExchangeMatcher("/secure"))
);
@@ -215,7 +215,7 @@ public class HttpsRedirectSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.redirectToHttps(redirectToHttps ->
.redirectToHttps((redirectToHttps) ->
redirectToHttps
.portMapper(portMapper())
);

View File

@@ -91,9 +91,9 @@ public class LogoutSpecTests {
@Test
public void logoutWhenCustomLogoutInLambdaThenCustomLogoutUsed() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(authorizeExchange -> authorizeExchange.anyExchange().authenticated())
.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().authenticated())
.formLogin(withDefaults())
.logout(logout -> logout.requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")))
.logout((logout) -> logout.requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")))
.build();
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();

View File

@@ -144,7 +144,7 @@ public class OAuth2ClientSpecTests {
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
this.client.get()
.uri(uriBuilder -> uriBuilder.path("/authorize/oauth2/code/registration-id")
.uri((uriBuilder) -> uriBuilder.path("/authorize/oauth2/code/registration-id")
.queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state")
.build())
.exchange().expectStatus().is3xxRedirection();
@@ -185,7 +185,7 @@ public class OAuth2ClientSpecTests {
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
this.client.get()
.uri(uriBuilder -> uriBuilder.path("/authorize/oauth2/code/registration-id")
.uri((uriBuilder) -> uriBuilder.path("/authorize/oauth2/code/registration-id")
.queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state")
.build())
.exchange().expectStatus().is3xxRedirection();
@@ -264,7 +264,7 @@ public class OAuth2ClientSpecTests {
.authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository)
.and()
.requestCache(c -> c.requestCache(this.requestCache));
.requestCache((c) -> c.requestCache(this.requestCache));
// @formatter:on
return http.build();
}
@@ -287,12 +287,12 @@ public class OAuth2ClientSpecTests {
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2Client(oauth2Client ->
.oauth2Client((oauth2Client) ->
oauth2Client
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository))
.requestCache(c -> c.requestCache(this.requestCache));
.requestCache((c) -> c.requestCache(this.requestCache));
// @formatter:on
return http.build();
}

View File

@@ -226,7 +226,7 @@ public class OAuth2LoginTests {
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
@@ -268,14 +268,14 @@ public class OAuth2LoginTests {
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
return new RedirectServerAuthenticationSuccessHandler(redirectLocation)
.onAuthenticationSuccess(webFilterExchange, authentication);
});
given(failureHandler.onAuthenticationFailure(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
given(failureHandler.onAuthenticationFailure(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
AuthenticationException authenticationException = invocation.getArgument(1);
@@ -321,7 +321,7 @@ public class OAuth2LoginTests {
given(manager.authenticate(any())).willReturn(Mono.just(result));
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(resolver.resolve(any())).willReturn(Mono.empty());
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) invocation -> {
given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
WebFilterExchange webFilterExchange = invocation.getArgument(0);
Authentication authentication = invocation.getArgument(1);
@@ -442,7 +442,7 @@ public class OAuth2LoginTests {
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
given(jwtDecoderFactory.createDecoder(any())).willReturn(token -> Mono
given(jwtDecoderFactory.createDecoder(any())).willReturn((token) -> Mono
.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader()
@@ -602,11 +602,11 @@ public class OAuth2LoginTests {
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange(exchanges ->
.authorizeExchange((exchanges) ->
exchanges
.anyExchange().authenticated()
)
.oauth2Login(oauth2Login ->
.oauth2Login((oauth2Login) ->
oauth2Login
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
@@ -674,13 +674,13 @@ public class OAuth2LoginTests {
}
private ReactiveJwtDecoder getJwtDecoder() {
return token -> {
return (token) -> {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.SUB, "subject");
claims.put(IdTokenClaimNames.ISS, "http://localhost/issuer");
claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client"));
claims.put(IdTokenClaimNames.AZP, "client");
Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
Jwt jwt = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
return Mono.just(jwt);
};
}

View File

@@ -135,7 +135,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenValidThenReturnsOk() {
this.spring.register(PublicKeyConfig.class, RootController.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -143,7 +143,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenExpiredThenReturnsInvalidToken() {
this.spring.register(PublicKeyConfig.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.expired)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.expired)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
}
@@ -152,7 +152,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenUnsignedThenReturnsInvalidToken() {
this.spring.register(PublicKeyConfig.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.unsignedToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.unsignedToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
}
@@ -161,7 +161,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenEmptyBearerTokenThenReturnsInvalidToken() {
this.spring.register(PublicKeyConfig.class).autowire();
this.client.get().headers(headers -> headers.add("Authorization", "Bearer ")).exchange().expectStatus()
this.client.get().headers((headers) -> headers.add("Authorization", "Bearer ")).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
}
@@ -170,7 +170,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenValidTokenAndPublicKeyInLambdaThenReturnsOk() {
this.spring.register(PublicKeyInLambdaConfig.class, RootController.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -178,7 +178,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenExpiredTokenAndPublicKeyInLambdaThenReturnsInvalidToken() {
this.spring.register(PublicKeyInLambdaConfig.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.expired)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.expired)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
}
@@ -187,7 +187,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenValidUsingPlaceholderThenReturnsOk() {
this.spring.register(PlaceholderConfig.class, RootController.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -198,7 +198,7 @@ public class OAuth2ResourceServerSpecTests {
ReactiveJwtDecoder jwtDecoder = this.spring.getContext().getBean(ReactiveJwtDecoder.class);
given(jwtDecoder.decode(anyString())).willReturn(Mono.just(this.jwt));
this.client.get().headers(headers -> headers.setBearerAuth("token")).exchange().expectStatus().isOk();
this.client.get().headers((headers) -> headers.setBearerAuth("token")).exchange().expectStatus().isOk();
verify(jwtDecoder).decode(anyString());
}
@@ -210,7 +210,7 @@ public class OAuth2ResourceServerSpecTests {
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
mockWebServer.enqueue(new MockResponse().setBody(this.jwkSet));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadTokenWithKid)).exchange()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadTokenWithKid)).exchange()
.expectStatus().isOk();
}
@@ -221,7 +221,7 @@ public class OAuth2ResourceServerSpecTests {
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
mockWebServer.enqueue(new MockResponse().setBody(this.jwkSet));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadTokenWithKid)).exchange()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadTokenWithKid)).exchange()
.expectStatus().isOk();
}
@@ -234,7 +234,7 @@ public class OAuth2ResourceServerSpecTests {
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
}
@@ -248,7 +248,7 @@ public class OAuth2ResourceServerSpecTests {
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
}
@@ -268,7 +268,7 @@ public class OAuth2ResourceServerSpecTests {
given(authenticationManager.authenticate(any(Authentication.class)))
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isUnauthorized().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
}
@@ -277,7 +277,7 @@ public class OAuth2ResourceServerSpecTests {
public void postWhenSignedThenReturnsOk() {
this.spring.register(PublicKeyConfig.class, RootController.class).autowire();
this.client.post().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.post().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -285,7 +285,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenTokenHasInsufficientScopeThenReturnsInsufficientScope() {
this.spring.register(DenyAllConfig.class, RootController.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isForbidden().expectHeader()
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"insufficient_scope\""));
}
@@ -308,7 +308,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenSignedAndCustomConverterThenConverts() {
this.spring.register(CustomJwtAuthenticationConverterConfig.class, RootController.class).autowire();
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -323,7 +323,7 @@ public class OAuth2ResourceServerSpecTests {
public void getWhenCustomBearerTokenDeniedHandlerThenResponds() {
this.spring.register(CustomErrorHandlingConfig.class).autowire();
this.client.get().uri("/unobtainable").headers(headers -> headers.setBearerAuth(this.messageReadToken))
this.client.get().uri("/unobtainable").headers((headers) -> headers.setBearerAuth(this.messageReadToken))
.exchange().expectStatus().isEqualTo(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
}
@@ -392,7 +392,7 @@ public class OAuth2ResourceServerSpecTests {
this.spring.getContext().getBean(MockWebServer.class)
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -402,7 +402,7 @@ public class OAuth2ResourceServerSpecTests {
this.spring.getContext().getBean(MockWebServer.class)
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
}
@@ -417,8 +417,8 @@ public class OAuth2ResourceServerSpecTests {
@Override
public MockResponse dispatch(RecordedRequest request) {
String authorization = request.getHeader(org.springframework.http.HttpHeaders.AUTHORIZATION);
return Optional.ofNullable(authorization).filter(a -> isAuthorized(authorization, username, password))
.map(a -> ok(response)).orElse(unauthorized());
return Optional.ofNullable(authorization).filter((a) -> isAuthorized(authorization, username, password))
.map((a) -> ok(response)).orElse(unauthorized());
}
};
}
@@ -488,13 +488,13 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.authorizeExchange(exchanges ->
.authorizeExchange((exchanges) ->
exchanges
.anyExchange().hasAuthority("SCOPE_message:read")
)
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(jwt ->
.jwt((jwt) ->
jwt
.publicKey(publicKey())
)
@@ -572,9 +572,9 @@ public class OAuth2ResourceServerSpecTests {
// @formatter:off
http
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(jwt ->
.jwt((jwt) ->
jwt
.jwkSetUri(jwkSetUri)
)
@@ -672,9 +672,9 @@ public class OAuth2ResourceServerSpecTests {
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
// @formatter:off
http
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.jwt(jwt ->
.jwt((jwt) ->
jwt
.authenticationManager(authenticationManager())
)
@@ -743,7 +743,7 @@ public class OAuth2ResourceServerSpecTests {
@Bean
ServerAuthenticationConverter bearerTokenAuthenticationConverter() {
return exchange -> Mono.justOrEmpty(exchange.getRequest().getCookies().getFirst("TOKEN").getValue())
return (exchange) -> Mono.justOrEmpty(exchange.getRequest().getCookies().getFirst("TOKEN").getValue())
.map(BearerTokenAuthenticationToken::new);
}
@@ -773,7 +773,7 @@ public class OAuth2ResourceServerSpecTests {
Converter<Jwt, Mono<AbstractAuthenticationToken>> jwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
converter.setJwtGrantedAuthoritiesConverter((jwt) -> {
String[] claims = ((String) jwt.getClaims().get("scope")).split(" ");
return Stream.of(claims).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
});
@@ -852,9 +852,9 @@ public class OAuth2ResourceServerSpecTests {
// @formatter:off
http
.oauth2ResourceServer(oauth2ResourceServer ->
.oauth2ResourceServer((oauth2ResourceServer) ->
oauth2ResourceServer
.opaqueToken(opaqueToken ->
.opaqueToken((opaqueToken) ->
opaqueToken
.introspectionUri(introspectionUri)
.introspectionClientCredentials("client", "secret")

View File

@@ -84,9 +84,10 @@ public class RequestCacheTests {
@Test
public void requestWhenCustomRequestCacheInLambdaThenCustomCacheUsed() {
SecurityWebFilterChain securityWebFilter = this.http
.authorizeExchange(authorizeExchange -> authorizeExchange.anyExchange().authenticated())
.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().authenticated())
.formLogin(withDefaults())
.requestCache(requestCache -> requestCache.requestCache(NoOpServerRequestCache.getInstance())).build();
.requestCache((requestCache) -> requestCache.requestCache(NoOpServerRequestCache.getInstance()))
.build();
WebTestClient webTestClient = WebTestClient
.bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController())

View File

@@ -133,9 +133,9 @@ public class ServerHttpSecurityTests {
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/")
.headers(headers -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader()
.valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
.headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
@@ -154,9 +154,9 @@ public class ServerHttpSecurityTests {
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/")
.headers(headers -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader()
.valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
.headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNotNull();
}
@@ -187,7 +187,7 @@ public class ServerHttpSecurityTests {
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).isNotPresent();
Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class)
.map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
.map((logoutWebFilter) -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
LogoutWebFilter.class, "logoutHandler"));
assertThat(logoutHandler).get().isExactlyInstanceOf(SecurityContextServerLogoutHandler.class);
@@ -199,15 +199,15 @@ public class ServerHttpSecurityTests {
.and().build();
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).get()
.extracting(csrfWebFilter -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository"))
.extracting((csrfWebFilter) -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository"))
.isEqualTo(this.csrfTokenRepository);
Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class)
.map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
.map((logoutWebFilter) -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
LogoutWebFilter.class, "logoutHandler"));
assertThat(logoutHandler).get().isExactlyInstanceOf(DelegatingServerLogoutHandler.class)
.extracting(delegatingLogoutHandler -> ((List<ServerLogoutHandler>) ReflectionTestUtils
.extracting((delegatingLogoutHandler) -> ((List<ServerLogoutHandler>) ReflectionTestUtils
.getField(delegatingLogoutHandler, DelegatingServerLogoutHandler.class, "delegates")).stream()
.map(ServerLogoutHandler::getClass).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SecurityContextServerLogoutHandler.class, CsrfServerLogoutHandler.class));
@@ -271,9 +271,9 @@ public class ServerHttpSecurityTests {
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/")
.headers(headers -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader()
.valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
.headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class)
.consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
@@ -291,7 +291,7 @@ public class ServerHttpSecurityTests {
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/").exchange().expectStatus().isUnauthorized()
.expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, value -> assertThat(value).contains("myrealm"))
.expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, (value) -> assertThat(value).contains("myrealm"))
.expectBody(String.class).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
@@ -302,7 +302,7 @@ public class ServerHttpSecurityTests {
this.http.securityContextRepository(new WebSessionServerSecurityContextRepository());
HttpBasicServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();
authenticationEntryPoint.setRealm("myrealm");
this.http.httpBasic(httpBasic -> httpBasic.authenticationEntryPoint(authenticationEntryPoint));
this.http.httpBasic((httpBasic) -> httpBasic.authenticationEntryPoint(authenticationEntryPoint));
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().authenticated();
@@ -310,7 +310,7 @@ public class ServerHttpSecurityTests {
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/").exchange().expectStatus().isUnauthorized()
.expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, value -> assertThat(value).contains("myrealm"))
.expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, (value) -> assertThat(value).contains("myrealm"))
.expectBody(String.class).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
@@ -327,8 +327,8 @@ public class ServerHttpSecurityTests {
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers(headers -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"));
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
verifyZeroInteractions(this.authenticationManager);
}
@@ -340,12 +340,12 @@ public class ServerHttpSecurityTests {
.willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
SecurityWebFilterChain securityFilterChain = this.http
.httpBasic(httpBasic -> httpBasic.authenticationManager(customAuthenticationManager)).build();
.httpBasic((httpBasic) -> httpBasic.authenticationManager(customAuthenticationManager)).build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers(headers -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectBody(String.class).consumeWith(b -> assertThat(b.getResponseBody()).isEqualTo("ok"));
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk()
.expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
verifyZeroInteractions(this.authenticationManager);
verify(customAuthenticationManager).authenticate(any(Authentication.class));
@@ -370,7 +370,8 @@ public class ServerHttpSecurityTests {
X509PrincipalExtractor mockExtractor = mock(X509PrincipalExtractor.class);
ReactiveAuthenticationManager mockAuthenticationManager = mock(ReactiveAuthenticationManager.class);
this.http.x509(x509 -> x509.principalExtractor(mockExtractor).authenticationManager(mockAuthenticationManager));
this.http.x509(
(x509) -> x509.principalExtractor(mockExtractor).authenticationManager(mockAuthenticationManager));
SecurityWebFilterChain securityWebFilterChain = this.http.build();
WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst();
@@ -400,7 +401,7 @@ public class ServerHttpSecurityTests {
@Test
public void postWhenCsrfDisabledThenPermitted() {
SecurityWebFilterChain securityFilterChain = this.http.csrf(csrf -> csrf.disable()).build();
SecurityWebFilterChain securityFilterChain = this.http.csrf((csrf) -> csrf.disable()).build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
@@ -412,7 +413,7 @@ public class ServerHttpSecurityTests {
ServerCsrfTokenRepository customServerCsrfTokenRepository = mock(ServerCsrfTokenRepository.class);
given(customServerCsrfTokenRepository.loadToken(any(ServerWebExchange.class))).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http
.csrf(csrf -> csrf.csrfTokenRepository(customServerCsrfTokenRepository)).build();
.csrf((csrf) -> csrf.csrfTokenRepository(customServerCsrfTokenRepository)).build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
@@ -429,7 +430,7 @@ public class ServerHttpSecurityTests {
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository).and().authorizeExchange().anyExchange()
.authenticated().and().requestCache(c -> c.requestCache(requestCache)).build();
.authenticated().and().requestCache((c) -> c.requestCache(requestCache)).build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/test").exchange();
@@ -478,7 +479,7 @@ public class ServerHttpSecurityTests {
private <T extends WebFilter> Optional<T> getWebFilter(SecurityWebFilterChain filterChain, Class<T> filterClass) {
return (Optional<T>) filterChain.getWebFilters().filter(Objects::nonNull)
.filter(filter -> filter.getClass().isAssignableFrom(filterClass)).singleOrEmpty().blockOptional();
.filter((filter) -> filter.getClass().isAssignableFrom(filterClass)).singleOrEmpty().blockOptional();
}
private WebTestClient buildClient() {
@@ -491,9 +492,9 @@ public class ServerHttpSecurityTests {
@GetMapping("/**")
Mono<String> pathWithinApplicationFromContext() {
return Mono.subscriberContext().filter(c -> c.hasKey(ServerWebExchange.class))
.map(c -> c.get(ServerWebExchange.class))
.map(e -> e.getRequest().getPath().pathWithinApplication().value());
return Mono.subscriberContext().filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class))
.map((e) -> e.getRequest().getPath().pathWithinApplication().value());
}
}

View File

@@ -81,7 +81,7 @@ final class HtmlUnitWebTestClient {
private MultiValueMap<String, String> formData(List<NameValuePair> params) {
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(params.size());
params.forEach(pair -> result.add(pair.getName(), pair.getValue()));
params.forEach((pair) -> result.add(pair.getName(), pair.getValue()));
return result;
}
@@ -139,7 +139,7 @@ final class HtmlUnitWebTestClient {
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(request).flatMap(response -> redirectIfNecessary(request, next, response));
return next.exchange(request).flatMap((response) -> redirectIfNecessary(request, next, response));
}
private Mono<ClientResponse> redirectIfNecessary(ClientRequest request, ExchangeFunction next,
@@ -153,11 +153,11 @@ final class HtmlUnitWebTestClient {
redirectUrl = scheme + "://" + host + location.toASCIIString();
}
ClientRequest redirect = ClientRequest.method(HttpMethod.GET, URI.create(redirectUrl))
.headers(headers -> headers.addAll(request.headers()))
.cookies(cookies -> cookies.addAll(request.cookies()))
.attributes(attributes -> attributes.putAll(request.attributes())).build();
.headers((headers) -> headers.addAll(request.headers()))
.cookies((cookies) -> cookies.addAll(request.cookies()))
.attributes((attributes) -> attributes.putAll(request.attributes())).build();
return next.exchange(redirect).flatMap(r -> redirectIfNecessary(request, next, r));
return next.exchange(redirect).flatMap((r) -> redirectIfNecessary(request, next, r));
}
return Mono.just(response);
@@ -171,9 +171,9 @@ final class HtmlUnitWebTestClient {
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
return next.exchange(withClientCookies(request)).doOnSuccess(response -> {
response.cookies().values().forEach(cookies -> {
cookies.forEach(cookie -> {
return next.exchange(withClientCookies(request)).doOnSuccess((response) -> {
response.cookies().values().forEach((cookies) -> {
cookies.forEach((cookie) -> {
if (cookie.getMaxAge().isZero()) {
this.cookies.remove(cookie.getName());
}
@@ -186,14 +186,14 @@ final class HtmlUnitWebTestClient {
}
private ClientRequest withClientCookies(ClientRequest request) {
return ClientRequest.from(request).cookies(c -> {
return ClientRequest.from(request).cookies((c) -> {
c.addAll(clientCookies());
}).build();
}
private MultiValueMap<String, String> clientCookies() {
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(this.cookies.size());
this.cookies.values().forEach(cookie -> result.add(cookie.getName(), cookie.getValue()));
this.cookies.values().forEach((cookie) -> result.add(cookie.getName(), cookie.getValue()));
return result;
}

View File

@@ -67,7 +67,7 @@ final class MockWebResponseBuilder {
HttpHeaders responseHeaders = this.exchangeResult.getResponseHeaders();
List<NameValuePair> result = new ArrayList<>(responseHeaders.size());
responseHeaders.forEach((headerName, headerValues) -> headerValues
.forEach(headerValue -> result.add(new NameValuePair(headerName, headerValue))));
.forEach((headerValue) -> result.add(new NameValuePair(headerName, headerValue))));
return result;
}