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:
parent
01d90c9881
commit
52f20b5281
|
@ -231,7 +231,7 @@ public class BasicLookupStrategy implements LookupStrategy {
|
||||||
|
|
||||||
String sql = computeRepeatingSql(this.lookupPrimaryKeysWhereClause, findNow.size());
|
String sql = computeRepeatingSql(this.lookupPrimaryKeysWhereClause, findNow.size());
|
||||||
|
|
||||||
Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, ps -> {
|
Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, (ps) -> {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|
||||||
for (Long toFind : findNow) {
|
for (Long toFind : findNow) {
|
||||||
|
@ -358,7 +358,7 @@ public class BasicLookupStrategy implements LookupStrategy {
|
||||||
// (including markers to each parent in the hierarchy)
|
// (including markers to each parent in the hierarchy)
|
||||||
String sql = computeRepeatingSql(this.lookupObjectIdentitiesWhereClause, objectIdentities.size());
|
String sql = computeRepeatingSql(this.lookupObjectIdentitiesWhereClause, objectIdentities.size());
|
||||||
|
|
||||||
Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, ps -> {
|
Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, (ps) -> {
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (ObjectIdentity oid : objectIdentities) {
|
for (ObjectIdentity oid : objectIdentities) {
|
||||||
// Determine prepared statement values for this iteration
|
// Determine prepared statement values for this iteration
|
||||||
|
|
|
@ -9,7 +9,7 @@ import org.gradle.api.Project;
|
||||||
public class GlobalLockPlugin implements Plugin<Project> {
|
public class GlobalLockPlugin implements Plugin<Project> {
|
||||||
@Override
|
@Override
|
||||||
public void apply(Project project) {
|
public void apply(Project project) {
|
||||||
project.getTasks().register("writeLocks", GlobalLockTask.class, writeAll -> {
|
project.getTasks().register("writeLocks", GlobalLockTask.class, (writeAll) -> {
|
||||||
writeAll.setDescription("Writes the locks for all projects");
|
writeAll.setDescription("Writes the locks for all projects");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,7 @@ import org.gradle.api.Project;
|
||||||
public class TrangPlugin implements Plugin<Project> {
|
public class TrangPlugin implements Plugin<Project> {
|
||||||
@Override
|
@Override
|
||||||
public void apply(Project project) {
|
public void apply(Project project) {
|
||||||
project.getTasks().register("rncToXsd", RncToXsd.class, rncToXsd -> {
|
project.getTasks().register("rncToXsd", RncToXsd.class, (rncToXsd) -> {
|
||||||
rncToXsd.setDescription("Converts .rnc to .xsd");
|
rncToXsd.setDescription("Converts .rnc to .xsd");
|
||||||
rncToXsd.setGroup("Build");
|
rncToXsd.setGroup("Build");
|
||||||
});
|
});
|
||||||
|
|
|
@ -71,7 +71,7 @@ public class CasAuthenticationFilterTests {
|
||||||
request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ");
|
request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ");
|
||||||
|
|
||||||
CasAuthenticationFilter filter = new CasAuthenticationFilter();
|
CasAuthenticationFilter filter = new CasAuthenticationFilter();
|
||||||
filter.setAuthenticationManager(a -> a);
|
filter.setAuthenticationManager((a) -> a);
|
||||||
|
|
||||||
assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue();
|
assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue();
|
||||||
|
|
||||||
|
@ -82,7 +82,7 @@ public class CasAuthenticationFilterTests {
|
||||||
@Test(expected = AuthenticationException.class)
|
@Test(expected = AuthenticationException.class)
|
||||||
public void testNullServiceTicketHandledGracefully() throws Exception {
|
public void testNullServiceTicketHandledGracefully() throws Exception {
|
||||||
CasAuthenticationFilter filter = new CasAuthenticationFilter();
|
CasAuthenticationFilter filter = new CasAuthenticationFilter();
|
||||||
filter.setAuthenticationManager(a -> {
|
filter.setAuthenticationManager((a) -> {
|
||||||
throw new BadCredentialsException("Rejected");
|
throw new BadCredentialsException("Rejected");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -155,7 +155,7 @@ public class JwtITests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
rsocket.authorizePayload(authorize -> authorize.anyRequest().authenticated().anyExchange().permitAll())
|
rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll())
|
||||||
.jwt(Customizer.withDefaults());
|
.jwt(Customizer.withDefaults());
|
||||||
return rsocket.build();
|
return rsocket.build();
|
||||||
}
|
}
|
||||||
|
|
|
@ -244,7 +244,7 @@ public class RSocketMessageHandlerConnectionITests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
rsocket.authorizePayload(authorize -> authorize.setup().hasRole("SETUP").route("secure.admin.*")
|
rsocket.authorizePayload((authorize) -> authorize.setup().hasRole("SETUP").route("secure.admin.*")
|
||||||
.hasRole("ADMIN").route("secure.**").hasRole("USER").route("secure.authority.*")
|
.hasRole("ADMIN").route("secure.**").hasRole("USER").route("secure.authority.*")
|
||||||
.hasAuthority("ROLE_USER").route("management.*").hasAnyAuthority("ROLE_ADMIN").route("prohibit")
|
.hasAuthority("ROLE_USER").route("management.*").hasAnyAuthority("ROLE_ADMIN").route("prohibit")
|
||||||
.denyAll().anyRequest().permitAll()).basicAuthentication(Customizer.withDefaults());
|
.denyAll().anyRequest().permitAll()).basicAuthentication(Customizer.withDefaults());
|
||||||
|
|
|
@ -81,7 +81,7 @@ public class RSocketMessageHandlerITests {
|
||||||
.transport(TcpServerTransport.create("localhost", 0)).start().block();
|
.transport(TcpServerTransport.create("localhost", 0)).start().block();
|
||||||
|
|
||||||
this.requester = RSocketRequester.builder()
|
this.requester = RSocketRequester.builder()
|
||||||
// .rsocketFactory(factory ->
|
// .rsocketFactory((factory) ->
|
||||||
// factory.addRequesterPlugin(payloadInterceptor))
|
// factory.addRequesterPlugin(payloadInterceptor))
|
||||||
.rsocketStrategies(this.handler.getRSocketStrategies())
|
.rsocketStrategies(this.handler.getRSocketStrategies())
|
||||||
.connectTcp("localhost", this.server.address().getPort()).block();
|
.connectTcp("localhost", this.server.address().getPort()).block();
|
||||||
|
@ -221,7 +221,7 @@ public class RSocketMessageHandlerITests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
rsocket.authorizePayload(authorize -> {
|
rsocket.authorizePayload((authorize) -> {
|
||||||
authorize.route("secure.*").authenticated().anyExchange().permitAll();
|
authorize.route("secure.*").authenticated().anyExchange().permitAll();
|
||||||
}).basicAuthentication(Customizer.withDefaults());
|
}).basicAuthentication(Customizer.withDefaults());
|
||||||
return rsocket.build();
|
return rsocket.build();
|
||||||
|
@ -242,7 +242,7 @@ public class RSocketMessageHandlerITests {
|
||||||
|
|
||||||
@MessageMapping({ "secure.retrieve-flux", "retrieve-flux" })
|
@MessageMapping({ "secure.retrieve-flux", "retrieve-flux" })
|
||||||
Flux<String> retrieveFlux(Flux<String> payload) {
|
Flux<String> retrieveFlux(Flux<String> payload) {
|
||||||
return payload.doOnNext(this::add).map(p -> "hello " + p);
|
return payload.doOnNext(this::add).map((p) -> "hello " + p);
|
||||||
}
|
}
|
||||||
|
|
||||||
@MessageMapping({ "secure.send", "send" })
|
@MessageMapping({ "secure.send", "send" })
|
||||||
|
|
|
@ -139,7 +139,7 @@ public class SimpleAuthenticationITests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
rsocket.authorizePayload(authorize -> authorize.anyRequest().authenticated().anyExchange().permitAll())
|
rsocket.authorizePayload((authorize) -> authorize.anyRequest().authenticated().anyExchange().permitAll())
|
||||||
.simpleAuthentication(Customizer.withDefaults());
|
.simpleAuthentication(Customizer.withDefaults());
|
||||||
return rsocket.build();
|
return rsocket.build();
|
||||||
}
|
}
|
||||||
|
|
|
@ -135,8 +135,8 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||||
|
|
||||||
ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
|
ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
|
||||||
assertThat(providerManager.getProviders()).hasSize(1);
|
assertThat(providerManager.getProviders()).hasSize(1);
|
||||||
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper")
|
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper").allSatisfy(
|
||||||
.allSatisfy(contextMapper -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
|
(contextMapper) -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -153,10 +153,10 @@ public class LdapProviderBeanDefinitionParserTests {
|
||||||
|
|
||||||
AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0);
|
AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0);
|
||||||
assertThat(authenticationProvider).extracting("authenticator.userDnFormat")
|
assertThat(authenticationProvider).extracting("authenticator.userDnFormat")
|
||||||
.satisfies(messageFormats -> assertThat(messageFormats)
|
.satisfies((messageFormats) -> assertThat(messageFormats)
|
||||||
.isEqualTo(new MessageFormat[] { new MessageFormat("uid={0},ou=people") }));
|
.isEqualTo(new MessageFormat[] { new MessageFormat("uid={0},ou=people") }));
|
||||||
assertThat(authenticationProvider).extracting("authoritiesPopulator.groupSearchFilter")
|
assertThat(authenticationProvider).extracting("authoritiesPopulator.groupSearchFilter")
|
||||||
.satisfies(searchFilter -> assertThat(searchFilter).isEqualTo("member={0}"));
|
.satisfies((searchFilter) -> assertThat(searchFilter).isEqualTo("member={0}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,7 +37,7 @@ public interface Customizer<T> {
|
||||||
* @return a {@link Customizer} that does not alter the input argument.
|
* @return a {@link Customizer} that does not alter the input argument.
|
||||||
*/
|
*/
|
||||||
static <T> Customizer<T> withDefaults() {
|
static <T> Customizer<T> withDefaults() {
|
||||||
return t -> {
|
return (t) -> {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -60,7 +60,7 @@ import org.springframework.security.rsocket.util.matcher.RoutePayloadExchangeMat
|
||||||
* @Bean
|
* @Bean
|
||||||
* PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
* PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
* rsocket
|
* rsocket
|
||||||
* .authorizePayload(authorize ->
|
* .authorizePayload((authorize) ->
|
||||||
* authorize
|
* authorize
|
||||||
* .anyRequest().authenticated()
|
* .anyRequest().authenticated()
|
||||||
* );
|
* );
|
||||||
|
@ -87,7 +87,7 @@ import org.springframework.security.rsocket.util.matcher.RoutePayloadExchangeMat
|
||||||
* @Bean
|
* @Bean
|
||||||
* PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
* PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
|
||||||
* rsocket
|
* rsocket
|
||||||
* .authorizePayload(authorize ->
|
* .authorizePayload((authorize) ->
|
||||||
* authorize
|
* authorize
|
||||||
* // must have ROLE_SETUP to make connection
|
* // must have ROLE_SETUP to make connection
|
||||||
* .setup().hasRole("SETUP")
|
* .setup().hasRole("SETUP")
|
||||||
|
|
|
@ -47,8 +47,8 @@ class SecuritySocketAcceptorInterceptorConfiguration {
|
||||||
throw new NoSuchBeanDefinitionException("No RSocketSecurity defined");
|
throw new NoSuchBeanDefinitionException("No RSocketSecurity defined");
|
||||||
}
|
}
|
||||||
rsocket.basicAuthentication(Customizer.withDefaults()).simpleAuthentication(Customizer.withDefaults())
|
rsocket.basicAuthentication(Customizer.withDefaults()).simpleAuthentication(Customizer.withDefaults())
|
||||||
.authorizePayload(authz -> authz.setup().authenticated().anyRequest().authenticated()
|
.authorizePayload((authz) -> authz.setup().authenticated().anyRequest().authenticated()
|
||||||
.matcher(e -> MatchResult.match()).permitAll());
|
.matcher((e) -> MatchResult.match()).permitAll());
|
||||||
return rsocket.build();
|
return rsocket.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -260,11 +260,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) {
|
* protected void configure(HttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .openidLogin(openidLogin ->
|
* .openidLogin((openidLogin) ->
|
||||||
* openidLogin
|
* openidLogin
|
||||||
* .permitAll()
|
* .permitAll()
|
||||||
* );
|
* );
|
||||||
|
@ -293,48 +293,48 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
*
|
*
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http.authorizeRequests(authorizeRequests ->
|
* http.authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .openidLogin(openidLogin ->
|
* .openidLogin((openidLogin) ->
|
||||||
* openidLogin
|
* openidLogin
|
||||||
* .loginPage("/login")
|
* .loginPage("/login")
|
||||||
* .permitAll()
|
* .permitAll()
|
||||||
* .authenticationUserDetailsService(
|
* .authenticationUserDetailsService(
|
||||||
* new AutoProvisioningUserDetailsService())
|
* new AutoProvisioningUserDetailsService())
|
||||||
* .attributeExchange(googleExchange ->
|
* .attributeExchange((googleExchange) ->
|
||||||
* googleExchange
|
* googleExchange
|
||||||
* .identifierPattern("https://www.google.com/.*")
|
* .identifierPattern("https://www.google.com/.*")
|
||||||
* .attribute(emailAttribute ->
|
* .attribute((emailAttribute) ->
|
||||||
* emailAttribute
|
* emailAttribute
|
||||||
* .name("email")
|
* .name("email")
|
||||||
* .type("https://axschema.org/contact/email")
|
* .type("https://axschema.org/contact/email")
|
||||||
* .required(true)
|
* .required(true)
|
||||||
* )
|
* )
|
||||||
* .attribute(firstnameAttribute ->
|
* .attribute((firstnameAttribute) ->
|
||||||
* firstnameAttribute
|
* firstnameAttribute
|
||||||
* .name("firstname")
|
* .name("firstname")
|
||||||
* .type("https://axschema.org/namePerson/first")
|
* .type("https://axschema.org/namePerson/first")
|
||||||
* .required(true)
|
* .required(true)
|
||||||
* )
|
* )
|
||||||
* .attribute(lastnameAttribute ->
|
* .attribute((lastnameAttribute) ->
|
||||||
* lastnameAttribute
|
* lastnameAttribute
|
||||||
* .name("lastname")
|
* .name("lastname")
|
||||||
* .type("https://axschema.org/namePerson/last")
|
* .type("https://axschema.org/namePerson/last")
|
||||||
* .required(true)
|
* .required(true)
|
||||||
* )
|
* )
|
||||||
* )
|
* )
|
||||||
* .attributeExchange(yahooExchange ->
|
* .attributeExchange((yahooExchange) ->
|
||||||
* yahooExchange
|
* yahooExchange
|
||||||
* .identifierPattern(".*yahoo.com.*")
|
* .identifierPattern(".*yahoo.com.*")
|
||||||
* .attribute(emailAttribute ->
|
* .attribute((emailAttribute) ->
|
||||||
* emailAttribute
|
* emailAttribute
|
||||||
* .name("email")
|
* .name("email")
|
||||||
* .type("https://schema.openid.net/contact/email")
|
* .type("https://schema.openid.net/contact/email")
|
||||||
* .required(true)
|
* .required(true)
|
||||||
* )
|
* )
|
||||||
* .attribute(fullnameAttribute ->
|
* .attribute((fullnameAttribute) ->
|
||||||
* fullnameAttribute
|
* fullnameAttribute
|
||||||
* .name("fullname")
|
* .name("fullname")
|
||||||
* .type("https://axschema.org/namePerson")
|
* .type("https://axschema.org/namePerson")
|
||||||
|
@ -488,7 +488,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .headers(headers ->
|
* .headers((headers) ->
|
||||||
* headers
|
* headers
|
||||||
* .contentTypeOptions(withDefaults())
|
* .contentTypeOptions(withDefaults())
|
||||||
* .xssProtection(withDefaults())
|
* .xssProtection(withDefaults())
|
||||||
|
@ -510,7 +510,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .headers(headers -> headers.disable());
|
* .headers((headers) -> headers.disable());
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
* </pre>
|
* </pre>
|
||||||
|
@ -529,7 +529,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .headers(headers ->
|
* .headers((headers) ->
|
||||||
* headers
|
* headers
|
||||||
* .defaultsDisabled()
|
* .defaultsDisabled()
|
||||||
* .cacheControl(withDefaults())
|
* .cacheControl(withDefaults())
|
||||||
|
@ -551,9 +551,9 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .headers(headers ->
|
* .headers((headers) ->
|
||||||
* headers
|
* headers
|
||||||
* .frameOptions(frameOptions -> frameOptions.disable())
|
* .frameOptions((frameOptions) -> frameOptions.disable())
|
||||||
* );
|
* );
|
||||||
* }
|
* }
|
||||||
* </pre>
|
* </pre>
|
||||||
|
@ -677,17 +677,17 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .anyRequest().hasRole("USER")
|
* .anyRequest().hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(formLogin ->
|
* .formLogin((formLogin) ->
|
||||||
* formLogin
|
* formLogin
|
||||||
* .permitAll()
|
* .permitAll()
|
||||||
* )
|
* )
|
||||||
* .sessionManagement(sessionManagement ->
|
* .sessionManagement((sessionManagement) ->
|
||||||
* sessionManagement
|
* sessionManagement
|
||||||
* .sessionConcurrency(sessionConcurrency ->
|
* .sessionConcurrency((sessionConcurrency) ->
|
||||||
* sessionConcurrency
|
* sessionConcurrency
|
||||||
* .maximumSessions(1)
|
* .maximumSessions(1)
|
||||||
* .expiredUrl("/login?expired")
|
* .expiredUrl("/login?expired")
|
||||||
|
@ -788,11 +788,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .requiresChannel(requiresChannel ->
|
* .requiresChannel((requiresChannel) ->
|
||||||
* requiresChannel
|
* requiresChannel
|
||||||
* .anyRequest().requiresSecure()
|
* .anyRequest().requiresSecure()
|
||||||
* )
|
* )
|
||||||
* .portMapper(portMapper ->
|
* .portMapper((portMapper) ->
|
||||||
* portMapper
|
* portMapper
|
||||||
* .http(9090).mapsTo(9443)
|
* .http(9090).mapsTo(9443)
|
||||||
* .http(80).mapsTo(443)
|
* .http(80).mapsTo(443)
|
||||||
|
@ -901,11 +901,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .jee(jee ->
|
* .jee((jee) ->
|
||||||
* jee
|
* jee
|
||||||
* .mappableRoles("USER", "ADMIN")
|
* .mappableRoles("USER", "ADMIN")
|
||||||
* );
|
* );
|
||||||
|
@ -1009,7 +1009,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -1081,7 +1081,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -1188,7 +1188,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -1209,7 +1209,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/admin/**").hasRole("ADMIN")
|
* .antMatchers("/admin/**").hasRole("ADMIN")
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
|
@ -1231,7 +1231,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* .antMatchers("/admin/**").hasRole("ADMIN")
|
* .antMatchers("/admin/**").hasRole("ADMIN")
|
||||||
|
@ -1286,11 +1286,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .requestCache(requestCache ->
|
* .requestCache((requestCache) ->
|
||||||
* requestCache.disable()
|
* requestCache.disable()
|
||||||
* );
|
* );
|
||||||
* }
|
* }
|
||||||
|
@ -1334,12 +1334,12 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* // sample exception handling customization
|
* // sample exception handling customization
|
||||||
* .exceptionHandling(exceptionHandling ->
|
* .exceptionHandling((exceptionHandling) ->
|
||||||
* exceptionHandling
|
* exceptionHandling
|
||||||
* .accessDeniedPage("/errors/access-denied")
|
* .accessDeniedPage("/errors/access-denied")
|
||||||
* );
|
* );
|
||||||
|
@ -1383,7 +1383,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .securityContext(securityContext ->
|
* .securityContext((securityContext) ->
|
||||||
* securityContext
|
* securityContext
|
||||||
* .securityContextRepository(SCR)
|
* .securityContextRepository(SCR)
|
||||||
* );
|
* );
|
||||||
|
@ -1425,7 +1425,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .servletApi(servletApi ->
|
* .servletApi((servletApi) ->
|
||||||
* servletApi.disable()
|
* servletApi.disable()
|
||||||
* );
|
* );
|
||||||
* }
|
* }
|
||||||
|
@ -1481,7 +1481,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .csrf(csrf -> csrf.disable());
|
* .csrf((csrf) -> csrf.disable());
|
||||||
* }
|
* }
|
||||||
* }
|
* }
|
||||||
* </pre>
|
* </pre>
|
||||||
|
@ -1557,13 +1557,13 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(withDefaults())
|
* .formLogin(withDefaults())
|
||||||
* // sample logout customization
|
* // sample logout customization
|
||||||
* .logout(logout ->
|
* .logout((logout) ->
|
||||||
* logout.deleteCookies("remove")
|
* logout.deleteCookies("remove")
|
||||||
* .invalidateHttpSession(false)
|
* .invalidateHttpSession(false)
|
||||||
* .logoutUrl("/custom-logout")
|
* .logoutUrl("/custom-logout")
|
||||||
|
@ -1672,13 +1672,13 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(withDefaults())
|
* .formLogin(withDefaults())
|
||||||
* // sample anonymous customization
|
* // sample anonymous customization
|
||||||
* .anonymous(anonymous ->
|
* .anonymous((anonymous) ->
|
||||||
* anonymous
|
* anonymous
|
||||||
* .authorities("ROLE_ANON")
|
* .authorities("ROLE_ANON")
|
||||||
* )
|
* )
|
||||||
|
@ -1698,13 +1698,13 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(withDefaults())
|
* .formLogin(withDefaults())
|
||||||
* // sample anonymous customization
|
* // sample anonymous customization
|
||||||
* .anonymous(anonymous ->
|
* .anonymous((anonymous) ->
|
||||||
* anonymous.disable()
|
* anonymous.disable()
|
||||||
* );
|
* );
|
||||||
* }
|
* }
|
||||||
|
@ -1807,7 +1807,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -1826,11 +1826,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(formLogin ->
|
* .formLogin((formLogin) ->
|
||||||
* formLogin
|
* formLogin
|
||||||
* .usernameParameter("username")
|
* .usernameParameter("username")
|
||||||
* .passwordParameter("password")
|
* .passwordParameter("password")
|
||||||
|
@ -2184,7 +2184,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .anyRequest().authenticated()
|
* .anyRequest().authenticated()
|
||||||
* )
|
* )
|
||||||
|
@ -2268,7 +2268,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .anyRequest().authenticated()
|
* .anyRequest().authenticated()
|
||||||
* )
|
* )
|
||||||
|
@ -2325,13 +2325,13 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .anyRequest().authenticated()
|
* .anyRequest().authenticated()
|
||||||
* )
|
* )
|
||||||
* .oauth2ResourceServer(oauth2ResourceServer ->
|
* .oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
* oauth2ResourceServer
|
* oauth2ResourceServer
|
||||||
* .jwt(jwt ->
|
* .jwt((jwt) ->
|
||||||
* jwt
|
* jwt
|
||||||
* .decoder(jwtDecoder())
|
* .decoder(jwtDecoder())
|
||||||
* )
|
* )
|
||||||
|
@ -2418,12 +2418,12 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
* .formLogin(withDefaults())
|
* .formLogin(withDefaults())
|
||||||
* .requiresChannel(requiresChannel ->
|
* .requiresChannel((requiresChannel) ->
|
||||||
* requiresChannel
|
* requiresChannel
|
||||||
* .anyRequest().requiresSecure()
|
* .anyRequest().requiresSecure()
|
||||||
* );
|
* );
|
||||||
|
@ -2492,7 +2492,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -2727,11 +2727,11 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .requestMatchers(requestMatchers ->
|
* .requestMatchers((requestMatchers) ->
|
||||||
* requestMatchers
|
* requestMatchers
|
||||||
* .antMatchers("/api/**", "/oauth/**")
|
* .antMatchers("/api/**", "/oauth/**")
|
||||||
* )
|
* )
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -2750,12 +2750,12 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .requestMatchers(requestMatchers ->
|
* .requestMatchers((requestMatchers) ->
|
||||||
* requestMatchers
|
* requestMatchers
|
||||||
* .antMatchers("/api/**")
|
* .antMatchers("/api/**")
|
||||||
* .antMatchers("/oauth/**")
|
* .antMatchers("/oauth/**")
|
||||||
* )
|
* )
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
@ -2774,15 +2774,15 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||||
* @Override
|
* @Override
|
||||||
* protected void configure(HttpSecurity http) throws Exception {
|
* protected void configure(HttpSecurity http) throws Exception {
|
||||||
* http
|
* http
|
||||||
* .requestMatchers(requestMatchers ->
|
* .requestMatchers((requestMatchers) ->
|
||||||
* requestMatchers
|
* requestMatchers
|
||||||
* .antMatchers("/api/**")
|
* .antMatchers("/api/**")
|
||||||
* )
|
* )
|
||||||
* .requestMatchers(requestMatchers ->
|
* .requestMatchers((requestMatchers) ->
|
||||||
* requestMatchers
|
* requestMatchers
|
||||||
* .antMatchers("/oauth/**")
|
* .antMatchers("/oauth/**")
|
||||||
* )
|
* )
|
||||||
* .authorizeRequests(authorizeRequests ->
|
* .authorizeRequests((authorizeRequests) ->
|
||||||
* authorizeRequests
|
* authorizeRequests
|
||||||
* .antMatchers("/**").hasRole("USER")
|
* .antMatchers("/**").hasRole("USER")
|
||||||
* )
|
* )
|
||||||
|
|
|
@ -119,9 +119,8 @@ final class OAuth2ClientConfiguration {
|
||||||
if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) {
|
if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) {
|
||||||
if (this.accessTokenResponseClient != null) {
|
if (this.accessTokenResponseClient != null) {
|
||||||
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder
|
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder
|
||||||
.builder().authorizationCode().refreshToken()
|
.builder().authorizationCode().refreshToken().clientCredentials((configurer) -> configurer
|
||||||
.clientCredentials(
|
.accessTokenResponseClient(this.accessTokenResponseClient))
|
||||||
configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient))
|
|
||||||
.password().build();
|
.password().build();
|
||||||
DefaultOAuth2AuthorizedClientManager defaultAuthorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
|
DefaultOAuth2AuthorizedClientManager defaultAuthorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
|
||||||
this.clientRegistrationRepository, this.authorizedClientRepository);
|
this.clientRegistrationRepository, this.authorizedClientRepository);
|
||||||
|
|
|
@ -72,7 +72,7 @@ class SecurityReactorContextConfiguration {
|
||||||
Function<? super Publisher<Object>, ? extends Publisher<Object>> lifter = Operators
|
Function<? super Publisher<Object>, ? extends Publisher<Object>> lifter = Operators
|
||||||
.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
|
.liftPublisher((pub, sub) -> createSubscriberIfNecessary(sub));
|
||||||
|
|
||||||
Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, pub -> {
|
Hooks.onLastOperator(SECURITY_REACTOR_CONTEXT_OPERATOR_KEY, (pub) -> {
|
||||||
if (!contextAttributesAvailable()) {
|
if (!contextAttributesAvailable()) {
|
||||||
// No need to decorate so return original Publisher
|
// No need to decorate so return original Publisher
|
||||||
return pub;
|
return pub;
|
||||||
|
|
|
@ -170,7 +170,7 @@ public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
|
||||||
* <pre>
|
* <pre>
|
||||||
* http
|
* http
|
||||||
* .csrf()
|
* .csrf()
|
||||||
* .ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
|
* .ignoringRequestMatchers((request) -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
|
||||||
* .and()
|
* .and()
|
||||||
* ...
|
* ...
|
||||||
* </pre>
|
* </pre>
|
||||||
|
|
|
@ -76,7 +76,7 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void init(H http) {
|
public void init(H http) {
|
||||||
Function<HttpServletRequest, Map<String, String>> hiddenInputs = request -> {
|
Function<HttpServletRequest, Map<String, String>> hiddenInputs = (request) -> {
|
||||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||||
if (token == null) {
|
if (token == null) {
|
||||||
return Collections.emptyMap();
|
return Collections.emptyMap();
|
||||||
|
|
|
@ -504,7 +504,7 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>>
|
||||||
? this.authorizationEndpointConfig.authorizationRequestBaseUri
|
? this.authorizationEndpointConfig.authorizationRequestBaseUri
|
||||||
: OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
: OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||||
Map<String, String> loginUrlToClientName = new HashMap<>();
|
Map<String, String> loginUrlToClientName = new HashMap<>();
|
||||||
clientRegistrations.forEach(registration -> loginUrlToClientName.put(
|
clientRegistrations.forEach((registration) -> loginUrlToClientName.put(
|
||||||
authorizationRequestBaseUri + "/" + registration.getRegistrationId(), registration.getClientName()));
|
authorizationRequestBaseUri + "/" + registration.getRegistrationId(), registration.getClientName()));
|
||||||
|
|
||||||
return loginUrlToClientName;
|
return loginUrlToClientName;
|
||||||
|
|
|
@ -242,7 +242,7 @@ public final class OAuth2ResourceServerConfigurer<H extends HttpSecurityBuilder<
|
||||||
AuthenticationManagerResolver resolver = this.authenticationManagerResolver;
|
AuthenticationManagerResolver resolver = this.authenticationManagerResolver;
|
||||||
if (resolver == null) {
|
if (resolver == null) {
|
||||||
AuthenticationManager authenticationManager = getAuthenticationManager(http);
|
AuthenticationManager authenticationManager = getAuthenticationManager(http);
|
||||||
resolver = request -> authenticationManager;
|
resolver = (request) -> authenticationManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(resolver);
|
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(resolver);
|
||||||
|
|
|
@ -303,7 +303,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
|
||||||
Map<String, String> idps = new LinkedHashMap<>();
|
Map<String, String> idps = new LinkedHashMap<>();
|
||||||
if (idpRepo instanceof Iterable) {
|
if (idpRepo instanceof Iterable) {
|
||||||
Iterable<RelyingPartyRegistration> repo = (Iterable<RelyingPartyRegistration>) idpRepo;
|
Iterable<RelyingPartyRegistration> repo = (Iterable<RelyingPartyRegistration>) idpRepo;
|
||||||
repo.forEach(p -> idps.put(authRequestPrefixUrl.replace("{registrationId}", p.getRegistrationId()),
|
repo.forEach((p) -> idps.put(authRequestPrefixUrl.replace("{registrationId}", p.getRegistrationId()),
|
||||||
p.getRegistrationId()));
|
p.getRegistrationId()));
|
||||||
}
|
}
|
||||||
return idps;
|
return idps;
|
||||||
|
|
|
@ -76,7 +76,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
|
||||||
registry.addConverter(String.class, RSAPublicKey.class, x509);
|
registry.addConverter(String.class, RSAPublicKey.class, x509);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
beanFactory.addPropertyEditorRegistrar(registry -> {
|
beanFactory.addPropertyEditorRegistrar((registry) -> {
|
||||||
registry.registerCustomEditor(RSAPublicKey.class, new ConverterPropertyEditorAdapter<>(x509));
|
registry.registerCustomEditor(RSAPublicKey.class, new ConverterPropertyEditorAdapter<>(x509));
|
||||||
registry.registerCustomEditor(RSAPrivateKey.class, new ConverterPropertyEditorAdapter<>(pkcs8));
|
registry.registerCustomEditor(RSAPrivateKey.class, new ConverterPropertyEditorAdapter<>(pkcs8));
|
||||||
});
|
});
|
||||||
|
@ -101,7 +101,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
|
||||||
}
|
}
|
||||||
|
|
||||||
private Converter<String, InputStream> pemInputStreamConverter() {
|
private Converter<String, InputStream> pemInputStreamConverter() {
|
||||||
return source -> source.startsWith("-----") ? toInputStream(source)
|
return (source) -> source.startsWith("-----") ? toInputStream(source)
|
||||||
: toInputStream(this.resourceLoader.getResource(source));
|
: toInputStream(this.resourceLoader.getResource(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -119,7 +119,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
|
||||||
}
|
}
|
||||||
|
|
||||||
private <T> Converter<InputStream, T> autoclose(Converter<InputStream, T> inputStreamKeyConverter) {
|
private <T> Converter<InputStream, T> autoclose(Converter<InputStream, T> inputStreamKeyConverter) {
|
||||||
return inputStream -> {
|
return (inputStream) -> {
|
||||||
try (InputStream is = inputStream) {
|
try (InputStream is = inputStream) {
|
||||||
return inputStreamKeyConverter.convert(is);
|
return inputStreamKeyConverter.convert(is);
|
||||||
}
|
}
|
||||||
|
@ -130,7 +130,7 @@ public class RsaKeyConversionServicePostProcessor implements BeanFactoryPostProc
|
||||||
}
|
}
|
||||||
|
|
||||||
private <S, T, I> Converter<S, T> pair(Converter<S, I> one, Converter<I, T> two) {
|
private <S, T, I> Converter<S, T> pair(Converter<S, I> one, Converter<I, T> two) {
|
||||||
return source -> {
|
return (source) -> {
|
||||||
I intermediary = one.convert(source);
|
I intermediary = one.convert(source);
|
||||||
return two.convert(intermediary);
|
return two.convert(intermediary);
|
||||||
};
|
};
|
||||||
|
|
|
@ -469,7 +469,7 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser {
|
||||||
|
|
||||||
String authorizationRequestBaseUri = DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
String authorizationRequestBaseUri = DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
|
||||||
Map<String, String> loginUrlToClientName = new HashMap<>();
|
Map<String, String> loginUrlToClientName = new HashMap<>();
|
||||||
clientRegistrations.forEach(registration -> loginUrlToClientName.put(
|
clientRegistrations.forEach((registration) -> loginUrlToClientName.put(
|
||||||
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
|
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
|
||||||
registration.getClientName()));
|
registration.getClientName()));
|
||||||
|
|
||||||
|
|
|
@ -147,19 +147,19 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
|
||||||
String providerId = providerElt.getAttribute(ATT_PROVIDER_ID);
|
String providerId = providerElt.getAttribute(ATT_PROVIDER_ID);
|
||||||
provider.put(ATT_PROVIDER_ID, providerId);
|
provider.put(ATT_PROVIDER_ID, providerId);
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_AUTHORIZATION_URI))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_AUTHORIZATION_URI))
|
||||||
.ifPresent(value -> provider.put(ATT_AUTHORIZATION_URI, value));
|
.ifPresent((value) -> provider.put(ATT_AUTHORIZATION_URI, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_TOKEN_URI))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_TOKEN_URI))
|
||||||
.ifPresent(value -> provider.put(ATT_TOKEN_URI, value));
|
.ifPresent((value) -> provider.put(ATT_TOKEN_URI, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_URI))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_URI))
|
||||||
.ifPresent(value -> provider.put(ATT_USER_INFO_URI, value));
|
.ifPresent((value) -> provider.put(ATT_USER_INFO_URI, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_AUTHENTICATION_METHOD))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_AUTHENTICATION_METHOD))
|
||||||
.ifPresent(value -> provider.put(ATT_USER_INFO_AUTHENTICATION_METHOD, value));
|
.ifPresent((value) -> provider.put(ATT_USER_INFO_AUTHENTICATION_METHOD, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_USER_NAME_ATTRIBUTE))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_USER_INFO_USER_NAME_ATTRIBUTE))
|
||||||
.ifPresent(value -> provider.put(ATT_USER_INFO_USER_NAME_ATTRIBUTE, value));
|
.ifPresent((value) -> provider.put(ATT_USER_INFO_USER_NAME_ATTRIBUTE, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_JWK_SET_URI))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_JWK_SET_URI))
|
||||||
.ifPresent(value -> provider.put(ATT_JWK_SET_URI, value));
|
.ifPresent((value) -> provider.put(ATT_JWK_SET_URI, value));
|
||||||
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_ISSUER_URI))
|
getOptionalIfNotEmpty(providerElt.getAttribute(ATT_ISSUER_URI))
|
||||||
.ifPresent(value -> provider.put(ATT_ISSUER_URI, value));
|
.ifPresent((value) -> provider.put(ATT_ISSUER_URI, value));
|
||||||
providers.put(providerId, provider);
|
providers.put(providerId, provider);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -210,7 +210,7 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Optional<String> getOptionalIfNotEmpty(String str) {
|
private static Optional<String> getOptionalIfNotEmpty(String str) {
|
||||||
return Optional.ofNullable(str).filter(s -> !s.isEmpty());
|
return Optional.ofNullable(str).filter((s) -> !s.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static CommonOAuth2Provider getCommonProvider(String providerId) {
|
private static CommonOAuth2Provider getCommonProvider(String providerId) {
|
||||||
|
@ -246,7 +246,7 @@ public final class ClientRegistrationsBeanDefinitionParser implements BeanDefini
|
||||||
private static String getCanonicalName(String name) {
|
private static String getCanonicalName(String name) {
|
||||||
StringBuilder canonicalName = new StringBuilder(name.length());
|
StringBuilder canonicalName = new StringBuilder(name.length());
|
||||||
name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase)
|
name.chars().filter(Character::isLetterOrDigit).map(Character::toLowerCase)
|
||||||
.forEach(c -> canonicalName.append((char) c));
|
.forEach((c) -> canonicalName.append((char) c));
|
||||||
return canonicalName.toString();
|
return canonicalName.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -396,7 +396,7 @@ public class ServerHttpSecurity {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .redirectToHttps()
|
* .redirectToHttps()
|
||||||
* .httpsRedirectWhen(serverWebExchange ->
|
* .httpsRedirectWhen((serverWebExchange) ->
|
||||||
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
|
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
|
||||||
* return http.build();
|
* return http.build();
|
||||||
* }
|
* }
|
||||||
|
@ -431,9 +431,9 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .redirectToHttps(redirectToHttps ->
|
* .redirectToHttps((redirectToHttps) ->
|
||||||
* redirectToHttps
|
* redirectToHttps
|
||||||
* .httpsRedirectWhen(serverWebExchange ->
|
* .httpsRedirectWhen((serverWebExchange) ->
|
||||||
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
|
* serverWebExchange.getRequest().getHeaders().containsKey("X-Requires-Https"))
|
||||||
* );
|
* );
|
||||||
* return http.build();
|
* return http.build();
|
||||||
|
@ -501,7 +501,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .csrf(csrf ->
|
* .csrf((csrf) ->
|
||||||
* csrf.disabled()
|
* csrf.disabled()
|
||||||
* );
|
* );
|
||||||
* return http.build();
|
* return http.build();
|
||||||
|
@ -516,7 +516,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .csrf(csrf ->
|
* .csrf((csrf) ->
|
||||||
* csrf
|
* csrf
|
||||||
* // Handle CSRF failures
|
* // Handle CSRF failures
|
||||||
* .accessDeniedHandler(accessDeniedHandler)
|
* .accessDeniedHandler(accessDeniedHandler)
|
||||||
|
@ -607,7 +607,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .anonymous(anonymous ->
|
* .anonymous((anonymous) ->
|
||||||
* anonymous
|
* anonymous
|
||||||
* .key("key")
|
* .key("key")
|
||||||
* .authorities("ROLE_ANONYMOUS")
|
* .authorities("ROLE_ANONYMOUS")
|
||||||
|
@ -660,7 +660,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .httpBasic(httpBasic ->
|
* .httpBasic((httpBasic) ->
|
||||||
* httpBasic
|
* httpBasic
|
||||||
* // used for authenticating the credentials
|
* // used for authenticating the credentials
|
||||||
* .authenticationManager(authenticationManager)
|
* .authenticationManager(authenticationManager)
|
||||||
|
@ -719,7 +719,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .formLogin(formLogin ->
|
* .formLogin((formLogin) ->
|
||||||
* formLogin
|
* formLogin
|
||||||
* // used for authenticating the credentials
|
* // used for authenticating the credentials
|
||||||
* .authenticationManager(authenticationManager)
|
* .authenticationManager(authenticationManager)
|
||||||
|
@ -781,7 +781,7 @@ public class ServerHttpSecurity {
|
||||||
* @Bean
|
* @Bean
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* .x509(x509 ->
|
* .x509((x509) ->
|
||||||
* x509
|
* x509
|
||||||
* .authenticationManager(authenticationManager)
|
* .authenticationManager(authenticationManager)
|
||||||
* .principalExtractor(principalExtractor)
|
* .principalExtractor(principalExtractor)
|
||||||
|
@ -839,7 +839,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .oauth2Login(oauth2Login ->
|
* .oauth2Login((oauth2Login) ->
|
||||||
* oauth2Login
|
* oauth2Login
|
||||||
* .authenticationConverter(authenticationConverter)
|
* .authenticationConverter(authenticationConverter)
|
||||||
* .authenticationManager(manager)
|
* .authenticationManager(manager)
|
||||||
|
@ -890,7 +890,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .oauth2Client(oauth2Client ->
|
* .oauth2Client((oauth2Client) ->
|
||||||
* oauth2Client
|
* oauth2Client
|
||||||
* .clientRegistrationRepository(clientRegistrationRepository)
|
* .clientRegistrationRepository(clientRegistrationRepository)
|
||||||
* .authorizedClientRepository(authorizedClientRepository)
|
* .authorizedClientRepository(authorizedClientRepository)
|
||||||
|
@ -941,9 +941,9 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .oauth2ResourceServer(oauth2ResourceServer ->
|
* .oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
* oauth2ResourceServer
|
* oauth2ResourceServer
|
||||||
* .jwt(jwt ->
|
* .jwt((jwt) ->
|
||||||
* jwt
|
* jwt
|
||||||
* .publicKey(publicKey())
|
* .publicKey(publicKey())
|
||||||
* )
|
* )
|
||||||
|
@ -1027,15 +1027,15 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .headers(headers ->
|
* .headers((headers) ->
|
||||||
* headers
|
* headers
|
||||||
* // customize frame options to be same origin
|
* // customize frame options to be same origin
|
||||||
* .frameOptions(frameOptions ->
|
* .frameOptions((frameOptions) ->
|
||||||
* frameOptions
|
* frameOptions
|
||||||
* .mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
|
* .mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)
|
||||||
* )
|
* )
|
||||||
* // disable cache control
|
* // disable cache control
|
||||||
* .cache(cache ->
|
* .cache((cache) ->
|
||||||
* cache
|
* cache
|
||||||
* .disable()
|
* .disable()
|
||||||
* )
|
* )
|
||||||
|
@ -1088,7 +1088,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .exceptionHandling(exceptionHandling ->
|
* .exceptionHandling((exceptionHandling) ->
|
||||||
* exceptionHandling
|
* exceptionHandling
|
||||||
* // customize how to request for authentication
|
* // customize how to request for authentication
|
||||||
* .authenticationEntryPoint(entryPoint)
|
* .authenticationEntryPoint(entryPoint)
|
||||||
|
@ -1126,7 +1126,7 @@ public class ServerHttpSecurity {
|
||||||
* .pathMatchers("/users/{username}").access((authentication, context) ->
|
* .pathMatchers("/users/{username}").access((authentication, context) ->
|
||||||
* authentication
|
* authentication
|
||||||
* .map(Authentication::getName)
|
* .map(Authentication::getName)
|
||||||
* .map(username -> username.equals(context.getVariables().get("username")))
|
* .map((username) -> username.equals(context.getVariables().get("username")))
|
||||||
* .map(AuthorizationDecision::new)
|
* .map(AuthorizationDecision::new)
|
||||||
* )
|
* )
|
||||||
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
|
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
|
||||||
|
@ -1153,7 +1153,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .authorizeExchange(exchanges ->
|
* .authorizeExchange((exchanges) ->
|
||||||
* exchanges
|
* exchanges
|
||||||
* // any URL that starts with /admin/ requires the role "ROLE_ADMIN"
|
* // any URL that starts with /admin/ requires the role "ROLE_ADMIN"
|
||||||
* .pathMatchers("/admin/**").hasRole("ADMIN")
|
* .pathMatchers("/admin/**").hasRole("ADMIN")
|
||||||
|
@ -1164,7 +1164,7 @@ public class ServerHttpSecurity {
|
||||||
* .pathMatchers("/users/{username}").access((authentication, context) ->
|
* .pathMatchers("/users/{username}").access((authentication, context) ->
|
||||||
* authentication
|
* authentication
|
||||||
* .map(Authentication::getName)
|
* .map(Authentication::getName)
|
||||||
* .map(username -> username.equals(context.getVariables().get("username")))
|
* .map((username) -> username.equals(context.getVariables().get("username")))
|
||||||
* .map(AuthorizationDecision::new)
|
* .map(AuthorizationDecision::new)
|
||||||
* )
|
* )
|
||||||
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
|
* // allows providing a custom matching strategy that requires the role "ROLE_CUSTOM"
|
||||||
|
@ -1222,7 +1222,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .logout(logout ->
|
* .logout((logout) ->
|
||||||
* logout
|
* logout
|
||||||
* // configures how log out is done
|
* // configures how log out is done
|
||||||
* .logoutHandler(logoutHandler)
|
* .logoutHandler(logoutHandler)
|
||||||
|
@ -1278,7 +1278,7 @@ public class ServerHttpSecurity {
|
||||||
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
* public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
|
||||||
* http
|
* http
|
||||||
* // ...
|
* // ...
|
||||||
* .requestCache(requestCache ->
|
* .requestCache((requestCache) ->
|
||||||
* requestCache
|
* requestCache
|
||||||
* // configures how the request is cached
|
* // configures how the request is cached
|
||||||
* .requestCache(customRequestCache)
|
* .requestCache(customRequestCache)
|
||||||
|
@ -1405,7 +1405,7 @@ public class ServerHttpSecurity {
|
||||||
}
|
}
|
||||||
AnnotationAwareOrderComparator.sort(this.webFilters);
|
AnnotationAwareOrderComparator.sort(this.webFilters);
|
||||||
List<WebFilter> sortedWebFilters = new ArrayList<>();
|
List<WebFilter> sortedWebFilters = new ArrayList<>();
|
||||||
this.webFilters.forEach(f -> {
|
this.webFilters.forEach((f) -> {
|
||||||
if (f instanceof OrderedWebFilter) {
|
if (f instanceof OrderedWebFilter) {
|
||||||
f = ((OrderedWebFilter) f).webFilter;
|
f = ((OrderedWebFilter) f).webFilter;
|
||||||
}
|
}
|
||||||
|
@ -1675,7 +1675,7 @@ public class ServerHttpSecurity {
|
||||||
* @return the {@link HttpsRedirectSpec} for additional configuration
|
* @return the {@link HttpsRedirectSpec} for additional configuration
|
||||||
*/
|
*/
|
||||||
public HttpsRedirectSpec httpsRedirectWhen(Function<ServerWebExchange, Boolean> when) {
|
public HttpsRedirectSpec httpsRedirectWhen(Function<ServerWebExchange, Boolean> when) {
|
||||||
ServerWebExchangeMatcher matcher = e -> when.apply(e) ? ServerWebExchangeMatcher.MatchResult.match()
|
ServerWebExchangeMatcher matcher = (e) -> when.apply(e) ? ServerWebExchangeMatcher.MatchResult.match()
|
||||||
: ServerWebExchangeMatcher.MatchResult.notMatch();
|
: ServerWebExchangeMatcher.MatchResult.notMatch();
|
||||||
return httpsRedirectWhen(matcher);
|
return httpsRedirectWhen(matcher);
|
||||||
}
|
}
|
||||||
|
@ -3128,9 +3128,9 @@ public class ServerHttpSecurity {
|
||||||
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter delegate = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
|
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter delegate = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
|
||||||
clientRegistrationRepository);
|
clientRegistrationRepository);
|
||||||
delegate.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
|
delegate.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
|
||||||
ServerAuthenticationConverter authenticationConverter = exchange -> delegate.convert(exchange)
|
ServerAuthenticationConverter authenticationConverter = (exchange) -> delegate.convert(exchange)
|
||||||
.onErrorMap(OAuth2AuthorizationException.class,
|
.onErrorMap(OAuth2AuthorizationException.class,
|
||||||
e -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()));
|
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString()));
|
||||||
this.authenticationConverter = authenticationConverter;
|
this.authenticationConverter = authenticationConverter;
|
||||||
return authenticationConverter;
|
return authenticationConverter;
|
||||||
}
|
}
|
||||||
|
@ -3248,7 +3248,7 @@ public class ServerHttpSecurity {
|
||||||
MediaType.TEXT_PLAIN);
|
MediaType.TEXT_PLAIN);
|
||||||
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
|
htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
|
||||||
|
|
||||||
ServerWebExchangeMatcher xhrMatcher = exchange -> {
|
ServerWebExchangeMatcher xhrMatcher = (exchange) -> {
|
||||||
if (exchange.getRequest().getHeaders().getOrEmpty("X-Requested-With").contains("XMLHttpRequest")) {
|
if (exchange.getRequest().getHeaders().getOrEmpty("X-Requested-With").contains("XMLHttpRequest")) {
|
||||||
return ServerWebExchangeMatcher.MatchResult.match();
|
return ServerWebExchangeMatcher.MatchResult.match();
|
||||||
}
|
}
|
||||||
|
@ -3330,7 +3330,7 @@ public class ServerHttpSecurity {
|
||||||
}
|
}
|
||||||
Map<String, String> result = new HashMap<>();
|
Map<String, String> result = new HashMap<>();
|
||||||
registrations.iterator().forEachRemaining(
|
registrations.iterator().forEachRemaining(
|
||||||
r -> result.put("/oauth2/authorization/" + r.getRegistrationId(), r.getClientName()));
|
(r) -> result.put("/oauth2/authorization/" + r.getRegistrationId(), r.getClientName()));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3784,7 +3784,7 @@ public class ServerHttpSecurity {
|
||||||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
|
||||||
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
|
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
|
||||||
return super.filter(exchange, chain).onErrorResume(AuthenticationException.class,
|
return super.filter(exchange, chain).onErrorResume(AuthenticationException.class,
|
||||||
e -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
@ -89,7 +89,7 @@ public class AuthenticationManagerBuilderTests {
|
||||||
public void customAuthenticationEventPublisherWithWeb() throws Exception {
|
public void customAuthenticationEventPublisherWithWeb() throws Exception {
|
||||||
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
|
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
|
||||||
AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.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)
|
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
|
||||||
.inMemoryAuthentication().and().build();
|
.inMemoryAuthentication().and().build();
|
||||||
|
|
||||||
|
|
|
@ -49,10 +49,10 @@ public class NamespaceAuthenticationManagerTests {
|
||||||
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
|
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
|
||||||
|
|
||||||
this.mockMvc.perform(formLogin())
|
this.mockMvc.perform(formLogin())
|
||||||
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNull()));
|
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
|
||||||
|
|
||||||
this.mockMvc.perform(formLogin())
|
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
|
// no exception due to username being cleared out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -61,10 +61,10 @@ public class NamespaceAuthenticationManagerTests {
|
||||||
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
|
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
|
||||||
|
|
||||||
this.mockMvc.perform(formLogin())
|
this.mockMvc.perform(formLogin())
|
||||||
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
|
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
|
||||||
|
|
||||||
this.mockMvc.perform(formLogin())
|
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
|
// no exception due to username being cleared out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -74,7 +74,7 @@ public class NamespaceAuthenticationManagerTests {
|
||||||
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
|
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
|
||||||
|
|
||||||
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
|
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
|
||||||
.authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
|
.authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
|
|
|
@ -197,7 +197,7 @@ public class AuthenticationConfigurationTests {
|
||||||
public void getAuthenticationManagerWhenPostProcessThenUsesBeanClassLoaderOnProxyFactoryBean() throws Exception {
|
public void getAuthenticationManagerWhenPostProcessThenUsesBeanClassLoaderOnProxyFactoryBean() throws Exception {
|
||||||
this.spring.register(Sec2531Config.class).autowire();
|
this.spring.register(Sec2531Config.class).autowire();
|
||||||
ObjectPostProcessor<Object> opp = this.spring.getContext().getBean(ObjectPostProcessor.class);
|
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);
|
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
|
||||||
config.getAuthenticationManager();
|
config.getAuthenticationManager();
|
||||||
|
|
|
@ -224,7 +224,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||||
|
|
||||||
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
|
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
|
||||||
.subscriberContext(this.withAdmin);
|
.subscriberContext(this.withAdmin);
|
||||||
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
|
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -349,7 +349,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||||
|
|
||||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||||
.subscriberContext(this.withAdmin);
|
.subscriberContext(this.withAdmin);
|
||||||
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
|
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
|
||||||
.verifyComplete();
|
.verifyComplete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -457,7 +457,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
static <T> Publisher<T> publisher(Flux<T> flux) {
|
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) {
|
static <T> Publisher<T> publisherJust(T... data) {
|
||||||
|
|
|
@ -221,7 +221,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||||
public void globalSecurityProxiesSecurity() {
|
public void globalSecurityProxiesSecurity() {
|
||||||
this.spring.register(Sec3005Config.class).autowire();
|
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
|
// // gh-3797
|
||||||
|
|
|
@ -241,7 +241,7 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||||
this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
|
this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||||
|
|
||||||
assertThat(this.service.runAs().getAuthorities())
|
assertThat(this.service.runAs().getAuthorities())
|
||||||
.anyMatch(authority -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
|
.anyMatch((authority) -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -106,7 +106,7 @@ public class WebSecurityConfigurerAdapterPowermockTests {
|
||||||
|
|
||||||
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
|
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
|
||||||
.getAllValues().stream()
|
.getAllValues().stream()
|
||||||
.filter(e -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
|
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
|
||||||
.findFirst().orElse(null);
|
.findFirst().orElse(null);
|
||||||
|
|
||||||
assertThat(callableProcessingInterceptor).isNotNull();
|
assertThat(callableProcessingInterceptor).isNotNull();
|
||||||
|
|
|
@ -189,7 +189,7 @@ public class HttpSecurityConfigurationTests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
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
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
return http.authorizeRequests(authorize -> authorize.anyRequest().authenticated()).formLogin(withDefaults())
|
return http.authorizeRequests((authorize) -> authorize.anyRequest().authenticated())
|
||||||
.build();
|
.formLogin(withDefaults()).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -123,7 +123,7 @@ public class SecurityReactorContextConfigurationResourceServerTests {
|
||||||
@GetMapping("/token")
|
@GetMapping("/token")
|
||||||
public String token() {
|
public String token() {
|
||||||
return this.rest.get().uri(this.uri).retrieve().bodyToMono(String.class)
|
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -209,9 +209,9 @@ public class SecurityReactorContextConfigurationTests {
|
||||||
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
|
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
|
||||||
|
|
||||||
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
|
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
|
||||||
.filter(ctx -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
|
.filter((ctx) -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
|
||||||
.map(ctx -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
|
.map((ctx) -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
|
||||||
.map(attributes -> {
|
.map((attributes) -> {
|
||||||
if (attributes.containsKey(HttpServletRequest.class)
|
if (attributes.containsKey(HttpServletRequest.class)
|
||||||
&& attributes.containsKey(HttpServletResponse.class)
|
&& attributes.containsKey(HttpServletResponse.class)
|
||||||
&& attributes.containsKey(Authentication.class)) {
|
&& attributes.containsKey(Authentication.class)) {
|
||||||
|
@ -231,7 +231,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||||
expectedContextAttributes.put(Authentication.class, this.authentication);
|
expectedContextAttributes.put(Authentication.class, this.authentication);
|
||||||
|
|
||||||
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
|
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
|
||||||
.flatMap(response -> filter.filter(clientRequest, exchange));
|
.flatMap((response) -> filter.filter(clientRequest, exchange));
|
||||||
|
|
||||||
StepVerifier.create(clientResponseMono).expectAccessibleContext()
|
StepVerifier.create(clientResponseMono).expectAccessibleContext()
|
||||||
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)
|
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)
|
||||||
|
|
|
@ -368,27 +368,27 @@ public class WebSecurityConfigurationTests {
|
||||||
@Order(1)
|
@Order(1)
|
||||||
@Bean
|
@Bean
|
||||||
SecurityFilterChain filterChain1(HttpSecurity http) throws Exception {
|
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();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(2)
|
@Order(2)
|
||||||
@Bean
|
@Bean
|
||||||
SecurityFilterChain filterChain2(HttpSecurity http) throws Exception {
|
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();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(3)
|
@Order(3)
|
||||||
@Bean
|
@Bean
|
||||||
SecurityFilterChain filterChain3(HttpSecurity http) throws Exception {
|
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();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
SecurityFilterChain filterChain4(HttpSecurity http) throws Exception {
|
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
|
@Bean
|
||||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
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)
|
@Order(2)
|
||||||
@Bean
|
@Bean
|
||||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
return http.antMatcher("/filter/**").authorizeRequests(authorize -> authorize.anyRequest().authenticated())
|
return http.antMatcher("/filter/**")
|
||||||
.build();
|
.authorizeRequests((authorize) -> authorize.anyRequest().authenticated()).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Order(1)
|
@Order(1)
|
||||||
|
@ -665,7 +665,7 @@ public class WebSecurityConfigurationTests {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.antMatcher("/config/**").authorizeRequests(authorize -> authorize.anyRequest().permitAll());
|
http.antMatcher("/config/**").authorizeRequests((authorize) -> authorize.anyRequest().permitAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -103,7 +103,7 @@ public class AnonymousConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.anonymous(anonymous ->
|
.anonymous((anonymous) ->
|
||||||
anonymous
|
anonymous
|
||||||
.principal("principal")
|
.principal("principal")
|
||||||
);
|
);
|
||||||
|
@ -119,7 +119,7 @@ public class AnonymousConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
|
@ -145,7 +145,7 @@ public class AnonymousConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
|
|
|
@ -393,7 +393,7 @@ public class AuthorizeRequestsTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.antMatchers(HttpMethod.POST).denyAll()
|
.antMatchers(HttpMethod.POST).denyAll()
|
||||||
);
|
);
|
||||||
|
@ -533,7 +533,7 @@ public class AuthorizeRequestsTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.httpBasic(withDefaults())
|
.httpBasic(withDefaults())
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.mvcMatchers("/path").denyAll()
|
.mvcMatchers("/path").denyAll()
|
||||||
);
|
);
|
||||||
|
@ -605,7 +605,7 @@ public class AuthorizeRequestsTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.httpBasic(withDefaults())
|
.httpBasic(withDefaults())
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.mvcMatchers("/path").servletPath("/spring").denyAll()
|
.mvcMatchers("/path").servletPath("/spring").denyAll()
|
||||||
);
|
);
|
||||||
|
@ -677,7 +677,7 @@ public class AuthorizeRequestsTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.httpBasic(withDefaults())
|
.httpBasic(withDefaults())
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.mvcMatchers("/user/{userName}").access("#userName == 'user'")
|
.mvcMatchers("/user/{userName}").access("#userName == 'user'")
|
||||||
);
|
);
|
||||||
|
|
|
@ -151,7 +151,7 @@ public class ChannelSecurityConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requiresChannel(requiresChannel ->
|
.requiresChannel((requiresChannel) ->
|
||||||
requiresChannel
|
requiresChannel
|
||||||
.anyRequest().requiresSecure()
|
.anyRequest().requiresSecure()
|
||||||
);
|
);
|
||||||
|
|
|
@ -244,7 +244,7 @@ public class CorsConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
@ -298,7 +298,7 @@ public class CorsConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
@ -351,7 +351,7 @@ public class CorsConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
|
|
@ -93,7 +93,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
static class IgnoringRequestMatchers extends WebSecurityConfigurerAdapter {
|
static class IgnoringRequestMatchers extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
|
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
@ -110,13 +110,13 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
static class IgnoringRequestInLambdaMatchers extends WebSecurityConfigurerAdapter {
|
static class IgnoringRequestInLambdaMatchers extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
|
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.csrf(csrf ->
|
.csrf((csrf) ->
|
||||||
csrf
|
csrf
|
||||||
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/path"))
|
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/path"))
|
||||||
.ignoringRequestMatchers(this.requestMatcher)
|
.ignoringRequestMatchers(this.requestMatcher)
|
||||||
|
@ -129,7 +129,7 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
static class IgnoringPathsAndMatchers extends WebSecurityConfigurerAdapter {
|
static class IgnoringPathsAndMatchers extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
|
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
@ -146,13 +146,13 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
static class IgnoringPathsAndMatchersInLambdaConfig extends WebSecurityConfigurerAdapter {
|
static class IgnoringPathsAndMatchersInLambdaConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
RequestMatcher requestMatcher = request -> HttpMethod.POST.name().equals(request.getMethod());
|
RequestMatcher requestMatcher = (request) -> HttpMethod.POST.name().equals(request.getMethod());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.csrf(csrf ->
|
.csrf((csrf) ->
|
||||||
csrf
|
csrf
|
||||||
.ignoringAntMatchers("/no-csrf")
|
.ignoringAntMatchers("/no-csrf")
|
||||||
.ignoringRequestMatchers(this.requestMatcher)
|
.ignoringRequestMatchers(this.requestMatcher)
|
||||||
|
|
|
@ -558,7 +558,7 @@ public class CsrfConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.csrf(csrf -> csrf.requireCsrfProtectionMatcher(MATCHER));
|
.csrf((csrf) -> csrf.requireCsrfProtectionMatcher(MATCHER));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -601,7 +601,7 @@ public class CsrfConfigurerTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.csrf(csrf -> csrf.csrfTokenRepository(REPO));
|
.csrf((csrf) -> csrf.csrfTokenRepository(REPO));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -87,8 +87,8 @@ public class DefaultFiltersTests {
|
||||||
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
|
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
|
||||||
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
|
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
|
||||||
assertThat(filterChain.getFilters().size()).isEqualTo(1);
|
assertThat(filterChain.getFilters().size()).isEqualTo(1);
|
||||||
long filter = filterChain.getFilters().stream().filter(it -> it instanceof UsernamePasswordAuthenticationFilter)
|
long filter = filterChain.getFilters().stream()
|
||||||
.count();
|
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
|
||||||
assertThat(filter).isEqualTo(1);
|
assertThat(filter).isEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -325,7 +325,7 @@ public class DefaultLoginPageConfigurerTests {
|
||||||
|
|
||||||
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
|
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||||
assertThat(filterChain.getFilterChains().get(0).getFilters().stream()
|
assertThat(filterChain.getFilterChains().get(0).getFilters().stream()
|
||||||
.filter(filter -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())
|
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())
|
||||||
.isZero();
|
.isZero();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -116,11 +116,11 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
)
|
)
|
||||||
.exceptionHandling(exceptionHandling ->
|
.exceptionHandling((exceptionHandling) ->
|
||||||
exceptionHandling
|
exceptionHandling
|
||||||
.defaultAccessDeniedHandlerFor(
|
.defaultAccessDeniedHandlerFor(
|
||||||
this.teapotDeniedHandler,
|
this.teapotDeniedHandler,
|
||||||
|
|
|
@ -229,7 +229,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
|
||||||
public void getWhenHasIpAddressConfiguredAndIpAddressMatchesThenRespondsWithOk() throws Exception {
|
public void getWhenHasIpAddressConfiguredAndIpAddressMatchesThenRespondsWithOk() throws Exception {
|
||||||
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
|
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");
|
request.setRemoteAddr("192.168.1.0");
|
||||||
return request;
|
return request;
|
||||||
})).andExpect(status().isOk());
|
})).andExpect(status().isOk());
|
||||||
|
@ -239,7 +239,7 @@ public class ExpressionUrlAuthorizationConfigurerTests {
|
||||||
public void getWhenHasIpAddressConfiguredAndIpAddressDoesNotMatchThenRespondsWithUnauthorized() throws Exception {
|
public void getWhenHasIpAddressConfiguredAndIpAddressDoesNotMatchThenRespondsWithUnauthorized() throws Exception {
|
||||||
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
|
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");
|
request.setRemoteAddr("192.168.1.1");
|
||||||
return request;
|
return request;
|
||||||
})).andExpect(status().isUnauthorized());
|
})).andExpect(status().isUnauthorized());
|
||||||
|
|
|
@ -392,7 +392,7 @@ public class FormLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
|
@ -456,11 +456,11 @@ public class FormLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.formLogin(formLogin ->
|
.formLogin((formLogin) ->
|
||||||
formLogin
|
formLogin
|
||||||
.loginPage("/authenticate")
|
.loginPage("/authenticate")
|
||||||
.permitAll()
|
.permitAll()
|
||||||
|
@ -514,18 +514,18 @@ public class FormLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.formLogin(formLogin ->
|
.formLogin((formLogin) ->
|
||||||
formLogin
|
formLogin
|
||||||
.loginProcessingUrl("/loginCheck")
|
.loginProcessingUrl("/loginCheck")
|
||||||
.loginPage("/login")
|
.loginPage("/login")
|
||||||
.defaultSuccessUrl("/", true)
|
.defaultSuccessUrl("/", true)
|
||||||
.permitAll()
|
.permitAll()
|
||||||
)
|
)
|
||||||
.logout(logout ->
|
.logout((logout) ->
|
||||||
logout
|
logout
|
||||||
.logoutSuccessUrl("/login")
|
.logoutSuccessUrl("/login")
|
||||||
.logoutUrl("/logout")
|
.logoutUrl("/logout")
|
||||||
|
|
|
@ -486,7 +486,7 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.contentTypeOptions(withDefaults())
|
.contentTypeOptions(withDefaults())
|
||||||
|
@ -548,7 +548,7 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.cacheControl(withDefaults())
|
.cacheControl(withDefaults())
|
||||||
|
@ -580,7 +580,7 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.xssProtection(withDefaults())
|
.xssProtection(withDefaults())
|
||||||
|
@ -611,9 +611,9 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.frameOptions(frameOptionsConfig -> frameOptionsConfig.sameOrigin())
|
.frameOptions((frameOptionsConfig) -> frameOptionsConfig.sameOrigin())
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
@ -763,10 +763,10 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.httpPublicKeyPinning(hpkp ->
|
.httpPublicKeyPinning((hpkp) ->
|
||||||
hpkp
|
hpkp
|
||||||
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
|
.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=")
|
||||||
.reportUri("https://example.net/pkp-report")
|
.reportUri("https://example.net/pkp-report")
|
||||||
|
@ -815,10 +815,10 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.contentSecurityPolicy(csp ->
|
.contentSecurityPolicy((csp) ->
|
||||||
csp
|
csp
|
||||||
.policyDirectives("default-src 'self'; script-src trustedscripts.example.com")
|
.policyDirectives("default-src 'self'; script-src trustedscripts.example.com")
|
||||||
.reportOnly()
|
.reportOnly()
|
||||||
|
@ -851,10 +851,10 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.contentSecurityPolicy(csp ->
|
.contentSecurityPolicy((csp) ->
|
||||||
csp.policyDirectives("")
|
csp.policyDirectives("")
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
@ -870,7 +870,7 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.contentSecurityPolicy(withDefaults())
|
.contentSecurityPolicy(withDefaults())
|
||||||
|
@ -902,7 +902,7 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.referrerPolicy()
|
.referrerPolicy()
|
||||||
|
@ -934,10 +934,10 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.referrerPolicy(referrerPolicy ->
|
.referrerPolicy((referrerPolicy) ->
|
||||||
referrerPolicy.policy(ReferrerPolicy.SAME_ORIGIN)
|
referrerPolicy.policy(ReferrerPolicy.SAME_ORIGIN)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
@ -999,10 +999,10 @@ public class HeadersConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.headers(headers ->
|
.headers((headers) ->
|
||||||
headers
|
headers
|
||||||
.defaultsDisabled()
|
.defaultsDisabled()
|
||||||
.httpStrictTransportSecurity(hstsConfig -> hstsConfig.preload(true))
|
.httpStrictTransportSecurity((hstsConfig) -> hstsConfig.preload(true))
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
|
@ -153,7 +153,7 @@ public class HttpBasicConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
|
|
@ -302,12 +302,12 @@ public class HttpSecurityRequestMatchersTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requestMatchers(requestMatchers ->
|
.requestMatchers((requestMatchers) ->
|
||||||
requestMatchers
|
requestMatchers
|
||||||
.mvcMatchers("/path")
|
.mvcMatchers("/path")
|
||||||
)
|
)
|
||||||
.httpBasic(withDefaults())
|
.httpBasic(withDefaults())
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
);
|
);
|
||||||
|
@ -374,13 +374,13 @@ public class HttpSecurityRequestMatchersTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requestMatchers(requestMatchers ->
|
.requestMatchers((requestMatchers) ->
|
||||||
requestMatchers
|
requestMatchers
|
||||||
.mvcMatchers("/path").servletPath("/spring")
|
.mvcMatchers("/path").servletPath("/spring")
|
||||||
.mvcMatchers("/never-match")
|
.mvcMatchers("/never-match")
|
||||||
)
|
)
|
||||||
.httpBasic(withDefaults())
|
.httpBasic(withDefaults())
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
);
|
);
|
||||||
|
|
|
@ -81,7 +81,7 @@ public class JeeConfigurerTests {
|
||||||
Principal user = mock(Principal.class);
|
Principal user = mock(Principal.class);
|
||||||
given(user.getName()).willReturn("user");
|
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_ADMIN");
|
||||||
request.addUserRole("ROLE_USER");
|
request.addUserRole("ROLE_USER");
|
||||||
return request;
|
return request;
|
||||||
|
@ -94,7 +94,7 @@ public class JeeConfigurerTests {
|
||||||
Principal user = mock(Principal.class);
|
Principal user = mock(Principal.class);
|
||||||
given(user.getName()).willReturn("user");
|
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_ADMIN");
|
||||||
request.addUserRole("ROLE_USER");
|
request.addUserRole("ROLE_USER");
|
||||||
return request;
|
return request;
|
||||||
|
@ -107,7 +107,7 @@ public class JeeConfigurerTests {
|
||||||
Principal user = mock(Principal.class);
|
Principal user = mock(Principal.class);
|
||||||
given(user.getName()).willReturn("user");
|
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_ADMIN");
|
||||||
request.addUserRole("ROLE_USER");
|
request.addUserRole("ROLE_USER");
|
||||||
return request;
|
return request;
|
||||||
|
@ -125,7 +125,7 @@ public class JeeConfigurerTests {
|
||||||
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
|
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
|
||||||
.willReturn(userDetails);
|
.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_ADMIN");
|
||||||
request.addUserRole("ROLE_USER");
|
request.addUserRole("ROLE_USER");
|
||||||
return request;
|
return request;
|
||||||
|
@ -184,11 +184,11 @@ public class JeeConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.jee(jee ->
|
.jee((jee) ->
|
||||||
jee
|
jee
|
||||||
.mappableRoles("USER")
|
.mappableRoles("USER")
|
||||||
);
|
);
|
||||||
|
@ -204,11 +204,11 @@ public class JeeConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.jee(jee ->
|
.jee((jee) ->
|
||||||
jee
|
jee
|
||||||
.mappableAuthorities("ROLE_USER")
|
.mappableAuthorities("ROLE_USER")
|
||||||
);
|
);
|
||||||
|
@ -227,11 +227,11 @@ public class JeeConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.jee(jee ->
|
.jee((jee) ->
|
||||||
jee
|
jee
|
||||||
.authenticatedUserDetailsService(authenticationUserDetailsService)
|
.authenticatedUserDetailsService(authenticationUserDetailsService)
|
||||||
);
|
);
|
||||||
|
|
|
@ -267,7 +267,7 @@ public class LogoutConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.logout(logout ->
|
.logout((logout) ->
|
||||||
logout.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class))
|
logout.defaultLogoutSuccessHandlerFor(null, mock(RequestMatcher.class))
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
@ -296,7 +296,7 @@ public class LogoutConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.logout(logout ->
|
.logout((logout) ->
|
||||||
logout.defaultLogoutSuccessHandlerFor(mock(LogoutSuccessHandler.class), null)
|
logout.defaultLogoutSuccessHandlerFor(mock(LogoutSuccessHandler.class), null)
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
@ -397,7 +397,7 @@ public class LogoutConfigurerTests {
|
||||||
http
|
http
|
||||||
.csrf()
|
.csrf()
|
||||||
.disable()
|
.disable()
|
||||||
.logout(logout -> logout.logoutUrl("/custom/logout"));
|
.logout((logout) -> logout.logoutUrl("/custom/logout"));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -424,7 +424,7 @@ public class LogoutConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.logout(logout -> logout.addLogoutHandler(null));
|
.logout((logout) -> logout.addLogoutHandler(null));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -198,7 +198,7 @@ public class NamespaceHttpAnonymousTests {
|
||||||
|
|
||||||
Optional<AnonymousAuthenticationToken> anonymousToken() {
|
Optional<AnonymousAuthenticationToken> anonymousToken() {
|
||||||
return Optional.of(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication)
|
return Optional.of(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication)
|
||||||
.filter(a -> a instanceof AnonymousAuthenticationToken)
|
.filter((a) -> a instanceof AnonymousAuthenticationToken)
|
||||||
.map(AnonymousAuthenticationToken.class::cast);
|
.map(AnonymousAuthenticationToken.class::cast);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -199,7 +199,7 @@ public class NamespaceHttpBasicTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
|
@ -232,11 +232,11 @@ public class NamespaceHttpBasicTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.httpBasic(httpBasicConfig -> httpBasicConfig.realmName("Custom Realm"));
|
.httpBasic((httpBasicConfig) -> httpBasicConfig.realmName("Custom Realm"));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -274,7 +274,7 @@ public class NamespaceHttpBasicTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.httpBasic(httpBasicConfig ->
|
.httpBasic((httpBasicConfig) ->
|
||||||
httpBasicConfig.authenticationDetailsSource(this.authenticationDetailsSource));
|
httpBasicConfig.authenticationDetailsSource(this.authenticationDetailsSource));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
@ -314,11 +314,11 @@ public class NamespaceHttpBasicTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.httpBasic(httpBasicConfig ->
|
.httpBasic((httpBasicConfig) ->
|
||||||
httpBasicConfig.authenticationEntryPoint(this.authenticationEntryPoint));
|
httpBasicConfig.authenticationEntryPoint(this.authenticationEntryPoint));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
|
@ -153,7 +153,7 @@ public class NamespaceHttpHeadersTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ResultMatcher includes(Map<String, String> headers, String... headerNames) {
|
private static ResultMatcher includes(Map<String, String> headers, String... headerNames) {
|
||||||
return result -> {
|
return (result) -> {
|
||||||
assertThat(result.getResponse().getHeaderNames()).hasSameSizeAs(headerNames);
|
assertThat(result.getResponse().getHeaderNames()).hasSameSizeAs(headerNames);
|
||||||
for (String headerName : headerNames) {
|
for (String headerName : headerNames) {
|
||||||
header().string(headerName, headers.get(headerName)).match(result);
|
header().string(headerName, headers.get(headerName)).match(result);
|
||||||
|
|
|
@ -66,7 +66,7 @@ public class NamespaceHttpJeeTests {
|
||||||
Principal user = mock(Principal.class);
|
Principal user = mock(Principal.class);
|
||||||
given(user.getName()).willReturn("joe");
|
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_admin");
|
||||||
request.addUserRole("ROLE_user");
|
request.addUserRole("ROLE_user");
|
||||||
request.addUserRole("ROLE_unmapped");
|
request.addUserRole("ROLE_unmapped");
|
||||||
|
|
|
@ -95,7 +95,7 @@ public class NamespaceHttpLogoutTests {
|
||||||
|
|
||||||
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
|
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
|
||||||
.andExpect(redirectedUrl("/logout-success"))
|
.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));
|
.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))
|
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
|
||||||
.andExpect(redirectedUrl("/logout-success"))
|
.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));
|
.andExpect(cookie().maxAge("remove", 0)).andExpect(session(Objects::nonNull));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -134,16 +134,16 @@ public class NamespaceHttpLogoutTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
ResultMatcher authenticated(boolean authenticated) {
|
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);
|
.map(Authentication::isAuthenticated).orElse(false)).isEqualTo(authenticated);
|
||||||
}
|
}
|
||||||
|
|
||||||
ResultMatcher noCookies() {
|
ResultMatcher noCookies() {
|
||||||
return result -> assertThat(result.getResponse().getCookies()).isEmpty();
|
return (result) -> assertThat(result.getResponse().getCookies()).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
ResultMatcher session(Predicate<HttpSession> sessionPredicate) {
|
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"));
|
.is(new Condition<>(sessionPredicate, "sessionPredicate failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -190,7 +190,7 @@ public class NamespaceHttpLogoutTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.logout(logout ->
|
.logout((logout) ->
|
||||||
logout.deleteCookies("remove")
|
logout.deleteCookies("remove")
|
||||||
.invalidateHttpSession(false)
|
.invalidateHttpSession(false)
|
||||||
.logoutUrl("/custom-logout")
|
.logoutUrl("/custom-logout")
|
||||||
|
@ -227,7 +227,7 @@ public class NamespaceHttpLogoutTests {
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.logout(logout -> logout.logoutSuccessHandler(logoutSuccessHandler));
|
.logout((logout) -> logout.logoutSuccessHandler(logoutSuccessHandler));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -120,13 +120,13 @@ public class NamespaceHttpOpenIDLoginTests {
|
||||||
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
||||||
assertThat(attributeObject).isInstanceOf(List.class);
|
assertThat(attributeObject).isInstanceOf(List.class);
|
||||||
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
|
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()))
|
&& "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired()))
|
||||||
.isTrue();
|
.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()))
|
&& "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired()))
|
||||||
.isTrue();
|
.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()))
|
&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
|
||||||
.isTrue();
|
.isTrue();
|
||||||
}
|
}
|
||||||
|
|
|
@ -124,11 +124,11 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
)
|
)
|
||||||
.exceptionHandling(exceptionHandling ->
|
.exceptionHandling((exceptionHandling) ->
|
||||||
exceptionHandling.accessDeniedPage("/AccessDeniedPageConfig")
|
exceptionHandling.accessDeniedPage("/AccessDeniedPageConfig")
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
@ -167,11 +167,11 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
)
|
)
|
||||||
.exceptionHandling(exceptionHandling ->
|
.exceptionHandling((exceptionHandling) ->
|
||||||
exceptionHandling.accessDeniedHandler(accessDeniedHandler())
|
exceptionHandling.accessDeniedHandler(accessDeniedHandler())
|
||||||
);
|
);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
|
|
|
@ -273,7 +273,7 @@ public class NamespaceHttpX509Tests {
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
.and()
|
.and()
|
||||||
.x509()
|
.x509()
|
||||||
.userDetailsService(username -> USER);
|
.userDetailsService((username) -> USER);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -296,7 +296,7 @@ public class NamespaceHttpX509Tests {
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
.and()
|
.and()
|
||||||
.x509()
|
.x509()
|
||||||
.authenticationUserDetailsService(authentication -> USER);
|
.authenticationUserDetailsService((authentication) -> USER);
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -244,7 +244,7 @@ public class NamespaceRememberMeTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
static RequestPostProcessor rememberMeLogin(String parameterName, boolean parameterValue) {
|
static RequestPostProcessor rememberMeLogin(String parameterName, boolean parameterValue) {
|
||||||
return request -> {
|
return (request) -> {
|
||||||
csrf().postProcessRequest(request);
|
csrf().postProcessRequest(request);
|
||||||
request.setParameter("username", "user");
|
request.setParameter("username", "user");
|
||||||
request.setParameter("password", "password");
|
request.setParameter("password", "password");
|
||||||
|
|
|
@ -96,7 +96,7 @@ public class NamespaceSessionManagementTests {
|
||||||
public void authenticateWhenUsingInvalidSessionUrlThenMatchesNamespace() throws Exception {
|
public void authenticateWhenUsingInvalidSessionUrlThenMatchesNamespace() throws Exception {
|
||||||
this.spring.register(CustomSessionManagementConfig.class).autowire();
|
this.spring.register(CustomSessionManagementConfig.class).autowire();
|
||||||
|
|
||||||
this.mvc.perform(get("/auth").with(request -> {
|
this.mvc.perform(get("/auth").with((request) -> {
|
||||||
request.setRequestedSessionIdValid(false);
|
request.setRequestedSessionIdValid(false);
|
||||||
request.setRequestedSessionId("id");
|
request.setRequestedSessionId("id");
|
||||||
return request;
|
return request;
|
||||||
|
@ -137,7 +137,7 @@ public class NamespaceSessionManagementTests {
|
||||||
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
|
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
|
||||||
mock.setMethod("GET");
|
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"));
|
.andExpect(redirectedUrl("/session-auth-error"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -158,7 +158,7 @@ public class NamespaceSessionManagementTests {
|
||||||
public void authenticateWhenUsingCustomInvalidSessionStrategyThenMatchesNamespace() throws Exception {
|
public void authenticateWhenUsingCustomInvalidSessionStrategyThenMatchesNamespace() throws Exception {
|
||||||
this.spring.register(InvalidSessionStrategyConfig.class).autowire();
|
this.spring.register(InvalidSessionStrategyConfig.class).autowire();
|
||||||
|
|
||||||
this.mvc.perform(get("/auth").with(request -> {
|
this.mvc.perform(get("/auth").with((request) -> {
|
||||||
request.setRequestedSessionIdValid(false);
|
request.setRequestedSessionIdValid(false);
|
||||||
request.setRequestedSessionId("id");
|
request.setRequestedSessionId("id");
|
||||||
return request;
|
return request;
|
||||||
|
|
|
@ -91,11 +91,11 @@ public class PortMapperConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requiresChannel(requiresChannel ->
|
.requiresChannel((requiresChannel) ->
|
||||||
requiresChannel
|
requiresChannel
|
||||||
.anyRequest().requiresSecure()
|
.anyRequest().requiresSecure()
|
||||||
)
|
)
|
||||||
.portMapper(portMapper ->
|
.portMapper((portMapper) ->
|
||||||
portMapper
|
portMapper
|
||||||
.http(543).mapsTo(123)
|
.http(543).mapsTo(123)
|
||||||
);
|
);
|
||||||
|
@ -113,11 +113,11 @@ public class PortMapperConfigurerTests {
|
||||||
customPortMapper.setPortMappings(Collections.singletonMap("543", "123"));
|
customPortMapper.setPortMappings(Collections.singletonMap("543", "123"));
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requiresChannel(requiresChannel ->
|
.requiresChannel((requiresChannel) ->
|
||||||
requiresChannel
|
requiresChannel
|
||||||
.anyRequest().requiresSecure()
|
.anyRequest().requiresSecure()
|
||||||
)
|
)
|
||||||
.portMapper(portMapper ->
|
.portMapper((portMapper) ->
|
||||||
portMapper
|
portMapper
|
||||||
.portMapper(customPortMapper)
|
.portMapper(customPortMapper)
|
||||||
);
|
);
|
||||||
|
|
|
@ -121,7 +121,7 @@ public class RememberMeConfigurerTests {
|
||||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||||
|
|
||||||
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
|
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
|
||||||
.withAuthentication(auth -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
|
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -196,7 +196,7 @@ public class RememberMeConfigurerTests {
|
||||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||||
|
|
||||||
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
|
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
|
||||||
.withAuthentication(auth -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
|
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
|
@ -334,7 +334,7 @@ public class RememberMeConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
|
@ -389,12 +389,12 @@ public class RememberMeConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().hasRole("USER")
|
.anyRequest().hasRole("USER")
|
||||||
)
|
)
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.rememberMe(rememberMe ->
|
.rememberMe((rememberMe) ->
|
||||||
rememberMe
|
rememberMe
|
||||||
.rememberMeCookieDomain("spring.io")
|
.rememberMeCookieDomain("spring.io")
|
||||||
);
|
);
|
||||||
|
|
|
@ -333,7 +333,7 @@ public class RequestCacheConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
@ -351,7 +351,7 @@ public class RequestCacheConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
@ -369,12 +369,12 @@ public class RequestCacheConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.requestCache(requestCache ->
|
.requestCache((requestCache) ->
|
||||||
requestCache
|
requestCache
|
||||||
.requestCache(new NullRequestCache())
|
.requestCache(new NullRequestCache())
|
||||||
);
|
);
|
||||||
|
|
|
@ -87,15 +87,15 @@ public class RequestMatcherConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.requestMatchers(requestMatchers ->
|
.requestMatchers((requestMatchers) ->
|
||||||
requestMatchers
|
requestMatchers
|
||||||
.antMatchers("/api/**")
|
.antMatchers("/api/**")
|
||||||
)
|
)
|
||||||
.requestMatchers(requestMatchers ->
|
.requestMatchers((requestMatchers) ->
|
||||||
requestMatchers
|
requestMatchers
|
||||||
.antMatchers("/oauth/**")
|
.antMatchers("/oauth/**")
|
||||||
)
|
)
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
);
|
);
|
||||||
|
|
|
@ -252,7 +252,7 @@ public class SecurityContextConfigurerTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.securityContext(securityContext ->
|
.securityContext((securityContext) ->
|
||||||
securityContext
|
securityContext
|
||||||
.securityContextRepository(new NullSecurityContextRepository())
|
.securityContextRepository(new NullSecurityContextRepository())
|
||||||
);
|
);
|
||||||
|
|
|
@ -343,7 +343,7 @@ public class ServletApiConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.servletApi(servletApi ->
|
.servletApi((servletApi) ->
|
||||||
servletApi
|
servletApi
|
||||||
.rolePrefix("PERMISSION_")
|
.rolePrefix("PERMISSION_")
|
||||||
);
|
);
|
||||||
|
|
|
@ -362,9 +362,9 @@ public class SessionManagementConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.sessionManagement(sessionManagement ->
|
.sessionManagement((sessionManagement) ->
|
||||||
sessionManagement
|
sessionManagement
|
||||||
.sessionFixation(sessionFixation ->
|
.sessionFixation((sessionFixation) ->
|
||||||
sessionFixation.newSession()
|
sessionFixation.newSession()
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
@ -417,9 +417,9 @@ public class SessionManagementConfigurerTests {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.sessionManagement(sessionManagement ->
|
.sessionManagement((sessionManagement) ->
|
||||||
sessionManagement
|
sessionManagement
|
||||||
.sessionConcurrency(sessionConcurrency ->
|
.sessionConcurrency((sessionConcurrency) ->
|
||||||
sessionConcurrency
|
sessionConcurrency
|
||||||
.maximumSessions(1)
|
.maximumSessions(1)
|
||||||
.maxSessionsPreventsLogin(true)
|
.maxSessionsPreventsLogin(true)
|
||||||
|
@ -446,7 +446,7 @@ public class SessionManagementConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.sessionManagement(sessionManagement ->
|
.sessionManagement((sessionManagement) ->
|
||||||
sessionManagement
|
sessionManagement
|
||||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
);
|
);
|
||||||
|
|
|
@ -182,7 +182,7 @@ public class X509ConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.x509(x509 ->
|
.x509((x509) ->
|
||||||
x509
|
x509
|
||||||
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)")
|
.subjectPrincipalRegex("CN=(.*?)@example.com(?:,|$)")
|
||||||
);
|
);
|
||||||
|
|
|
@ -233,7 +233,7 @@ public class OAuth2ClientConfigurerTests {
|
||||||
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver;
|
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver;
|
||||||
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
|
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
|
||||||
given(authorizationRequestResolver.resolve(any()))
|
given(authorizationRequestResolver.resolve(any()))
|
||||||
.willAnswer(invocation -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
|
.willAnswer((invocation) -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
|
||||||
|
|
||||||
this.spring.register(OAuth2ClientConfig.class).autowire();
|
this.spring.register(OAuth2ClientConfig.class).autowire();
|
||||||
|
|
||||||
|
@ -295,7 +295,7 @@ public class OAuth2ClientConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
|
|
@ -586,7 +586,7 @@ public class OAuth2LoginConfigurerTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createOauth2AccessTokenResponseClient() {
|
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createOauth2AccessTokenResponseClient() {
|
||||||
return request -> {
|
return (request) -> {
|
||||||
Map<String, Object> additionalParameters = new HashMap<>();
|
Map<String, Object> additionalParameters = new HashMap<>();
|
||||||
if (request.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
|
if (request.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
|
||||||
additionalParameters.put(OidcParameterNames.ID_TOKEN, "token123");
|
additionalParameters.put(OidcParameterNames.ID_TOKEN, "token123");
|
||||||
|
@ -598,17 +598,17 @@ public class OAuth2LoginConfigurerTests {
|
||||||
|
|
||||||
private static OAuth2UserService<OAuth2UserRequest, OAuth2User> createOauth2UserService() {
|
private static OAuth2UserService<OAuth2UserRequest, OAuth2User> createOauth2UserService() {
|
||||||
Map<String, Object> userAttributes = Collections.singletonMap("name", "spring");
|
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");
|
userAttributes, "name");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static OAuth2UserService<OidcUserRequest, OidcUser> createOidcUserService() {
|
private static OAuth2UserService<OidcUserRequest, OidcUser> createOidcUserService() {
|
||||||
OidcIdToken idToken = TestOidcIdTokens.idToken().build();
|
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() {
|
private static GrantedAuthoritiesMapper createGrantedAuthoritiesMapper() {
|
||||||
return authorities -> {
|
return (authorities) -> {
|
||||||
boolean isOidc = OidcUserAuthority.class.isInstance(authorities.iterator().next());
|
boolean isOidc = OidcUserAuthority.class.isInstance(authorities.iterator().next());
|
||||||
List<GrantedAuthority> mappedAuthorities = new ArrayList<>(authorities);
|
List<GrantedAuthority> mappedAuthorities = new ArrayList<>(authorities);
|
||||||
mappedAuthorities.add(new SimpleGrantedAuthority(isOidc ? "ROLE_OIDC_USER" : "ROLE_OAUTH2_USER"));
|
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 {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2Login(oauth2Login ->
|
.oauth2Login((oauth2Login) ->
|
||||||
oauth2Login
|
oauth2Login
|
||||||
.clientRegistrationRepository(
|
.clientRegistrationRepository(
|
||||||
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
|
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
|
||||||
|
@ -811,10 +811,10 @@ public class OAuth2LoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2Login(oauth2Login ->
|
.oauth2Login((oauth2Login) ->
|
||||||
oauth2Login
|
oauth2Login
|
||||||
.clientRegistrationRepository(this.clientRegistrationRepository)
|
.clientRegistrationRepository(this.clientRegistrationRepository)
|
||||||
.authorizationEndpoint(authorizationEndpoint ->
|
.authorizationEndpoint((authorizationEndpoint) ->
|
||||||
authorizationEndpoint
|
authorizationEndpoint
|
||||||
.authorizationRequestResolver(this.resolver)
|
.authorizationRequestResolver(this.resolver)
|
||||||
)
|
)
|
||||||
|
@ -866,7 +866,7 @@ public class OAuth2LoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2Login(oauth2Login ->
|
.oauth2Login((oauth2Login) ->
|
||||||
oauth2Login
|
oauth2Login
|
||||||
.clientRegistrationRepository(
|
.clientRegistrationRepository(
|
||||||
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
|
new InMemoryClientRegistrationRepository(GOOGLE_CLIENT_REGISTRATION))
|
||||||
|
@ -945,21 +945,21 @@ public class OAuth2LoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.securityContext(securityContext ->
|
.securityContext((securityContext) ->
|
||||||
securityContext
|
securityContext
|
||||||
.securityContextRepository(securityContextRepository())
|
.securityContextRepository(securityContextRepository())
|
||||||
)
|
)
|
||||||
.oauth2Login(oauth2Login ->
|
.oauth2Login((oauth2Login) ->
|
||||||
oauth2Login
|
oauth2Login
|
||||||
.tokenEndpoint(tokenEndpoint ->
|
.tokenEndpoint((tokenEndpoint) ->
|
||||||
tokenEndpoint
|
tokenEndpoint
|
||||||
.accessTokenResponseClient(createOauth2AccessTokenResponseClient())
|
.accessTokenResponseClient(createOauth2AccessTokenResponseClient())
|
||||||
)
|
)
|
||||||
.userInfoEndpoint(userInfoEndpoint ->
|
.userInfoEndpoint((userInfoEndpoint) ->
|
||||||
userInfoEndpoint
|
userInfoEndpoint
|
||||||
.userService(createOauth2UserService())
|
.userService(createOauth2UserService())
|
||||||
.oidcUserService(createOidcUserService())
|
.oidcUserService(createOidcUserService())
|
||||||
|
@ -985,7 +985,7 @@ public class OAuth2LoginConfigurerTests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory() {
|
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory() {
|
||||||
return clientRegistration -> getJwtDecoder();
|
return (clientRegistration) -> getJwtDecoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static JwtDecoder getJwtDecoder() {
|
private static JwtDecoder getJwtDecoder() {
|
||||||
|
@ -994,7 +994,7 @@ public class OAuth2LoginConfigurerTests {
|
||||||
claims.put(IdTokenClaimNames.ISS, "http://localhost/iss");
|
claims.put(IdTokenClaimNames.ISS, "http://localhost/iss");
|
||||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("clientId", "a", "u", "d"));
|
claims.put(IdTokenClaimNames.AUD, Arrays.asList("clientId", "a", "u", "d"));
|
||||||
claims.put(IdTokenClaimNames.AZP, "clientId");
|
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);
|
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
|
||||||
given(jwtDecoder.decode(any())).willReturn(jwt);
|
given(jwtDecoder.decode(any())).willReturn(jwt);
|
||||||
return jwtDecoder;
|
return jwtDecoder;
|
||||||
|
@ -1007,12 +1007,12 @@ public class OAuth2LoginConfigurerTests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory1() {
|
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory1() {
|
||||||
return clientRegistration -> JwtDecoderFactoryConfig.getJwtDecoder();
|
return (clientRegistration) -> JwtDecoderFactoryConfig.getJwtDecoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory2() {
|
JwtDecoderFactory<ClientRegistration> jwtDecoderFactory2() {
|
||||||
return clientRegistration -> JwtDecoderFactoryConfig.getJwtDecoder();
|
return (clientRegistration) -> JwtDecoderFactoryConfig.getJwtDecoder();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1404,12 +1404,12 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
|
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(withDefaults())
|
.jwt(withDefaults())
|
||||||
);
|
);
|
||||||
|
@ -1450,14 +1450,14 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
|
.antMatchers("/requires-read-scope").access("hasAuthority('SCOPE_message:read')")
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(jwt ->
|
.jwt((jwt) ->
|
||||||
jwt
|
jwt
|
||||||
.jwkSetUri(this.jwkSetUri)
|
.jwkSetUri(this.jwkSetUri)
|
||||||
)
|
)
|
||||||
|
@ -1601,7 +1601,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
.anyRequest().denyAll()
|
.anyRequest().denyAll()
|
||||||
.and()
|
.and()
|
||||||
.exceptionHandling()
|
.exceptionHandling()
|
||||||
.defaultAccessDeniedHandlerFor(new AccessDeniedHandlerImpl(), request -> false)
|
.defaultAccessDeniedHandlerFor(new AccessDeniedHandlerImpl(), (request) -> false)
|
||||||
.and()
|
.and()
|
||||||
.httpBasic()
|
.httpBasic()
|
||||||
.and()
|
.and()
|
||||||
|
@ -1668,7 +1668,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() {
|
Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() {
|
||||||
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
|
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
|
||||||
converter.setJwtGrantedAuthoritiesConverter(
|
converter.setJwtGrantedAuthoritiesConverter(
|
||||||
jwt -> Collections.singletonList(new SimpleGrantedAuthority("message:read")));
|
(jwt) -> Collections.singletonList(new SimpleGrantedAuthority("message:read")));
|
||||||
return converter;
|
return converter;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1871,13 +1871,13 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(jwt ->
|
.jwt((jwt) ->
|
||||||
jwt
|
jwt
|
||||||
.decoder(decoder())
|
.decoder(decoder())
|
||||||
)
|
)
|
||||||
|
@ -2091,12 +2091,12 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.antMatchers("/requires-read-scope").hasAuthority("SCOPE_message:read")
|
.antMatchers("/requires-read-scope").hasAuthority("SCOPE_message:read")
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.opaqueToken(withDefaults())
|
.opaqueToken(withDefaults())
|
||||||
);
|
);
|
||||||
|
@ -2135,13 +2135,13 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.opaqueToken(opaqueToken ->
|
.opaqueToken((opaqueToken) ->
|
||||||
opaqueToken
|
opaqueToken
|
||||||
.authenticationManager(authenticationProvider()::authenticate)
|
.authenticationManager(authenticationProvider()::authenticate)
|
||||||
)
|
)
|
||||||
|
|
|
@ -127,11 +127,11 @@ public class OpenIDLoginConfigurerTests {
|
||||||
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
|
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
|
||||||
assertThat(
|
assertThat(
|
||||||
attributeList.stream()
|
attributeList.stream()
|
||||||
.anyMatch(attribute -> "nickname".equals(attribute.getName())
|
.anyMatch((attribute) -> "nickname".equals(attribute.getName())
|
||||||
&& "https://schema.openid.net/namePerson/friendly".equals(attribute.getType())))
|
&& "https://schema.openid.net/namePerson/friendly".equals(attribute.getType())))
|
||||||
.isTrue();
|
.isTrue();
|
||||||
assertThat(attributeList.stream()
|
assertThat(attributeList.stream()
|
||||||
.anyMatch(attribute -> "email".equals(attribute.getName())
|
.anyMatch((attribute) -> "email".equals(attribute.getName())
|
||||||
&& "https://schema.openid.net/contact/email".equals(attribute.getType())
|
&& "https://schema.openid.net/contact/email".equals(attribute.getType())
|
||||||
&& attribute.isRequired() && attribute.getCount() == 2)).isTrue();
|
&& attribute.isRequired() && attribute.getCount() == 2)).isTrue();
|
||||||
}
|
}
|
||||||
|
@ -231,11 +231,11 @@ public class OpenIDLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.openidLogin(openIdLogin ->
|
.openidLogin((openIdLogin) ->
|
||||||
openIdLogin
|
openIdLogin
|
||||||
.loginPage("/login/custom")
|
.loginPage("/login/custom")
|
||||||
);
|
);
|
||||||
|
@ -253,22 +253,22 @@ public class OpenIDLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
.openidLogin(openIdLogin ->
|
.openidLogin((openIdLogin) ->
|
||||||
openIdLogin
|
openIdLogin
|
||||||
.consumerManager(CONSUMER_MANAGER)
|
.consumerManager(CONSUMER_MANAGER)
|
||||||
.attributeExchange(attributeExchange ->
|
.attributeExchange((attributeExchange) ->
|
||||||
attributeExchange
|
attributeExchange
|
||||||
.identifierPattern(".*")
|
.identifierPattern(".*")
|
||||||
.attribute(nicknameAttribute ->
|
.attribute((nicknameAttribute) ->
|
||||||
nicknameAttribute
|
nicknameAttribute
|
||||||
.name("nickname")
|
.name("nickname")
|
||||||
.type("https://schema.openid.net/namePerson/friendly")
|
.type("https://schema.openid.net/namePerson/friendly")
|
||||||
)
|
)
|
||||||
.attribute(emailAttribute ->
|
.attribute((emailAttribute) ->
|
||||||
emailAttribute
|
emailAttribute
|
||||||
.name("email")
|
.name("email")
|
||||||
.type("https://schema.openid.net/contact/email")
|
.type("https://schema.openid.net/contact/email")
|
||||||
|
@ -291,14 +291,14 @@ public class OpenIDLoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authorizeRequests ->
|
.authorizeRequests((authorizeRequests) ->
|
||||||
authorizeRequests
|
authorizeRequests
|
||||||
.anyRequest().permitAll()
|
.anyRequest().permitAll()
|
||||||
)
|
)
|
||||||
.openidLogin(openIdLogin ->
|
.openidLogin((openIdLogin) ->
|
||||||
openIdLogin
|
openIdLogin
|
||||||
.consumerManager(CONSUMER_MANAGER)
|
.consumerManager(CONSUMER_MANAGER)
|
||||||
.attributeExchange(attributeExchange ->
|
.attributeExchange((attributeExchange) ->
|
||||||
attributeExchange
|
attributeExchange
|
||||||
.identifierPattern(".*")
|
.identifierPattern(".*")
|
||||||
.attribute(withDefaults())
|
.attribute(withDefaults())
|
||||||
|
|
|
@ -102,10 +102,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||||
*/
|
*/
|
||||||
public class Saml2LoginConfigurerTests {
|
public class Saml2LoginConfigurerTests {
|
||||||
|
|
||||||
private static final Converter<Assertion, Collection<? extends GrantedAuthority>> AUTHORITIES_EXTRACTOR = a -> Arrays
|
private static final Converter<Assertion, Collection<? extends GrantedAuthority>> AUTHORITIES_EXTRACTOR = (
|
||||||
.asList(new SimpleGrantedAuthority("TEST"));
|
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"));
|
.asList(new SimpleGrantedAuthority("TEST CONVERTED"));
|
||||||
|
|
||||||
private static final Duration RESPONSE_TIME_VALIDATION_SKEW = Duration.ZERO;
|
private static final Duration RESPONSE_TIME_VALIDATION_SKEW = Duration.ZERO;
|
||||||
|
@ -194,8 +194,8 @@ public class Saml2LoginConfigurerTests {
|
||||||
public void authenticateWhenCustomAuthenticationConverterThenUses() throws Exception {
|
public void authenticateWhenCustomAuthenticationConverterThenUses() throws Exception {
|
||||||
this.spring.register(CustomAuthenticationConverter.class).autowire();
|
this.spring.register(CustomAuthenticationConverter.class).autowire();
|
||||||
RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials()
|
RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials()
|
||||||
.assertingPartyDetails(party -> party.verificationX509Credentials(
|
.assertingPartyDetails((party) -> party.verificationX509Credentials(
|
||||||
c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
(c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||||
.build();
|
.build();
|
||||||
String response = new String(samlDecode(SIGNED_RESPONSE));
|
String response = new String(samlDecode(SIGNED_RESPONSE));
|
||||||
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
|
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
|
||||||
|
@ -212,7 +212,7 @@ public class Saml2LoginConfigurerTests {
|
||||||
"authenticationManager");
|
"authenticationManager");
|
||||||
ProviderManager pm = (ProviderManager) manager;
|
ProviderManager pm = (ProviderManager) manager;
|
||||||
AuthenticationProvider provider = pm.getProviders().stream()
|
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_EXTRACTOR, ReflectionTestUtils.getField(provider, "authoritiesExtractor"));
|
||||||
Assert.assertSame(AUTHORITIES_MAPPER, ReflectionTestUtils.getField(provider, "authoritiesMapper"));
|
Assert.assertSame(AUTHORITIES_MAPPER, ReflectionTestUtils.getField(provider, "authoritiesMapper"));
|
||||||
Assert.assertSame(RESPONSE_TIME_VALIDATION_SKEW,
|
Assert.assertSame(RESPONSE_TIME_VALIDATION_SKEW,
|
||||||
|
@ -221,7 +221,7 @@ public class Saml2LoginConfigurerTests {
|
||||||
|
|
||||||
private Saml2WebSsoAuthenticationFilter getSaml2SsoFilter(FilterChainProxy chain) {
|
private Saml2WebSsoAuthenticationFilter getSaml2SsoFilter(FilterChainProxy chain) {
|
||||||
return (Saml2WebSsoAuthenticationFilter) chain.getFilters("/login/saml2/sso/test").stream()
|
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 {
|
private void performSaml2Login(String expected) throws IOException, ServletException {
|
||||||
|
@ -324,7 +324,7 @@ public class Saml2LoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authz -> authz
|
.authorizeRequests((authz) -> authz
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.saml2Login(withDefaults());
|
.saml2Login(withDefaults());
|
||||||
|
@ -346,10 +346,10 @@ public class Saml2LoginConfigurerTests {
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeRequests(authz -> authz
|
.authorizeRequests((authz) -> authz
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
.saml2Login(saml2 -> {});
|
.saml2Login((saml2) -> {});
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -357,7 +357,7 @@ public class Saml2LoginConfigurerTests {
|
||||||
Saml2AuthenticationRequestFactory authenticationRequestFactory() {
|
Saml2AuthenticationRequestFactory authenticationRequestFactory() {
|
||||||
OpenSamlAuthenticationRequestFactory authenticationRequestFactory = new OpenSamlAuthenticationRequestFactory();
|
OpenSamlAuthenticationRequestFactory authenticationRequestFactory = new OpenSamlAuthenticationRequestFactory();
|
||||||
authenticationRequestFactory
|
authenticationRequestFactory
|
||||||
.setAuthnRequestConsumerResolver(context -> authnRequest -> authnRequest.setForceAuthn(true));
|
.setAuthnRequestConsumerResolver((context) -> (authnRequest) -> authnRequest.setForceAuthn(true));
|
||||||
return authenticationRequestFactory;
|
return authenticationRequestFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -371,8 +371,8 @@ public class Saml2LoginConfigurerTests {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
http.authorizeRequests(authz -> authz.anyRequest().authenticated())
|
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
|
||||||
.saml2Login(saml2 -> saml2.authenticationConverter(authenticationConverter));
|
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -112,7 +112,7 @@ public class EnableWebFluxSecurityTests {
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain).build();
|
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);
|
.exchange().expectStatus().isOk().returnResult(String.class);
|
||||||
result.assertWithDiagnostics(() -> assertThat(result.getResponseCookies().isEmpty()));
|
result.assertWithDiagnostics(() -> assertThat(result.getResponseCookies().isEmpty()));
|
||||||
}
|
}
|
||||||
|
@ -126,16 +126,16 @@ public class EnableWebFluxSecurityTests {
|
||||||
WebTestClient client = WebTestClientBuilder
|
WebTestClient client = WebTestClientBuilder
|
||||||
.bindToWebFilters(
|
.bindToWebFilters(
|
||||||
(exchange, chain) -> contextRepository.save(exchange, context)
|
(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,
|
this.springSecurityFilterChain,
|
||||||
(exchange,
|
(exchange,
|
||||||
chain) -> ReactiveSecurityContextHolder.getContext()
|
chain) -> ReactiveSecurityContextHolder.getContext()
|
||||||
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
|
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
|
||||||
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class)
|
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
|
@Test
|
||||||
|
@ -145,13 +145,13 @@ public class EnableWebFluxSecurityTests {
|
||||||
.bindToWebFilters(this.springSecurityFilterChain,
|
.bindToWebFilters(this.springSecurityFilterChain,
|
||||||
(exchange,
|
(exchange,
|
||||||
chain) -> ReactiveSecurityContextHolder.getContext()
|
chain) -> ReactiveSecurityContextHolder.getContext()
|
||||||
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
|
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
|
||||||
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
||||||
.build();
|
.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)
|
.isOk().expectBody(String.class)
|
||||||
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("user"));
|
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -171,13 +171,13 @@ public class EnableWebFluxSecurityTests {
|
||||||
.bindToWebFilters(this.springSecurityFilterChain,
|
.bindToWebFilters(this.springSecurityFilterChain,
|
||||||
(exchange,
|
(exchange,
|
||||||
chain) -> ReactiveSecurityContextHolder.getContext()
|
chain) -> ReactiveSecurityContextHolder.getContext()
|
||||||
.map(SecurityContext::getAuthentication).flatMap(principal -> exchange
|
.map(SecurityContext::getAuthentication).flatMap((principal) -> exchange
|
||||||
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
||||||
.build();
|
.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)
|
.isOk().expectBody(String.class)
|
||||||
.consumeWith(result -> assertThat(result.getResponseBody()).isEqualTo("user"));
|
.consumeWith((result) -> assertThat(result.getResponseBody()).isEqualTo("user"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -185,7 +185,7 @@ public class EnableWebFluxSecurityTests {
|
||||||
this.spring.register(MapReactiveUserDetailsServiceConfig.class).autowire();
|
this.spring.register(MapReactiveUserDetailsServiceConfig.class).autowire();
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain).build();
|
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);
|
ReactiveUserDetailsService users = this.spring.getContext().getBean(ReactiveUserDetailsService.class);
|
||||||
assertThat(users.findByUsername("user").block().getPassword()).startsWith("{bcrypt}");
|
assertThat(users.findByUsername("user").block().getPassword()).startsWith("{bcrypt}");
|
||||||
|
@ -195,8 +195,8 @@ public class EnableWebFluxSecurityTests {
|
||||||
public void formLoginWorks() {
|
public void formLoginWorks() {
|
||||||
this.spring.register(Config.class).autowire();
|
this.spring.register(Config.class).autowire();
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain, (exchange,
|
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.springSecurityFilterChain, (exchange,
|
||||||
chain) -> Mono.subscriberContext().flatMap(c -> c.<Mono<Principal>>get(Authentication.class)).flatMap(
|
chain) -> Mono.subscriberContext().flatMap((c) -> c.<Mono<Principal>>get(Authentication.class)).flatMap(
|
||||||
principal -> exchange.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
(principal) -> exchange.getResponse().writeWith(Mono.just(toDataBuffer(principal.getName())))))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
|
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
|
||||||
|
|
|
@ -146,7 +146,7 @@ public class RsaKeyConversionServicePostProcessorTests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
BeanFactoryPostProcessor conversionServiceCustomizer() {
|
BeanFactoryPostProcessor conversionServiceCustomizer() {
|
||||||
return beanFactory -> beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
|
return (beanFactory) -> beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
|
||||||
.setResourceLoader(new CustomResourceLoader());
|
.setResourceLoader(new CustomResourceLoader());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -158,7 +158,7 @@ public class RsaKeyConversionServicePostProcessorTests {
|
||||||
@Bean
|
@Bean
|
||||||
ConversionService conversionService() {
|
ConversionService conversionService() {
|
||||||
GenericConversionService service = new GenericConversionService();
|
GenericConversionService service = new GenericConversionService();
|
||||||
service.addConverter(String.class, RSAPublicKey.class, source -> {
|
service.addConverter(String.class, RSAPublicKey.class, (source) -> {
|
||||||
throw new IllegalArgumentException("unsupported");
|
throw new IllegalArgumentException("unsupported");
|
||||||
});
|
});
|
||||||
return service;
|
return service;
|
||||||
|
|
|
@ -130,9 +130,9 @@ public class Element {
|
||||||
Collection<String> ids = new ArrayList<>();
|
Collection<String> ids = new ArrayList<>();
|
||||||
ids.add(getId());
|
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()) {
|
if (!this.childElmts.isEmpty()) {
|
||||||
ids.add(getId() + "-children");
|
ids.add(getId() + "-children");
|
||||||
|
@ -152,7 +152,8 @@ public class Element {
|
||||||
public Map<String, Element> getAllChildElmts() {
|
public Map<String, Element> getAllChildElmts() {
|
||||||
Map<String, Element> result = new HashMap<>();
|
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);
|
result.putAll(this.childElmts);
|
||||||
|
|
||||||
|
@ -162,7 +163,8 @@ public class Element {
|
||||||
public Map<String, Element> getAllParentElmts() {
|
public Map<String, Element> getAllParentElmts() {
|
||||||
Map<String, Element> result = new HashMap<>();
|
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);
|
result.putAll(this.parentElmts);
|
||||||
|
|
||||||
|
|
|
@ -61,7 +61,7 @@ public class SpringSecurityXsdParser {
|
||||||
private Map<String, Element> elements(XmlNode node) {
|
private Map<String, Element> elements(XmlNode node) {
|
||||||
Map<String, Element> elementNameToElement = new HashMap<>();
|
Map<String, Element> elementNameToElement = new HashMap<>();
|
||||||
|
|
||||||
node.children().forEach(child -> {
|
node.children().forEach((child) -> {
|
||||||
if ("element".equals(child.simpleName())) {
|
if ("element".equals(child.simpleName())) {
|
||||||
Element e = elmt(child);
|
Element e = elmt(child);
|
||||||
elementNameToElement.put(e.getName(), e);
|
elementNameToElement.put(e.getName(), e);
|
||||||
|
@ -81,7 +81,7 @@ public class SpringSecurityXsdParser {
|
||||||
*/
|
*/
|
||||||
private Collection<Attribute> attrs(XmlNode element) {
|
private Collection<Attribute> attrs(XmlNode element) {
|
||||||
Collection<Attribute> attrs = new ArrayList<>();
|
Collection<Attribute> attrs = new ArrayList<>();
|
||||||
element.children().forEach(c -> {
|
element.children().forEach((c) -> {
|
||||||
String name = c.simpleName();
|
String name = c.simpleName();
|
||||||
if ("attribute".equals(name)) {
|
if ("attribute".equals(name)) {
|
||||||
attrs.add(attr(c));
|
attrs.add(attr(c));
|
||||||
|
@ -103,7 +103,7 @@ public class SpringSecurityXsdParser {
|
||||||
private Collection<Attribute> attrgrps(XmlNode element) {
|
private Collection<Attribute> attrgrps(XmlNode element) {
|
||||||
Collection<Attribute> attrgrp = new ArrayList<>();
|
Collection<Attribute> attrgrp = new ArrayList<>();
|
||||||
|
|
||||||
element.children().forEach(c -> {
|
element.children().forEach((c) -> {
|
||||||
if (!"element".equals(c.simpleName())) {
|
if (!"element".equals(c.simpleName())) {
|
||||||
if ("attributeGroup".equals(c.simpleName())) {
|
if ("attributeGroup".equals(c.simpleName())) {
|
||||||
if (c.attribute("name") != null) {
|
if (c.attribute("name") != null) {
|
||||||
|
@ -130,7 +130,7 @@ public class SpringSecurityXsdParser {
|
||||||
root = root.parent().get();
|
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);
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -157,8 +157,8 @@ public class SpringSecurityXsdParser {
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
private String desc(XmlNode element) {
|
private String desc(XmlNode element) {
|
||||||
return element.child("annotation").flatMap(annotation -> annotation.child("documentation"))
|
return element.child("annotation").flatMap((annotation) -> annotation.child("documentation"))
|
||||||
.map(documentation -> documentation.text()).orElse(null);
|
.map((documentation) -> documentation.text()).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -197,8 +197,8 @@ public class SpringSecurityXsdParser {
|
||||||
e.setChildElmts(elements(n));
|
e.setChildElmts(elements(n));
|
||||||
e.setAttrs(attrs(n));
|
e.setAttrs(attrs(n));
|
||||||
e.getAttrs().addAll(attrgrps(n));
|
e.getAttrs().addAll(attrgrps(n));
|
||||||
e.getAttrs().forEach(attr -> attr.setElmt(e));
|
e.getAttrs().forEach((attr) -> attr.setElmt(e));
|
||||||
e.getChildElmts().values().forEach(element -> element.getParentElmts().put(e.getName(), e));
|
e.getChildElmts().values().forEach((element) -> element.getParentElmts().put(e.getName(), e));
|
||||||
|
|
||||||
String subGrpName = n.attribute("substitutionGroup");
|
String subGrpName = n.attribute("substitutionGroup");
|
||||||
if (!StringUtils.isEmpty(subGrpName)) {
|
if (!StringUtils.isEmpty(subGrpName)) {
|
||||||
|
|
|
@ -50,16 +50,16 @@ public class XmlNode {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Optional<XmlNode> child(String name) {
|
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() {
|
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) {
|
public String attribute(String name) {
|
||||||
return Optional.ofNullable(this.node.getAttributes()).map(attrs -> attrs.getNamedItem(name))
|
return Optional.ofNullable(this.node.getAttributes()).map((attrs) -> attrs.getNamedItem(name))
|
||||||
.map(attr -> attr.getTextContent()).orElse(null);
|
.map((attr) -> attr.getTextContent()).orElse(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Node node() {
|
public Node node() {
|
||||||
|
|
|
@ -70,9 +70,9 @@ public class XsdDocumentedTests {
|
||||||
XmlNode root = this.xml.parse(this.schemaDocumentLocation);
|
XmlNode root = this.xml.parse(this.schemaDocumentLocation);
|
||||||
|
|
||||||
List<String> nodes = root.child("schema").map(XmlNode::children).orElse(Stream.empty())
|
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")))
|
&& "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());
|
.filter(StringUtils::isNotEmpty).collect(Collectors.toList());
|
||||||
|
|
||||||
SecurityFiltersAssertions.assertEquals(nodes);
|
SecurityFiltersAssertions.assertEquals(nodes);
|
||||||
|
@ -91,9 +91,9 @@ public class XsdDocumentedTests {
|
||||||
XmlNode root = this.xml.parse(this.schema31xDocumentLocation);
|
XmlNode root = this.xml.parse(this.schema31xDocumentLocation);
|
||||||
|
|
||||||
List<String> nodes = root.child("schema").map(XmlNode::children).orElse(Stream.empty())
|
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")))
|
&& "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());
|
.filter(StringUtils::isNotEmpty).collect(Collectors.toList());
|
||||||
|
|
||||||
assertThat(nodes).isEqualTo(expected);
|
assertThat(nodes).isEqualTo(expected);
|
||||||
|
@ -129,11 +129,11 @@ public class XsdDocumentedTests {
|
||||||
Map<String, Element> elementsByElementName = this.xml.elementsByElementName(this.schemaDocumentLocation);
|
Map<String, Element> elementsByElementName = this.xml.elementsByElementName(this.schemaDocumentLocation);
|
||||||
|
|
||||||
List<String> documentIds = Files.lines(Paths.get(this.referenceLocation))
|
List<String> documentIds = Files.lines(Paths.get(this.referenceLocation))
|
||||||
.filter(line -> line.matches("\\[\\[(nsa-.*)\\]\\]")).map(line -> line.substring(2, line.length() - 2))
|
.filter((line) -> line.matches("\\[\\[(nsa-.*)\\]\\]"))
|
||||||
.collect(Collectors.toList());
|
.map((line) -> line.substring(2, line.length() - 2)).collect(Collectors.toList());
|
||||||
|
|
||||||
Set<String> expectedIds = elementsByElementName.values().stream().flatMap(element -> element.getIds().stream())
|
Set<String> expectedIds = elementsByElementName.values().stream()
|
||||||
.collect(Collectors.toSet());
|
.flatMap((element) -> element.getIds().stream()).collect(Collectors.toSet());
|
||||||
|
|
||||||
documentIds.removeAll(this.ignoredIds);
|
documentIds.removeAll(this.ignoredIds);
|
||||||
expectedIds.removeAll(this.ignoredIds);
|
expectedIds.removeAll(this.ignoredIds);
|
||||||
|
@ -179,7 +179,7 @@ public class XsdDocumentedTests {
|
||||||
String expression = "^\\* <<(nsa-.*),.*>>$";
|
String expression = "^\\* <<(nsa-.*),.*>>$";
|
||||||
if (line.matches(expression)) {
|
if (line.matches(expression)) {
|
||||||
String elmtId = line.replaceAll(expression, "$1");
|
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>> schemaAttrNameToChildren = new HashMap<>();
|
||||||
Map<String, List<String>> schemaAttrNameToParents = new HashMap<>();
|
Map<String, List<String>> schemaAttrNameToParents = new HashMap<>();
|
||||||
|
|
||||||
elementNameToElement.entrySet().stream().forEach(entry -> {
|
elementNameToElement.entrySet().stream().forEach((entry) -> {
|
||||||
String key = "nsa-" + entry.getKey();
|
String key = "nsa-" + entry.getKey();
|
||||||
if (this.ignoredIds.contains(key)) {
|
if (this.ignoredIds.contains(key)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> parentIds = entry.getValue().getAllParentElmts().values().stream()
|
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());
|
.sorted().collect(Collectors.toList());
|
||||||
if (!parentIds.isEmpty()) {
|
if (!parentIds.isEmpty()) {
|
||||||
schemaAttrNameToParents.put(key, parentIds);
|
schemaAttrNameToParents.put(key, parentIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
List<String> childIds = entry.getValue().getAllChildElmts().values().stream()
|
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());
|
.sorted().collect(Collectors.toList());
|
||||||
if (!childIds.isEmpty()) {
|
if (!childIds.isEmpty()) {
|
||||||
schemaAttrNameToChildren.put(key, childIds);
|
schemaAttrNameToChildren.put(key, childIds);
|
||||||
|
@ -224,12 +224,14 @@ public class XsdDocumentedTests {
|
||||||
Map<String, Element> elementNameToElement = this.xml.elementsByElementName(this.schemaDocumentLocation);
|
Map<String, Element> elementNameToElement = this.xml.elementsByElementName(this.schemaDocumentLocation);
|
||||||
|
|
||||||
String notDocElmtIds = elementNameToElement.values().stream()
|
String notDocElmtIds = elementNameToElement.values().stream()
|
||||||
.filter(element -> StringUtils.isEmpty(element.getDesc()) && !this.ignoredIds.contains(element.getId()))
|
.filter((element) -> StringUtils.isEmpty(element.getDesc())
|
||||||
.map(element -> element.getId()).sorted().collect(Collectors.joining("\n"));
|
&& !this.ignoredIds.contains(element.getId()))
|
||||||
|
.map((element) -> element.getId()).sorted().collect(Collectors.joining("\n"));
|
||||||
|
|
||||||
String notDocAttrIds = elementNameToElement.values().stream().flatMap(element -> element.getAttrs().stream())
|
String notDocAttrIds = elementNameToElement.values().stream().flatMap((element) -> element.getAttrs().stream())
|
||||||
.filter(element -> StringUtils.isEmpty(element.getDesc()) && !this.ignoredIds.contains(element.getId()))
|
.filter((element) -> StringUtils.isEmpty(element.getDesc())
|
||||||
.map(element -> element.getId()).sorted().collect(Collectors.joining("\n"));
|
&& !this.ignoredIds.contains(element.getId()))
|
||||||
|
.map((element) -> element.getId()).sorted().collect(Collectors.joining("\n"));
|
||||||
|
|
||||||
assertThat(notDocElmtIds).isEmpty();
|
assertThat(notDocElmtIds).isEmpty();
|
||||||
assertThat(notDocAttrIds).isEmpty();
|
assertThat(notDocAttrIds).isEmpty();
|
||||||
|
|
|
@ -142,7 +142,7 @@ public class CsrfConfigTests {
|
||||||
this.spring.configLocations(this.xml("shared-controllers"), this.xml("AutoConfig")).autowire();
|
this.spring.configLocations(this.xml("shared-controllers"), this.xml("AutoConfig")).autowire();
|
||||||
|
|
||||||
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
|
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
|
||||||
.addDispatcherServletCustomizer(dispatcherServlet -> dispatcherServlet.setDispatchTraceRequest(true))
|
.addDispatcherServletCustomizer((dispatcherServlet) -> dispatcherServlet.setDispatchTraceRequest(true))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
traceEnabled.perform(request(HttpMethod.TRACE, "/csrf-in-header")).andExpect(csrfInHeader());
|
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();
|
this.spring.configLocations(this.xml("shared-controllers"), this.xml("CsrfEnabled")).autowire();
|
||||||
|
|
||||||
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
|
MockMvc traceEnabled = MockMvcBuilders.webAppContextSetup(this.spring.getContext()).apply(springSecurity())
|
||||||
.addDispatcherServletCustomizer(dispatcherServlet -> dispatcherServlet.setDispatchTraceRequest(true))
|
.addDispatcherServletCustomizer((dispatcherServlet) -> dispatcherServlet.setDispatchTraceRequest(true))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
traceEnabled.perform(request(HttpMethod.TRACE, "/csrf-in-header")).andExpect(csrfInHeader());
|
traceEnabled.perform(request(HttpMethod.TRACE, "/csrf-in-header")).andExpect(csrfInHeader());
|
||||||
|
@ -425,11 +425,11 @@ public class CsrfConfigTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
ResultMatcher csrfInHeader() {
|
ResultMatcher csrfInHeader() {
|
||||||
return new CsrfReturnedResultMatcher(result -> result.getResponse().getHeader("X-CSRF-TOKEN"));
|
return new CsrfReturnedResultMatcher((result) -> result.getResponse().getHeader("X-CSRF-TOKEN"));
|
||||||
}
|
}
|
||||||
|
|
||||||
ResultMatcher csrfInBody() {
|
ResultMatcher csrfInBody() {
|
||||||
return new CsrfReturnedResultMatcher(result -> result.getResponse().getContentAsString());
|
return new CsrfReturnedResultMatcher((result) -> result.getResponse().getContentAsString());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Controller
|
@Controller
|
||||||
|
|
|
@ -126,7 +126,7 @@ public class HttpCorsConfigTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResultMatcher corsResponseHeaders() {
|
private ResultMatcher corsResponseHeaders() {
|
||||||
return result -> {
|
return (result) -> {
|
||||||
header().exists("Access-Control-Allow-Origin").match(result);
|
header().exists("Access-Control-Allow-Origin").match(result);
|
||||||
header().exists("X-Content-Type-Options").match(result);
|
header().exists("X-Content-Type-Options").match(result);
|
||||||
};
|
};
|
||||||
|
|
|
@ -659,7 +659,7 @@ public class HttpHeadersConfigTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ResultMatcher includes(Map<String, String> headers) {
|
private static ResultMatcher includes(Map<String, String> headers) {
|
||||||
return result -> {
|
return (result) -> {
|
||||||
for (Map.Entry<String, String> header : headers.entrySet()) {
|
for (Map.Entry<String, String> header : headers.entrySet()) {
|
||||||
header().string(header.getKey(), header.getValue()).match(result);
|
header().string(header.getKey(), header.getValue()).match(result);
|
||||||
}
|
}
|
||||||
|
@ -671,7 +671,7 @@ public class HttpHeadersConfigTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ResultMatcher excludes(Collection<String> headers) {
|
private static ResultMatcher excludes(Collection<String> headers) {
|
||||||
return result -> {
|
return (result) -> {
|
||||||
for (String name : headers) {
|
for (String name : headers) {
|
||||||
header().doesNotExist(name).match(result);
|
header().doesNotExist(name).match(result);
|
||||||
}
|
}
|
||||||
|
|
|
@ -214,7 +214,7 @@ public class InterceptUrlConfigTests {
|
||||||
MockServletContext servletContext = spy(new MockServletContext());
|
MockServletContext servletContext = spy(new MockServletContext());
|
||||||
final ServletRegistration registration = mock(ServletRegistration.class);
|
final ServletRegistration registration = mock(ServletRegistration.class);
|
||||||
given(registration.getMappings()).willReturn(Collections.singleton(servletPath));
|
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);
|
registration);
|
||||||
given(servletContext.getServletRegistrations()).willAnswer(answer);
|
given(servletContext.getServletRegistrations()).willAnswer(answer);
|
||||||
return servletContext;
|
return servletContext;
|
||||||
|
|
|
@ -340,7 +340,7 @@ public class MiscHttpConfigTests {
|
||||||
|
|
||||||
Class<?> userFilterClass = this.spring.getContext().getBean("userFilter").getClass();
|
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, userFilterClass, SecurityContextPersistenceFilter.class, LogoutFilter.class,
|
||||||
userFilterClass);
|
userFilterClass);
|
||||||
}
|
}
|
||||||
|
@ -355,7 +355,7 @@ public class MiscHttpConfigTests {
|
||||||
public void configureWhenUsingX509ThenAddsX509FilterCorrectly() {
|
public void configureWhenUsingX509ThenAddsX509FilterCorrectly() {
|
||||||
this.spring.configLocations(xml("X509")).autowire();
|
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,
|
.containsSubsequence(CsrfFilter.class, X509AuthenticationFilter.class,
|
||||||
ExceptionTranslationFilter.class);
|
ExceptionTranslationFilter.class);
|
||||||
}
|
}
|
||||||
|
@ -384,7 +384,7 @@ public class MiscHttpConfigTests {
|
||||||
|
|
||||||
List<String> values = result.getResponse().getHeaders("Set-Cookie");
|
List<String> values = result.getResponse().getHeaders("Set-Cookie");
|
||||||
assertThat(values.size()).isEqualTo(2);
|
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
|
@Test
|
||||||
|
@ -587,7 +587,7 @@ public class MiscHttpConfigTests {
|
||||||
Principal user = mock(Principal.class);
|
Principal user = mock(Principal.class);
|
||||||
given(user.getName()).willReturn("joe");
|
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("admin");
|
||||||
request.addUserRole("user");
|
request.addUserRole("user");
|
||||||
request.addUserRole("unmapped");
|
request.addUserRole("unmapped");
|
||||||
|
@ -703,7 +703,7 @@ public class MiscHttpConfigTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private Answer<ILoggingEvent> writeTo(OutputStream os) {
|
private Answer<ILoggingEvent> writeTo(OutputStream os) {
|
||||||
return invocation -> {
|
return (invocation) -> {
|
||||||
os.write(invocation.getArgument(0).toString().getBytes());
|
os.write(invocation.getArgument(0).toString().getBytes());
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
|
@ -274,7 +274,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||||
|
|
||||||
Jwt jwt = TestJwts.user();
|
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<>();
|
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||||
params.add("code", "code123");
|
params.add("code", "code123");
|
||||||
|
@ -331,7 +331,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||||
|
|
||||||
Jwt jwt = TestJwts.user();
|
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()))
|
given(this.userAuthoritiesMapper.mapAuthorities(any()))
|
||||||
.willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));
|
.willReturn((Collection) AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"));
|
||||||
|
|
|
@ -678,7 +678,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||||
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver = this.spring.getContext()
|
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver = this.spring.getContext()
|
||||||
.getBean(AuthenticationManagerResolver.class);
|
.getBean(AuthenticationManagerResolver.class);
|
||||||
given(authenticationManagerResolver.resolve(any(HttpServletRequest.class))).willReturn(
|
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());
|
this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());
|
||||||
|
|
||||||
|
|
|
@ -118,7 +118,7 @@ public class OpenIDConfigTests {
|
||||||
|
|
||||||
OpenIDConsumer consumer = mock(OpenIDConsumer.class);
|
OpenIDConsumer consumer = mock(OpenIDConsumer.class);
|
||||||
given(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString()))
|
given(consumer.beginConsumption(any(HttpServletRequest.class), anyString(), anyString(), anyString()))
|
||||||
.will(invocation -> openIdEndpointUrl + invocation.getArgument(2));
|
.will((invocation) -> openIdEndpointUrl + invocation.getArgument(2));
|
||||||
openIDFilter.setConsumer(consumer);
|
openIDFilter.setConsumer(consumer);
|
||||||
|
|
||||||
String expectedReturnTo = new StringBuilder("http://localhost/login/openid").append("?")
|
String expectedReturnTo = new StringBuilder("http://localhost/login/openid").append("?")
|
||||||
|
@ -155,7 +155,7 @@ public class OpenIDConfigTests {
|
||||||
this.mvc.perform(
|
this.mvc.perform(
|
||||||
get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint))
|
get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint))
|
||||||
.andExpect(status().isFound())
|
.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.type.nickname=http%3A%2F%2Fschema.openid.net%2FnamePerson%2Ffriendly&"
|
||||||
+ "openid.ext1.if_available=nickname&"
|
+ "openid.ext1.if_available=nickname&"
|
||||||
+ "openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&"
|
+ "openid.ext1.type.email=http%3A%2F%2Fschema.openid.net%2Fcontact%2Femail&"
|
||||||
|
|
|
@ -378,7 +378,7 @@ public class SessionManagementConfigTests {
|
||||||
|
|
||||||
this.spring.configLocations(this.xml("SessionFixationProtectionNoneWithInvalidSessionUrl")).autowire();
|
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.setRequestedSessionId("1");
|
||||||
request.setRequestedSessionIdValid(false);
|
request.setRequestedSessionIdValid(false);
|
||||||
return request;
|
return request;
|
||||||
|
|
|
@ -64,8 +64,8 @@ public class AuthorizeExchangeSpecTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void antMatchersWhenPatternsInLambdaThenAnyMethod() {
|
public void antMatchersWhenPatternsInLambdaThenAnyMethod() {
|
||||||
this.http.csrf(ServerHttpSecurity.CsrfSpec::disable)
|
this.http.csrf(ServerHttpSecurity.CsrfSpec::disable).authorizeExchange(
|
||||||
.authorizeExchange(exchanges -> exchanges.pathMatchers("/a", "/b").denyAll().anyExchange().permitAll());
|
(exchanges) -> exchanges.pathMatchers("/a", "/b").denyAll().anyExchange().permitAll());
|
||||||
|
|
||||||
WebTestClient client = buildClient();
|
WebTestClient client = buildClient();
|
||||||
|
|
||||||
|
@ -97,7 +97,7 @@ public class AuthorizeExchangeSpecTests {
|
||||||
|
|
||||||
@Test(expected = IllegalStateException.class)
|
@Test(expected = IllegalStateException.class)
|
||||||
public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() {
|
public void buildWhenMatcherDefinedWithNoAccessInLambdaThenThrowsException() {
|
||||||
this.http.authorizeExchange(exchanges -> exchanges.pathMatchers("/incomplete"));
|
this.http.authorizeExchange((exchanges) -> exchanges.pathMatchers("/incomplete"));
|
||||||
this.http.build();
|
this.http.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -78,7 +78,7 @@ public class CorsSpecTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void corsWhenEnabledInLambdaThenAccessControlAllowOriginAndSecurityHeaders() {
|
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("Access-Control-Allow-Origin", "*");
|
||||||
this.expectedHeaders.set("X-Frame-Options", "DENY");
|
this.expectedHeaders.set("X-Frame-Options", "DENY");
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
|
@ -104,7 +104,7 @@ public class CorsSpecTests {
|
||||||
private void assertHeaders() {
|
private void assertHeaders() {
|
||||||
WebTestClient client = buildClient();
|
WebTestClient client = buildClient();
|
||||||
FluxExchangeResult<String> response = client.get().uri("https://example.com/")
|
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();
|
Map<String, List<String>> responseHeaders = response.getResponseHeaders();
|
||||||
|
|
||||||
|
|
|
@ -52,7 +52,7 @@ public class ExceptionHandlingSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAuthenticationEntryPointUsed() {
|
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAuthenticationEntryPointUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
|
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated())
|
||||||
.exceptionHandling(withDefaults()).build();
|
.exceptionHandling(withDefaults()).build();
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
||||||
|
@ -75,8 +75,8 @@ public class ExceptionHandlingSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void requestWhenCustomAuthenticationEntryPointInLambdaThenCustomAuthenticationEntryPointUsed() {
|
public void requestWhenCustomAuthenticationEntryPointInLambdaThenCustomAuthenticationEntryPointUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
|
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated())
|
||||||
.exceptionHandling(exceptionHandling -> exceptionHandling
|
.exceptionHandling((exceptionHandling) -> exceptionHandling
|
||||||
.authenticationEntryPoint(redirectServerAuthenticationEntryPoint("/auth")))
|
.authenticationEntryPoint(redirectServerAuthenticationEntryPoint("/auth")))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
@ -92,19 +92,19 @@ public class ExceptionHandlingSpecTests {
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).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();
|
.expectStatus().isForbidden();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAccessDeniedHandlerUsed() {
|
public void requestWhenExceptionHandlingWithDefaultsInLambdaThenDefaultAccessDeniedHandlerUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
|
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
|
||||||
.authorizeExchange(exchanges -> exchanges.anyExchange().hasRole("ADMIN"))
|
.authorizeExchange((exchanges) -> exchanges.anyExchange().hasRole("ADMIN"))
|
||||||
.exceptionHandling(withDefaults()).build();
|
.exceptionHandling(withDefaults()).build();
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).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();
|
.expectStatus().isForbidden();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -116,21 +116,21 @@ public class ExceptionHandlingSpecTests {
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).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();
|
.expectStatus().isBadRequest();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void requestWhenCustomAccessDeniedHandlerInLambdaThenCustomAccessDeniedHandlerUsed() {
|
public void requestWhenCustomAccessDeniedHandlerInLambdaThenCustomAccessDeniedHandlerUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
|
SecurityWebFilterChain securityWebFilter = this.http.httpBasic(withDefaults())
|
||||||
.authorizeExchange(exchanges -> exchanges.anyExchange().hasRole("ADMIN"))
|
.authorizeExchange((exchanges) -> exchanges.anyExchange().hasRole("ADMIN"))
|
||||||
.exceptionHandling(exceptionHandling -> exceptionHandling
|
.exceptionHandling((exceptionHandling) -> exceptionHandling
|
||||||
.accessDeniedHandler(httpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST)))
|
.accessDeniedHandler(httpStatusServerAccessDeniedHandler(HttpStatus.BAD_REQUEST)))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityWebFilter).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();
|
.expectStatus().isBadRequest();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -92,7 +92,7 @@ public class FormLoginTests {
|
||||||
@Test
|
@Test
|
||||||
public void formLoginWhenDefaultsInLambdaThenCreatesDefaultLoginPage() {
|
public void formLoginWhenDefaultsInLambdaThenCreatesDefaultLoginPage() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated()).formLogin(withDefaults())
|
.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated()).formLogin(withDefaults())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
||||||
|
@ -135,8 +135,8 @@ public class FormLoginTests {
|
||||||
public void formLoginWhenCustomLoginPageInLambdaThenUsed() {
|
public void formLoginWhenCustomLoginPageInLambdaThenUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(
|
.authorizeExchange(
|
||||||
exchanges -> exchanges.pathMatchers("/login").permitAll().anyExchange().authenticated())
|
(exchanges) -> exchanges.pathMatchers("/login").permitAll().anyExchange().authenticated())
|
||||||
.formLogin(formLogin -> formLogin.loginPage("/login")).build();
|
.formLogin((formLogin) -> formLogin.loginPage("/login")).build();
|
||||||
|
|
||||||
WebTestClient webTestClient = WebTestClient
|
WebTestClient webTestClient = WebTestClient
|
||||||
.bindToController(new CustomLoginPageController(), new WebTestClientBuilder.Http200RestController())
|
.bindToController(new CustomLoginPageController(), new WebTestClientBuilder.Http200RestController())
|
||||||
|
@ -479,7 +479,7 @@ public class FormLoginTests {
|
||||||
@GetMapping("/login")
|
@GetMapping("/login")
|
||||||
public Mono<String> login(ServerWebExchange exchange) {
|
public Mono<String> login(ServerWebExchange exchange) {
|
||||||
Mono<CsrfToken> token = exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty());
|
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 charset=\"utf-8\">\n"
|
||||||
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\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"
|
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
|
||||||
|
|
|
@ -87,7 +87,7 @@ public class HeaderSpecTests {
|
||||||
public void headersWhenDisableInLambdaThenNoSecurityHeaders() {
|
public void headersWhenDisableInLambdaThenNoSecurityHeaders() {
|
||||||
new HashSet<>(this.expectedHeaders.keySet()).forEach(this::expectHeaderNamesNotPresent);
|
new HashSet<>(this.expectedHeaders.keySet()).forEach(this::expectHeaderNamesNotPresent);
|
||||||
|
|
||||||
this.http.headers(headers -> headers.disable());
|
this.http.headers((headers) -> headers.disable());
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -124,7 +124,7 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenCacheDisableInLambdaThenCacheNotWritten() {
|
public void headersWhenCacheDisableInLambdaThenCacheNotWritten() {
|
||||||
expectHeaderNamesNotPresent(HttpHeaders.CACHE_CONTROL, HttpHeaders.PRAGMA, HttpHeaders.EXPIRES);
|
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();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -140,7 +140,8 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenContentOptionsDisableInLambdaThenContentTypeOptionsNotWritten() {
|
public void headersWhenContentOptionsDisableInLambdaThenContentTypeOptionsNotWritten() {
|
||||||
expectHeaderNamesNotPresent(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS);
|
expectHeaderNamesNotPresent(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS);
|
||||||
this.http.headers(headers -> headers.contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable()));
|
this.http
|
||||||
|
.headers((headers) -> headers.contentTypeOptions((contentTypeOptions) -> contentTypeOptions.disable()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -156,7 +157,7 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenHstsDisableInLambdaThenHstsNotWritten() {
|
public void headersWhenHstsDisableInLambdaThenHstsNotWritten() {
|
||||||
expectHeaderNamesNotPresent(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
expectHeaderNamesNotPresent(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
||||||
this.http.headers(headers -> headers.hsts(hsts -> hsts.disable()));
|
this.http.headers((headers) -> headers.hsts((hsts) -> hsts.disable()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -176,8 +177,8 @@ public class HeaderSpecTests {
|
||||||
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
||||||
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
||||||
"max-age=60");
|
"max-age=60");
|
||||||
this.http
|
this.http.headers(
|
||||||
.headers(headers -> headers.hsts(hsts -> hsts.maxAge(Duration.ofSeconds(60)).includeSubdomains(false)));
|
(headers) -> headers.hsts((hsts) -> hsts.maxAge(Duration.ofSeconds(60)).includeSubdomains(false)));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -197,7 +198,7 @@ public class HeaderSpecTests {
|
||||||
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
this.expectedHeaders.remove(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY);
|
||||||
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
this.expectedHeaders.add(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
|
||||||
"max-age=60 ; includeSubDomains ; preload");
|
"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();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -213,7 +214,7 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenFrameOptionsDisableInLambdaThenFrameOptionsNotWritten() {
|
public void headersWhenFrameOptionsDisableInLambdaThenFrameOptionsNotWritten() {
|
||||||
expectHeaderNamesNotPresent(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS);
|
expectHeaderNamesNotPresent(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS);
|
||||||
this.http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.disable()));
|
this.http.headers((headers) -> headers.frameOptions((frameOptions) -> frameOptions.disable()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -229,8 +230,8 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenFrameOptionsModeInLambdaThenFrameOptionsCustomMode() {
|
public void headersWhenFrameOptionsModeInLambdaThenFrameOptionsCustomMode() {
|
||||||
this.expectedHeaders.set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN");
|
this.expectedHeaders.set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, "SAMEORIGIN");
|
||||||
this.http.headers(headers -> headers
|
this.http.headers((headers) -> headers.frameOptions(
|
||||||
.frameOptions(frameOptions -> frameOptions.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)));
|
(frameOptions) -> frameOptions.mode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN)));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -246,7 +247,7 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenXssProtectionDisableInLambdaThenXssProtectionNotWritten() {
|
public void headersWhenXssProtectionDisableInLambdaThenXssProtectionNotWritten() {
|
||||||
expectHeaderNamesNotPresent("X-Xss-Protection");
|
expectHeaderNamesNotPresent("X-Xss-Protection");
|
||||||
this.http.headers(headers -> headers.xssProtection(xssProtection -> xssProtection.disable()));
|
this.http.headers((headers) -> headers.xssProtection((xssProtection) -> xssProtection.disable()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -278,7 +279,7 @@ public class HeaderSpecTests {
|
||||||
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
|
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
|
||||||
expectedPolicyDirectives);
|
expectedPolicyDirectives);
|
||||||
|
|
||||||
this.http.headers(headers -> headers.contentSecurityPolicy(withDefaults()));
|
this.http.headers((headers) -> headers.contentSecurityPolicy(withDefaults()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -289,8 +290,8 @@ public class HeaderSpecTests {
|
||||||
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
|
this.expectedHeaders.add(ContentSecurityPolicyServerHttpHeadersWriter.CONTENT_SECURITY_POLICY,
|
||||||
policyDirectives);
|
policyDirectives);
|
||||||
|
|
||||||
this.http.headers(headers -> headers.contentSecurityPolicy(
|
this.http.headers((headers) -> headers.contentSecurityPolicy(
|
||||||
contentSecurityPolicy -> contentSecurityPolicy.policyDirectives(policyDirectives)));
|
(contentSecurityPolicy) -> contentSecurityPolicy.policyDirectives(policyDirectives)));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -308,7 +309,7 @@ public class HeaderSpecTests {
|
||||||
public void headersWhenReferrerPolicyEnabledInLambdaThenReferrerPolicyWritten() {
|
public void headersWhenReferrerPolicyEnabledInLambdaThenReferrerPolicyWritten() {
|
||||||
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
|
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
|
||||||
ReferrerPolicy.NO_REFERRER.getPolicy());
|
ReferrerPolicy.NO_REFERRER.getPolicy());
|
||||||
this.http.headers(headers -> headers.referrerPolicy(withDefaults()));
|
this.http.headers((headers) -> headers.referrerPolicy(withDefaults()));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -326,8 +327,8 @@ public class HeaderSpecTests {
|
||||||
public void headersWhenReferrerPolicyCustomEnabledInLambdaThenCustomReferrerPolicyWritten() {
|
public void headersWhenReferrerPolicyCustomEnabledInLambdaThenCustomReferrerPolicyWritten() {
|
||||||
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
|
this.expectedHeaders.add(ReferrerPolicyServerHttpHeadersWriter.REFERRER_POLICY,
|
||||||
ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE.getPolicy());
|
ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE.getPolicy());
|
||||||
this.http.headers(headers -> headers
|
this.http.headers((headers) -> headers
|
||||||
.referrerPolicy(referrerPolicy -> referrerPolicy.policy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE)));
|
.referrerPolicy((referrerPolicy) -> referrerPolicy.policy(ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE)));
|
||||||
|
|
||||||
assertHeaders();
|
assertHeaders();
|
||||||
}
|
}
|
||||||
|
@ -335,8 +336,8 @@ public class HeaderSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void headersWhenCustomHeadersWriter() {
|
public void headersWhenCustomHeadersWriter() {
|
||||||
this.expectedHeaders.add(CUSTOM_HEADER, CUSTOM_VALUE);
|
this.expectedHeaders.add(CUSTOM_HEADER, CUSTOM_VALUE);
|
||||||
this.http.headers(headers -> headers.writer(exchange -> {
|
this.http.headers((headers) -> headers.writer((exchange) -> {
|
||||||
return Mono.just(exchange).doOnNext(it -> {
|
return Mono.just(exchange).doOnNext((it) -> {
|
||||||
it.getResponse().getHeaders().add(CUSTOM_HEADER, CUSTOM_VALUE);
|
it.getResponse().getHeaders().add(CUSTOM_HEADER, CUSTOM_VALUE);
|
||||||
}).then();
|
}).then();
|
||||||
|
|
||||||
|
|
|
@ -174,7 +174,7 @@ public class HttpsRedirectSpecTests {
|
||||||
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.redirectToHttps(redirectToHttps ->
|
.redirectToHttps((redirectToHttps) ->
|
||||||
redirectToHttps
|
redirectToHttps
|
||||||
.httpsRedirectWhen(new PathPatternParserServerWebExchangeMatcher("/secure"))
|
.httpsRedirectWhen(new PathPatternParserServerWebExchangeMatcher("/secure"))
|
||||||
);
|
);
|
||||||
|
@ -215,7 +215,7 @@ public class HttpsRedirectSpecTests {
|
||||||
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.redirectToHttps(redirectToHttps ->
|
.redirectToHttps((redirectToHttps) ->
|
||||||
redirectToHttps
|
redirectToHttps
|
||||||
.portMapper(portMapper())
|
.portMapper(portMapper())
|
||||||
);
|
);
|
||||||
|
|
|
@ -91,9 +91,9 @@ public class LogoutSpecTests {
|
||||||
@Test
|
@Test
|
||||||
public void logoutWhenCustomLogoutInLambdaThenCustomLogoutUsed() {
|
public void logoutWhenCustomLogoutInLambdaThenCustomLogoutUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(authorizeExchange -> authorizeExchange.anyExchange().authenticated())
|
.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().authenticated())
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.logout(logout -> logout.requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")))
|
.logout((logout) -> logout.requiresLogout(ServerWebExchangeMatchers.pathMatchers("/custom-logout")))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
|
||||||
|
|
|
@ -144,7 +144,7 @@ public class OAuth2ClientSpecTests {
|
||||||
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
|
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
|
||||||
|
|
||||||
this.client.get()
|
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")
|
.queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state")
|
||||||
.build())
|
.build())
|
||||||
.exchange().expectStatus().is3xxRedirection();
|
.exchange().expectStatus().is3xxRedirection();
|
||||||
|
@ -185,7 +185,7 @@ public class OAuth2ClientSpecTests {
|
||||||
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
|
given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
|
||||||
|
|
||||||
this.client.get()
|
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")
|
.queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state")
|
||||||
.build())
|
.build())
|
||||||
.exchange().expectStatus().is3xxRedirection();
|
.exchange().expectStatus().is3xxRedirection();
|
||||||
|
@ -264,7 +264,7 @@ public class OAuth2ClientSpecTests {
|
||||||
.authenticationManager(this.manager)
|
.authenticationManager(this.manager)
|
||||||
.authorizationRequestRepository(this.authorizationRequestRepository)
|
.authorizationRequestRepository(this.authorizationRequestRepository)
|
||||||
.and()
|
.and()
|
||||||
.requestCache(c -> c.requestCache(this.requestCache));
|
.requestCache((c) -> c.requestCache(this.requestCache));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
@ -287,12 +287,12 @@ public class OAuth2ClientSpecTests {
|
||||||
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
|
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2Client(oauth2Client ->
|
.oauth2Client((oauth2Client) ->
|
||||||
oauth2Client
|
oauth2Client
|
||||||
.authenticationConverter(this.authenticationConverter)
|
.authenticationConverter(this.authenticationConverter)
|
||||||
.authenticationManager(this.manager)
|
.authenticationManager(this.manager)
|
||||||
.authorizationRequestRepository(this.authorizationRequestRepository))
|
.authorizationRequestRepository(this.authorizationRequestRepository))
|
||||||
.requestCache(c -> c.requestCache(this.requestCache));
|
.requestCache((c) -> c.requestCache(this.requestCache));
|
||||||
// @formatter:on
|
// @formatter:on
|
||||||
return http.build();
|
return http.build();
|
||||||
}
|
}
|
||||||
|
|
|
@ -226,7 +226,7 @@ public class OAuth2LoginTests {
|
||||||
given(manager.authenticate(any())).willReturn(Mono.just(result));
|
given(manager.authenticate(any())).willReturn(Mono.just(result));
|
||||||
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
||||||
given(resolver.resolve(any())).willReturn(Mono.empty());
|
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);
|
WebFilterExchange webFilterExchange = invocation.getArgument(0);
|
||||||
Authentication authentication = invocation.getArgument(1);
|
Authentication authentication = invocation.getArgument(1);
|
||||||
|
|
||||||
|
@ -268,14 +268,14 @@ public class OAuth2LoginTests {
|
||||||
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
|
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
|
||||||
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
||||||
given(resolver.resolve(any())).willReturn(Mono.empty());
|
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);
|
WebFilterExchange webFilterExchange = invocation.getArgument(0);
|
||||||
Authentication authentication = invocation.getArgument(1);
|
Authentication authentication = invocation.getArgument(1);
|
||||||
|
|
||||||
return new RedirectServerAuthenticationSuccessHandler(redirectLocation)
|
return new RedirectServerAuthenticationSuccessHandler(redirectLocation)
|
||||||
.onAuthenticationSuccess(webFilterExchange, authentication);
|
.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);
|
WebFilterExchange webFilterExchange = invocation.getArgument(0);
|
||||||
AuthenticationException authenticationException = invocation.getArgument(1);
|
AuthenticationException authenticationException = invocation.getArgument(1);
|
||||||
|
|
||||||
|
@ -321,7 +321,7 @@ public class OAuth2LoginTests {
|
||||||
given(manager.authenticate(any())).willReturn(Mono.just(result));
|
given(manager.authenticate(any())).willReturn(Mono.just(result));
|
||||||
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
|
||||||
given(resolver.resolve(any())).willReturn(Mono.empty());
|
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);
|
WebFilterExchange webFilterExchange = invocation.getArgument(0);
|
||||||
Authentication authentication = invocation.getArgument(1);
|
Authentication authentication = invocation.getArgument(1);
|
||||||
|
|
||||||
|
@ -442,7 +442,7 @@ public class OAuth2LoginTests {
|
||||||
|
|
||||||
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
|
ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = config.jwtDecoderFactory;
|
||||||
OAuth2Error oauth2Error = new OAuth2Error("invalid_id_token", "Invalid ID Token", null);
|
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))));
|
.error(new JwtValidationException("ID Token validation failed", Collections.singleton(oauth2Error))));
|
||||||
|
|
||||||
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader()
|
webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection().expectHeader()
|
||||||
|
@ -602,11 +602,11 @@ public class OAuth2LoginTests {
|
||||||
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
|
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeExchange(exchanges ->
|
.authorizeExchange((exchanges) ->
|
||||||
exchanges
|
exchanges
|
||||||
.anyExchange().authenticated()
|
.anyExchange().authenticated()
|
||||||
)
|
)
|
||||||
.oauth2Login(oauth2Login ->
|
.oauth2Login((oauth2Login) ->
|
||||||
oauth2Login
|
oauth2Login
|
||||||
.authenticationConverter(this.authenticationConverter)
|
.authenticationConverter(this.authenticationConverter)
|
||||||
.authenticationManager(this.manager)
|
.authenticationManager(this.manager)
|
||||||
|
@ -674,13 +674,13 @@ public class OAuth2LoginTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private ReactiveJwtDecoder getJwtDecoder() {
|
private ReactiveJwtDecoder getJwtDecoder() {
|
||||||
return token -> {
|
return (token) -> {
|
||||||
Map<String, Object> claims = new HashMap<>();
|
Map<String, Object> claims = new HashMap<>();
|
||||||
claims.put(IdTokenClaimNames.SUB, "subject");
|
claims.put(IdTokenClaimNames.SUB, "subject");
|
||||||
claims.put(IdTokenClaimNames.ISS, "http://localhost/issuer");
|
claims.put(IdTokenClaimNames.ISS, "http://localhost/issuer");
|
||||||
claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client"));
|
claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client"));
|
||||||
claims.put(IdTokenClaimNames.AZP, "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);
|
return Mono.just(jwt);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -135,7 +135,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenValidThenReturnsOk() {
|
public void getWhenValidThenReturnsOk() {
|
||||||
this.spring.register(PublicKeyConfig.class, RootController.class).autowire();
|
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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -143,7 +143,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenExpiredThenReturnsInvalidToken() {
|
public void getWhenExpiredThenReturnsInvalidToken() {
|
||||||
this.spring.register(PublicKeyConfig.class).autowire();
|
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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
||||||
}
|
}
|
||||||
|
@ -152,7 +152,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenUnsignedThenReturnsInvalidToken() {
|
public void getWhenUnsignedThenReturnsInvalidToken() {
|
||||||
this.spring.register(PublicKeyConfig.class).autowire();
|
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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
||||||
}
|
}
|
||||||
|
@ -161,7 +161,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenEmptyBearerTokenThenReturnsInvalidToken() {
|
public void getWhenEmptyBearerTokenThenReturnsInvalidToken() {
|
||||||
this.spring.register(PublicKeyConfig.class).autowire();
|
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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
||||||
}
|
}
|
||||||
|
@ -170,7 +170,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenValidTokenAndPublicKeyInLambdaThenReturnsOk() {
|
public void getWhenValidTokenAndPublicKeyInLambdaThenReturnsOk() {
|
||||||
this.spring.register(PublicKeyInLambdaConfig.class, RootController.class).autowire();
|
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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -178,7 +178,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenExpiredTokenAndPublicKeyInLambdaThenReturnsInvalidToken() {
|
public void getWhenExpiredTokenAndPublicKeyInLambdaThenReturnsInvalidToken() {
|
||||||
this.spring.register(PublicKeyInLambdaConfig.class).autowire();
|
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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"invalid_token\""));
|
||||||
}
|
}
|
||||||
|
@ -187,7 +187,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenValidUsingPlaceholderThenReturnsOk() {
|
public void getWhenValidUsingPlaceholderThenReturnsOk() {
|
||||||
this.spring.register(PlaceholderConfig.class, RootController.class).autowire();
|
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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -198,7 +198,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
ReactiveJwtDecoder jwtDecoder = this.spring.getContext().getBean(ReactiveJwtDecoder.class);
|
ReactiveJwtDecoder jwtDecoder = this.spring.getContext().getBean(ReactiveJwtDecoder.class);
|
||||||
given(jwtDecoder.decode(anyString())).willReturn(Mono.just(this.jwt));
|
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());
|
verify(jwtDecoder).decode(anyString());
|
||||||
}
|
}
|
||||||
|
@ -210,7 +210,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
|
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
|
||||||
mockWebServer.enqueue(new MockResponse().setBody(this.jwkSet));
|
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();
|
.expectStatus().isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -221,7 +221,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
|
MockWebServer mockWebServer = this.spring.getContext().getBean(MockWebServer.class);
|
||||||
mockWebServer.enqueue(new MockResponse().setBody(this.jwkSet));
|
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();
|
.expectStatus().isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -234,7 +234,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
given(authenticationManager.authenticate(any(Authentication.class)))
|
given(authenticationManager.authenticate(any(Authentication.class)))
|
||||||
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
|
.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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
||||||
}
|
}
|
||||||
|
@ -248,7 +248,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
given(authenticationManager.authenticate(any(Authentication.class)))
|
given(authenticationManager.authenticate(any(Authentication.class)))
|
||||||
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
|
.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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
||||||
}
|
}
|
||||||
|
@ -268,7 +268,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
given(authenticationManager.authenticate(any(Authentication.class)))
|
given(authenticationManager.authenticate(any(Authentication.class)))
|
||||||
.willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
|
.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()
|
.isUnauthorized().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
|
||||||
}
|
}
|
||||||
|
@ -277,7 +277,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void postWhenSignedThenReturnsOk() {
|
public void postWhenSignedThenReturnsOk() {
|
||||||
this.spring.register(PublicKeyConfig.class, RootController.class).autowire();
|
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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -285,7 +285,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenTokenHasInsufficientScopeThenReturnsInsufficientScope() {
|
public void getWhenTokenHasInsufficientScopeThenReturnsInsufficientScope() {
|
||||||
this.spring.register(DenyAllConfig.class, RootController.class).autowire();
|
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()
|
.isForbidden().expectHeader()
|
||||||
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"insufficient_scope\""));
|
.value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"insufficient_scope\""));
|
||||||
}
|
}
|
||||||
|
@ -308,7 +308,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenSignedAndCustomConverterThenConverts() {
|
public void getWhenSignedAndCustomConverterThenConverts() {
|
||||||
this.spring.register(CustomJwtAuthenticationConverterConfig.class, RootController.class).autowire();
|
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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -323,7 +323,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
public void getWhenCustomBearerTokenDeniedHandlerThenResponds() {
|
public void getWhenCustomBearerTokenDeniedHandlerThenResponds() {
|
||||||
this.spring.register(CustomErrorHandlingConfig.class).autowire();
|
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);
|
.exchange().expectStatus().isEqualTo(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -392,7 +392,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
this.spring.getContext().getBean(MockWebServer.class)
|
this.spring.getContext().getBean(MockWebServer.class)
|
||||||
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
|
.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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -402,7 +402,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
this.spring.getContext().getBean(MockWebServer.class)
|
this.spring.getContext().getBean(MockWebServer.class)
|
||||||
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
|
.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();
|
.isOk();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -417,8 +417,8 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
@Override
|
@Override
|
||||||
public MockResponse dispatch(RecordedRequest request) {
|
public MockResponse dispatch(RecordedRequest request) {
|
||||||
String authorization = request.getHeader(org.springframework.http.HttpHeaders.AUTHORIZATION);
|
String authorization = request.getHeader(org.springframework.http.HttpHeaders.AUTHORIZATION);
|
||||||
return Optional.ofNullable(authorization).filter(a -> isAuthorized(authorization, username, password))
|
return Optional.ofNullable(authorization).filter((a) -> isAuthorized(authorization, username, password))
|
||||||
.map(a -> ok(response)).orElse(unauthorized());
|
.map((a) -> ok(response)).orElse(unauthorized());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -488,13 +488,13 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.authorizeExchange(exchanges ->
|
.authorizeExchange((exchanges) ->
|
||||||
exchanges
|
exchanges
|
||||||
.anyExchange().hasAuthority("SCOPE_message:read")
|
.anyExchange().hasAuthority("SCOPE_message:read")
|
||||||
)
|
)
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(jwt ->
|
.jwt((jwt) ->
|
||||||
jwt
|
jwt
|
||||||
.publicKey(publicKey())
|
.publicKey(publicKey())
|
||||||
)
|
)
|
||||||
|
@ -572,9 +572,9 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(jwt ->
|
.jwt((jwt) ->
|
||||||
jwt
|
jwt
|
||||||
.jwkSetUri(jwkSetUri)
|
.jwkSetUri(jwkSetUri)
|
||||||
)
|
)
|
||||||
|
@ -672,9 +672,9 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
SecurityWebFilterChain springSecurity(ServerHttpSecurity http) {
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.jwt(jwt ->
|
.jwt((jwt) ->
|
||||||
jwt
|
jwt
|
||||||
.authenticationManager(authenticationManager())
|
.authenticationManager(authenticationManager())
|
||||||
)
|
)
|
||||||
|
@ -743,7 +743,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
ServerAuthenticationConverter bearerTokenAuthenticationConverter() {
|
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);
|
.map(BearerTokenAuthenticationToken::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -773,7 +773,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
Converter<Jwt, Mono<AbstractAuthenticationToken>> jwtAuthenticationConverter() {
|
Converter<Jwt, Mono<AbstractAuthenticationToken>> jwtAuthenticationConverter() {
|
||||||
|
|
||||||
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
|
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
|
||||||
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
|
converter.setJwtGrantedAuthoritiesConverter((jwt) -> {
|
||||||
String[] claims = ((String) jwt.getClaims().get("scope")).split(" ");
|
String[] claims = ((String) jwt.getClaims().get("scope")).split(" ");
|
||||||
return Stream.of(claims).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
return Stream.of(claims).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
|
||||||
});
|
});
|
||||||
|
@ -852,9 +852,9 @@ public class OAuth2ResourceServerSpecTests {
|
||||||
|
|
||||||
// @formatter:off
|
// @formatter:off
|
||||||
http
|
http
|
||||||
.oauth2ResourceServer(oauth2ResourceServer ->
|
.oauth2ResourceServer((oauth2ResourceServer) ->
|
||||||
oauth2ResourceServer
|
oauth2ResourceServer
|
||||||
.opaqueToken(opaqueToken ->
|
.opaqueToken((opaqueToken) ->
|
||||||
opaqueToken
|
opaqueToken
|
||||||
.introspectionUri(introspectionUri)
|
.introspectionUri(introspectionUri)
|
||||||
.introspectionClientCredentials("client", "secret")
|
.introspectionClientCredentials("client", "secret")
|
||||||
|
|
|
@ -84,9 +84,10 @@ public class RequestCacheTests {
|
||||||
@Test
|
@Test
|
||||||
public void requestWhenCustomRequestCacheInLambdaThenCustomCacheUsed() {
|
public void requestWhenCustomRequestCacheInLambdaThenCustomCacheUsed() {
|
||||||
SecurityWebFilterChain securityWebFilter = this.http
|
SecurityWebFilterChain securityWebFilter = this.http
|
||||||
.authorizeExchange(authorizeExchange -> authorizeExchange.anyExchange().authenticated())
|
.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().authenticated())
|
||||||
.formLogin(withDefaults())
|
.formLogin(withDefaults())
|
||||||
.requestCache(requestCache -> requestCache.requestCache(NoOpServerRequestCache.getInstance())).build();
|
.requestCache((requestCache) -> requestCache.requestCache(NoOpServerRequestCache.getInstance()))
|
||||||
|
.build();
|
||||||
|
|
||||||
WebTestClient webTestClient = WebTestClient
|
WebTestClient webTestClient = WebTestClient
|
||||||
.bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController())
|
.bindToController(new SecuredPageController(), new WebTestClientBuilder.Http200RestController())
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue