Remove restricted static imports
Replace static imports with class referenced methods. With the exception of a few well known static imports, checkstyle restricts the static imports that a class can use. For example, `asList(...)` would be replaced with `Arrays.asList(...)`. Issue gh-8945
This commit is contained in:
@@ -20,6 +20,7 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
@@ -34,11 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.powermock.api.mockito.PowerMockito.doThrow;
|
||||
import static org.powermock.api.mockito.PowerMockito.mock;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
|
||||
import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
@@ -88,9 +86,9 @@ public class SecurityNamespaceHandlerTests {
|
||||
@Test
|
||||
public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception {
|
||||
String className = "javax.servlet.Filter";
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME),
|
||||
any(ClassLoader.class));
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
|
||||
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
|
||||
Log logger = mock(Log.class);
|
||||
SecurityNamespaceHandler handler = new SecurityNamespaceHandler();
|
||||
@@ -98,7 +96,7 @@ public class SecurityNamespaceHandlerTests {
|
||||
|
||||
handler.init();
|
||||
|
||||
verifyStatic(ClassUtils.class);
|
||||
PowerMockito.verifyStatic(ClassUtils.class);
|
||||
ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
verifyZeroInteractions(logger);
|
||||
}
|
||||
@@ -108,18 +106,18 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = "javax.servlet.Filter";
|
||||
this.thrown.expect(BeanDefinitionParsingException.class);
|
||||
this.thrown.expectMessage("NoClassDefFoundError: " + className);
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME),
|
||||
any(ClassLoader.class));
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
|
||||
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception {
|
||||
String className = "javax.servlet.Filter";
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME),
|
||||
any(ClassLoader.class));
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
|
||||
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
|
||||
// should load just fine since no http block
|
||||
}
|
||||
@@ -129,8 +127,8 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = FILTER_CHAIN_PROXY_CLASSNAME;
|
||||
this.thrown.expect(BeanDefinitionParsingException.class);
|
||||
this.thrown.expectMessage("ClassNotFoundException: " + className);
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
|
||||
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK);
|
||||
}
|
||||
@@ -138,8 +136,8 @@ public class SecurityNamespaceHandlerTests {
|
||||
@Test
|
||||
public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception {
|
||||
String className = FILTER_CHAIN_PROXY_CLASSNAME;
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
|
||||
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
|
||||
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
|
||||
// should load just fine since no http block
|
||||
@@ -148,9 +146,9 @@ public class SecurityNamespaceHandlerTests {
|
||||
@Test
|
||||
public void websocketNotFoundExceptionNoMessageBlock() throws Exception {
|
||||
String className = FILTER_CHAIN_PROXY_CLASSNAME;
|
||||
spy(ClassUtils.class);
|
||||
doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(Message.class.getName()),
|
||||
any(ClassLoader.class));
|
||||
PowerMockito.spy(ClassUtils.class);
|
||||
PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
|
||||
eq(Message.class.getName()), any(ClassLoader.class));
|
||||
new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
|
||||
// should load just fine since no websocket block
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.core.userdetails.PasswordEncodedUser;
|
||||
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders;
|
||||
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -70,8 +72,8 @@ public class NamespaceAuthenticationManagerTests {
|
||||
public void authenticationManagerWhenGlobalAndEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
|
||||
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
|
||||
|
||||
this.mockMvc.perform(formLogin())
|
||||
.andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
|
||||
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
|
||||
.authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull()));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -34,7 +34,7 @@ import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.isNotNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@@ -22,6 +22,7 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
import org.powermock.core.classloader.annotations.PowerMockIgnore;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
@@ -48,8 +49,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
|
||||
/**
|
||||
@@ -79,9 +78,10 @@ public class WebSecurityConfigurerAdapterPowermockTests {
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
|
||||
spy(SpringFactoriesLoader.class);
|
||||
PowerMockito.spy(SpringFactoriesLoader.class);
|
||||
DefaultConfigurer configurer = new DefaultConfigurer();
|
||||
when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
PowerMockito
|
||||
.when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
|
||||
|
||||
loadConfig(Config.class);
|
||||
|
||||
@@ -55,7 +55,8 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -153,11 +154,9 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
|
||||
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
|
||||
|
||||
Throwable thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("user"));
|
||||
assertThat(thrown).isNull();
|
||||
|
||||
thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
|
||||
assertThat(thrown).isInstanceOf(UsernameNotFoundException.class);
|
||||
assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException();
|
||||
assertThatExceptionOfType(UsernameNotFoundException.class)
|
||||
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
|
||||
}
|
||||
|
||||
// SEC-2274: WebSecurityConfigurer adds ApplicationContext as a shared object
|
||||
|
||||
@@ -38,8 +38,7 @@ import org.springframework.security.core.userdetails.PasswordEncodedUser;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -62,11 +61,11 @@ public class HttpConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void configureWhenAddFilterUnregisteredThenThrowsBeanCreationException() {
|
||||
Throwable thrown = catchThrowable(() -> this.spring.register(UnregisteredFilterConfig.class).autowire());
|
||||
assertThat(thrown).isInstanceOf(BeanCreationException.class);
|
||||
assertThat(thrown.getMessage()).contains("The Filter class " + UnregisteredFilter.class.getName()
|
||||
+ " does not have a registered order and cannot be added without a specified order."
|
||||
+ " Consider using addFilterBefore or addFilterAfter instead.");
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(UnregisteredFilterConfig.class).autowire())
|
||||
.withMessageContaining("The Filter class " + UnregisteredFilter.class.getName()
|
||||
+ " does not have a registered order and cannot be added without a specified order."
|
||||
+ " Consider using addFilterBefore or addFilterAfter instead.");
|
||||
}
|
||||
|
||||
// https://github.com/spring-projects/spring-security-javaconfig/issues/104
|
||||
|
||||
@@ -34,10 +34,12 @@ import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResp
|
||||
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -52,9 +54,6 @@ import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientCredentials;
|
||||
import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
@@ -79,7 +78,8 @@ public class OAuth2ClientConfigurationTests {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
|
||||
|
||||
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
|
||||
ClientRegistration clientRegistration = clientRegistration().registrationId(clientRegistrationId).build();
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
|
||||
.willReturn(clientRegistration);
|
||||
|
||||
@@ -99,8 +99,10 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
|
||||
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
|
||||
|
||||
this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk())
|
||||
.andExpect(content().string("resolved"));
|
||||
this.mockMvc
|
||||
.perform(get("/authorized-client")
|
||||
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("resolved"));
|
||||
verifyZeroInteractions(accessTokenResponseClient);
|
||||
}
|
||||
|
||||
@@ -115,7 +117,8 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
|
||||
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
||||
|
||||
ClientRegistration clientRegistration = clientCredentials().registrationId(clientRegistrationId).build();
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
|
||||
@@ -128,8 +131,10 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
|
||||
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
|
||||
|
||||
this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk())
|
||||
.andExpect(content().string("resolved"));
|
||||
this.mockMvc
|
||||
.perform(get("/authorized-client")
|
||||
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("resolved"));
|
||||
verify(accessTokenResponseClient, times(1)).getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class));
|
||||
}
|
||||
|
||||
@@ -176,7 +181,8 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
|
||||
OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
|
||||
|
||||
ClientRegistration clientRegistration = clientRegistration().registrationId(clientRegistrationId).build();
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
|
||||
TestOAuth2AccessTokens.noScopes());
|
||||
|
||||
@@ -187,8 +193,10 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager;
|
||||
this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
|
||||
|
||||
this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk())
|
||||
.andExpect(content().string("resolved"));
|
||||
this.mockMvc
|
||||
.perform(get("/authorized-client")
|
||||
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("resolved"));
|
||||
|
||||
verify(authorizedClientManager).authorize(any());
|
||||
verifyNoInteractions(clientRegistrationRepository);
|
||||
|
||||
@@ -31,14 +31,14 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.TestBearerTokenAuthentications;
|
||||
import org.springframework.security.oauth2.server.resource.web.reactive.function.client.ServletBearerExchangeFilterFunction;
|
||||
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
import static org.springframework.security.oauth2.server.resource.authentication.TestBearerTokenAuthentications.bearer;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
@@ -60,21 +60,21 @@ public class SecurityReactorContextConfigurationResourceServerTests {
|
||||
// gh-7418
|
||||
@Test
|
||||
public void requestWhenUsingFilterThenBearerTokenPropagated() throws Exception {
|
||||
BearerTokenAuthentication authentication = bearer();
|
||||
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
|
||||
this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class).autowire();
|
||||
|
||||
this.mockMvc.perform(get("/token").with(authentication(authentication))).andExpect(status().isOk())
|
||||
.andExpect(content().string("Bearer token"));
|
||||
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("Bearer token"));
|
||||
}
|
||||
|
||||
// gh-7418
|
||||
@Test
|
||||
public void requestWhenNotUsingFilterThenBearerTokenNotPropagated() throws Exception {
|
||||
BearerTokenAuthentication authentication = bearer();
|
||||
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
|
||||
this.spring.register(BearerFilterlessConfig.class, WebServerConfig.class, Controller.class).autowire();
|
||||
|
||||
this.mockMvc.perform(get("/token").with(authentication(authentication))).andExpect(status().isOk())
|
||||
.andExpect(content().string(""));
|
||||
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
|
||||
.andExpect(status().isOk()).andExpect(content().string(""));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -33,11 +33,13 @@ import reactor.core.publisher.Operators;
|
||||
import reactor.test.StepVerifier;
|
||||
import reactor.util.context.Context;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
@@ -51,8 +53,6 @@ import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
import static org.springframework.http.HttpMethod.GET;
|
||||
import static org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES;
|
||||
|
||||
/**
|
||||
* Tests for {@link SecurityReactorContextConfiguration}.
|
||||
@@ -88,7 +88,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void createSubscriberIfNecessaryWhenSubscriberContextContainsSecurityContextAttributesThenReturnOriginalSubscriber() {
|
||||
Context context = Context.of(SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>());
|
||||
Context context = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>());
|
||||
BaseSubscriber<Object> originalSubscriber = new BaseSubscriber<Object>() {
|
||||
@Override
|
||||
public Context currentContext() {
|
||||
@@ -120,7 +120,8 @@ public class SecurityReactorContextConfigurationTests {
|
||||
Context resultContext = subscriber.currentContext();
|
||||
|
||||
assertThat(resultContext.getOrEmpty(testKey)).hasValue(testValue);
|
||||
Map<Object, Object> securityContextAttributes = resultContext.getOrDefault(SECURITY_CONTEXT_ATTRIBUTES, null);
|
||||
Map<Object, Object> securityContextAttributes = resultContext
|
||||
.getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null);
|
||||
assertThat(securityContextAttributes).hasSize(3);
|
||||
assertThat(securityContextAttributes).contains(entry(HttpServletRequest.class, this.servletRequest),
|
||||
entry(HttpServletResponse.class, this.servletResponse),
|
||||
@@ -133,7 +134,8 @@ public class SecurityReactorContextConfigurationTests {
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
SecurityContextHolder.getContext().setAuthentication(this.authentication);
|
||||
|
||||
Context parentContext = Context.of(SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>());
|
||||
Context parentContext = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES,
|
||||
new HashMap<>());
|
||||
BaseSubscriber<Object> parent = new BaseSubscriber<Object>() {
|
||||
@Override
|
||||
public Context currentContext() {
|
||||
@@ -206,8 +208,9 @@ public class SecurityReactorContextConfigurationTests {
|
||||
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
|
||||
|
||||
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
|
||||
.filter(ctx -> ctx.hasKey(SECURITY_CONTEXT_ATTRIBUTES)).map(ctx -> ctx.get(SECURITY_CONTEXT_ATTRIBUTES))
|
||||
.cast(Map.class).map(attributes -> {
|
||||
.filter(ctx -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
|
||||
.map(ctx -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
|
||||
.map(attributes -> {
|
||||
if (attributes.containsKey(HttpServletRequest.class)
|
||||
&& attributes.containsKey(HttpServletResponse.class)
|
||||
&& attributes.containsKey(Authentication.class)) {
|
||||
@@ -218,7 +221,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
}
|
||||
});
|
||||
|
||||
ClientRequest clientRequest = ClientRequest.create(GET, URI.create("https://example.com")).build();
|
||||
ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
|
||||
MockExchangeFunction exchange = new MockExchangeFunction();
|
||||
|
||||
Map<Object, Object> expectedContextAttributes = new HashMap<>();
|
||||
@@ -230,8 +233,8 @@ public class SecurityReactorContextConfigurationTests {
|
||||
.flatMap(response -> filter.filter(clientRequest, exchange));
|
||||
|
||||
StepVerifier.create(clientResponseMono).expectAccessibleContext()
|
||||
.contains(SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes).then().expectNext(clientResponseOk)
|
||||
.verifyComplete();
|
||||
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)
|
||||
.then().expectNext(clientResponseOk).verifyComplete();
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -20,6 +20,7 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.security.config.annotation.ObjectPostProcessor;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
@@ -28,9 +29,6 @@ import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.web.header.HeaderWriterFilter;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.http.HttpHeaders.CACHE_CONTROL;
|
||||
import static org.springframework.http.HttpHeaders.EXPIRES;
|
||||
import static org.springframework.http.HttpHeaders.PRAGMA;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
|
||||
@@ -54,8 +52,9 @@ public class HeadersConfigurerEagerHeadersTests {
|
||||
this.mvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff"))
|
||||
.andExpect(header().string("X-Frame-Options", "DENY"))
|
||||
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(EXPIRES, "0")).andExpect(header().string(PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string("X-XSS-Protection", "1; mode=block"));
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -27,16 +27,13 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
|
||||
import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler;
|
||||
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
|
||||
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
@@ -55,7 +52,8 @@ public class LogoutConfigurerClearSiteDataTests {
|
||||
|
||||
private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data";
|
||||
|
||||
private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS };
|
||||
private static final Directive[] SOURCE = { Directive.CACHE, Directive.COOKIES, Directive.STORAGE,
|
||||
Directive.EXECUTION_CONTEXTS };
|
||||
|
||||
private static final String HEADER_VALUE = "\"cache\", \"cookies\", \"storage\", \"executionContexts\"";
|
||||
|
||||
@@ -70,7 +68,7 @@ public class LogoutConfigurerClearSiteDataTests {
|
||||
public void logoutWhenRequestTypeGetThenHeaderNotPresentt() throws Exception {
|
||||
this.spring.register(HttpLogoutConfig.class).autowire();
|
||||
|
||||
this.mvc.perform(get("/logout").secure(true).with(csrf()))
|
||||
this.mvc.perform(get("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf()))
|
||||
.andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER));
|
||||
}
|
||||
|
||||
@@ -79,7 +77,8 @@ public class LogoutConfigurerClearSiteDataTests {
|
||||
public void logoutWhenRequestTypePostAndNotSecureThenHeaderNotPresent() throws Exception {
|
||||
this.spring.register(HttpLogoutConfig.class).autowire();
|
||||
|
||||
this.mvc.perform(post("/logout").with(csrf())).andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER));
|
||||
this.mvc.perform(post("/logout").with(SecurityMockMvcRequestPostProcessors.csrf()))
|
||||
.andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -87,7 +86,7 @@ public class LogoutConfigurerClearSiteDataTests {
|
||||
public void logoutWhenRequestTypePostAndSecureThenHeaderIsPresent() throws Exception {
|
||||
this.spring.register(HttpLogoutConfig.class).autowire();
|
||||
|
||||
this.mvc.perform(post("/logout").secure(true).with(csrf()))
|
||||
this.mvc.perform(post("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf()))
|
||||
.andExpect(header().stringValues(CLEAR_SITE_DATA_HEADER, HEADER_VALUE));
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.openid4java.consumer.ConsumerManager;
|
||||
import org.openid4java.discovery.DiscoveryInformation;
|
||||
import org.openid4java.discovery.yadis.YadisResolver;
|
||||
import org.openid4java.message.AuthRequest;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -63,7 +64,6 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
@@ -107,7 +107,7 @@ public class NamespaceHttpOpenIDLoginTests {
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
|
||||
server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -69,6 +69,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
|
||||
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
|
||||
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
|
||||
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
|
||||
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
|
||||
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
|
||||
@@ -80,6 +81,7 @@ import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoderFactory;
|
||||
import org.springframework.security.oauth2.jwt.TestJwts;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.security.web.context.HttpRequestResponseHolder;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
@@ -92,8 +94,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken;
|
||||
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
@@ -602,7 +602,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
}
|
||||
|
||||
private static OAuth2UserService<OidcUserRequest, OidcUser> createOidcUserService() {
|
||||
OidcIdToken idToken = idToken().build();
|
||||
OidcIdToken idToken = TestOidcIdTokens.idToken().build();
|
||||
return request -> new DefaultOidcUser(Collections.singleton(new OidcUserAuthority(idToken)), idToken);
|
||||
}
|
||||
|
||||
@@ -993,7 +993,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
claims.put(IdTokenClaimNames.ISS, "http://localhost/iss");
|
||||
claims.put(IdTokenClaimNames.AUD, Arrays.asList("clientId", "a", "u", "d"));
|
||||
claims.put(IdTokenClaimNames.AZP, "clientId");
|
||||
Jwt jwt = jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
|
||||
given(jwtDecoder.decode(any())).willReturn(jwt);
|
||||
return jwtDecoder;
|
||||
|
||||
@@ -94,13 +94,16 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
|
||||
import org.springframework.security.oauth2.jose.TestKeys;
|
||||
import org.springframework.security.oauth2.jwt.BadJwtException;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimNames;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtException;
|
||||
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.TestJwts;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
@@ -124,6 +127,7 @@ import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestOperations;
|
||||
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
@@ -131,7 +135,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
import static org.hamcrest.CoreMatchers.startsWith;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -140,12 +144,6 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes;
|
||||
import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS;
|
||||
import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB;
|
||||
import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri;
|
||||
import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withPublicKey;
|
||||
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
@@ -154,8 +152,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.GET;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.POST;
|
||||
|
||||
/**
|
||||
* Tests for {@link OAuth2ResourceServerConfigurer}
|
||||
@@ -169,9 +165,9 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
private static final String JWT_SUBJECT = "mock-test-subject";
|
||||
|
||||
private static final Map<String, Object> JWT_CLAIMS = Collections.singletonMap(SUB, JWT_SUBJECT);
|
||||
private static final Map<String, Object> JWT_CLAIMS = Collections.singletonMap(JwtClaimNames.SUB, JWT_SUBJECT);
|
||||
|
||||
private static final Jwt JWT = jwt().build();
|
||||
private static final Jwt JWT = TestJwts.jwt().build();
|
||||
|
||||
private static final String JWK_SET_URI = "https://mock.org";
|
||||
|
||||
@@ -185,8 +181,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
private static final String CLIENT_SECRET = "client-secret";
|
||||
|
||||
private static final BearerTokenAuthentication INTROSPECTION_AUTHENTICATION_TOKEN = new BearerTokenAuthentication(
|
||||
new DefaultOAuth2AuthenticatedPrincipal(JWT_CLAIMS, Collections.emptyList()), noScopes(),
|
||||
Collections.emptyList());
|
||||
new DefaultOAuth2AuthenticatedPrincipal(JWT_CLAIMS, Collections.emptyList()),
|
||||
TestOAuth2AccessTokens.noScopes(), Collections.emptyList());
|
||||
|
||||
@Autowired(required = false)
|
||||
MockMvc mvc;
|
||||
@@ -1361,8 +1357,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
private String jwtFromIssuer(String issuer) throws Exception {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(ISS, issuer);
|
||||
claims.put(SUB, "test-subject");
|
||||
claims.put(JwtClaimNames.ISS, issuer);
|
||||
claims.put(JwtClaimNames.SUB, "test-subject");
|
||||
claims.put("scope", "message:read");
|
||||
JWSObject jws = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("1").build(),
|
||||
new Payload(new JSONObject(claims)));
|
||||
@@ -2066,7 +2062,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
JwtDecoder decoder() throws Exception {
|
||||
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(this.spec));
|
||||
return withPublicKey(publicKey).build();
|
||||
return NimbusJwtDecoder.withPublicKey(publicKey).build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2285,7 +2281,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
return "post";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/authenticated", method = { GET, POST })
|
||||
@RequestMapping(value = "/authenticated", method = { RequestMethod.GET, RequestMethod.POST })
|
||||
public String authenticated(Authentication authentication) {
|
||||
return authentication.getName();
|
||||
}
|
||||
@@ -2365,7 +2361,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@Bean
|
||||
NimbusJwtDecoder jwtDecoder() {
|
||||
return withJwkSetUri("https://example.org/.well-known/jwks.json").restOperations(this.rest).build();
|
||||
return NimbusJwtDecoder.withJwkSetUri("https://example.org/.well-known/jwks.json").restOperations(this.rest)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -24,6 +24,7 @@ import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.openid4java.consumer.ConsumerManager;
|
||||
import org.openid4java.discovery.DiscoveryInformation;
|
||||
import org.openid4java.discovery.yadis.YadisResolver;
|
||||
import org.openid4java.message.AuthRequest;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -47,7 +48,6 @@ import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
@@ -113,7 +113,7 @@ public class OpenIDLoginConfigurerTests {
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
|
||||
server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
|
||||
@@ -151,7 +151,7 @@ public class OpenIDLoginConfigurerTests {
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
|
||||
server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ package org.springframework.security.config.annotation.web.configurers.saml2;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
@@ -60,14 +61,17 @@ import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.saml2.Saml2Exception;
|
||||
import org.springframework.security.saml2.core.TestSaml2X509Credentials;
|
||||
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationProvider;
|
||||
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationRequestFactory;
|
||||
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;
|
||||
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext;
|
||||
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory;
|
||||
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken;
|
||||
import org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts;
|
||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
|
||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
|
||||
import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations;
|
||||
import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter;
|
||||
import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestContextResolver;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
@@ -81,7 +85,6 @@ import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.web.util.UriComponents;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -89,10 +92,6 @@ import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
import static org.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential;
|
||||
import static org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts.authenticationRequestContext;
|
||||
import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.noCredentials;
|
||||
import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
@@ -171,7 +170,8 @@ public class Saml2LoginConfigurerTests {
|
||||
public void saml2LoginWhenCustomAuthenticationRequestContextResolverThenUses() throws Exception {
|
||||
this.spring.register(CustomAuthenticationRequestContextResolver.class).autowire();
|
||||
|
||||
Saml2AuthenticationRequestContext context = authenticationRequestContext().build();
|
||||
Saml2AuthenticationRequestContext context = TestSaml2AuthenticationRequestContexts
|
||||
.authenticationRequestContext().build();
|
||||
Saml2AuthenticationRequestContextResolver resolver = CustomAuthenticationRequestContextResolver.resolver;
|
||||
given(resolver.resolve(any(HttpServletRequest.class))).willReturn(context);
|
||||
this.mvc.perform(get("/saml2/authenticate/registration-id")).andExpect(status().isFound());
|
||||
@@ -193,9 +193,9 @@ public class Saml2LoginConfigurerTests {
|
||||
@Test
|
||||
public void authenticateWhenCustomAuthenticationConverterThenUses() throws Exception {
|
||||
this.spring.register(CustomAuthenticationConverter.class).autowire();
|
||||
RelyingPartyRegistration relyingPartyRegistration = noCredentials()
|
||||
.assertingPartyDetails(
|
||||
party -> party.verificationX509Credentials(c -> c.add(relyingPartyVerifyingCredential())))
|
||||
RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials()
|
||||
.assertingPartyDetails(party -> party.verificationX509Credentials(
|
||||
c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||
.build();
|
||||
String response = new String(samlDecode(SIGNED_RESPONSE));
|
||||
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
|
||||
@@ -254,7 +254,7 @@ public class Saml2LoginConfigurerTests {
|
||||
InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true));
|
||||
iout.write(b);
|
||||
iout.finish();
|
||||
return new String(out.toByteArray(), UTF_8);
|
||||
return new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new Saml2Exception("Unable to inflate string", e);
|
||||
@@ -387,7 +387,8 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
|
||||
RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class);
|
||||
given(repository.findByRegistrationId(anyString())).willReturn(relyingPartyRegistration().build());
|
||||
given(repository.findByRegistrationId(anyString()))
|
||||
.willReturn(TestRelyingPartyRegistrations.relyingPartyRegistration().build());
|
||||
return repository;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,10 +24,7 @@ import java.security.cert.X509Certificate;
|
||||
|
||||
import org.springframework.security.converter.RsaKeyConverters;
|
||||
import org.springframework.security.saml2.credentials.Saml2X509Credential;
|
||||
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.SIGNING;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION;
|
||||
import org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType;
|
||||
|
||||
/**
|
||||
* Preconfigured SAML credentials for SAML integration tests.
|
||||
@@ -58,7 +55,7 @@ public class TestSaml2Credentials {
|
||||
+ "xbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6z\n"
|
||||
+ "V9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3\n"
|
||||
+ "lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk\n" + "-----END CERTIFICATE-----";
|
||||
return new Saml2X509Credential(x509Certificate(certificate), VERIFICATION);
|
||||
return new Saml2X509Credential(x509Certificate(certificate), Saml2X509CredentialType.VERIFICATION);
|
||||
}
|
||||
|
||||
static X509Certificate x509Certificate(String source) {
|
||||
@@ -105,7 +102,7 @@ public class TestSaml2Credentials {
|
||||
+ "RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" + "-----END CERTIFICATE-----";
|
||||
PrivateKey pk = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(key.getBytes()));
|
||||
X509Certificate cert = x509Certificate(certificate);
|
||||
return new Saml2X509Credential(pk, cert, SIGNING, DECRYPTION);
|
||||
return new Saml2X509Credential(pk, cert, Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
|
||||
import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver;
|
||||
import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor;
|
||||
@@ -71,7 +72,6 @@ import org.springframework.web.reactive.function.BodyInserters;
|
||||
import org.springframework.web.reactive.result.view.AbstractView;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -202,8 +202,9 @@ public class EnableWebFluxSecurityTests {
|
||||
MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
|
||||
data.add("username", "user");
|
||||
data.add("password", "password");
|
||||
client.mutateWith(csrf()).post().uri("/login").body(BodyInserters.fromFormData(data)).exchange().expectStatus()
|
||||
.is3xxRedirection().expectHeader().valueMatches("Location", "/");
|
||||
client.mutateWith(SecurityMockServerConfigurers.csrf()).post().uri("/login")
|
||||
.body(BodyInserters.fromFormData(data)).exchange().expectStatus().is3xxRedirection().expectHeader()
|
||||
.valueMatches("Location", "/");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -46,8 +46,6 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.springframework.messaging.simp.SimpMessageType.MESSAGE;
|
||||
import static org.springframework.messaging.simp.SimpMessageType.SUBSCRIBE;
|
||||
|
||||
public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
|
||||
|
||||
@@ -139,7 +137,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
|
||||
.simpDestMatchers("/app/**").hasRole("USER")
|
||||
// <3>
|
||||
.simpSubscribeDestMatchers("/user/**", "/topic/friends/*").hasRole("USER") // <4>
|
||||
.simpTypeMatchers(MESSAGE, SUBSCRIBE).denyAll() // <5>
|
||||
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll() // <5>
|
||||
.anyMessage().denyAll(); // <6>
|
||||
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
|
||||
import org.springframework.security.util.InMemoryResource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -29,7 +29,7 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.util.InMemoryResource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -18,13 +18,12 @@ package org.springframework.security.config.debug;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.security.config.BeanIds;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
import org.springframework.security.web.debug.DebugFilter;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.security.config.BeanIds.FILTER_CHAIN_PROXY;
|
||||
import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -42,8 +41,9 @@ public class SecurityDebugBeanFactoryPostProcessorTests {
|
||||
"classpath:org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests-context.xml")
|
||||
.autowire();
|
||||
|
||||
assertThat(this.spring.getContext().getBean(SPRING_SECURITY_FILTER_CHAIN)).isInstanceOf(DebugFilter.class);
|
||||
assertThat(this.spring.getContext().getBean(FILTER_CHAIN_PROXY)).isInstanceOf(FilterChainProxy.class);
|
||||
assertThat(this.spring.getContext().getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN))
|
||||
.isInstanceOf(DebugFilter.class);
|
||||
assertThat(this.spring.getContext().getBean(BeanIds.FILTER_CHAIN_PROXY)).isInstanceOf(FilterChainProxy.class);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ import org.springframework.test.web.servlet.ResultMatcher;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.servlet.support.RequestDataValueProcessor;
|
||||
|
||||
@@ -68,14 +69,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.GET;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.HEAD;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.PATCH;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.POST;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.TRACE;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -441,20 +434,22 @@ public class CsrfConfigTests {
|
||||
@Controller
|
||||
public static class RootController {
|
||||
|
||||
@RequestMapping(value = "/csrf-in-header", method = { HEAD, TRACE, OPTIONS })
|
||||
@RequestMapping(value = "/csrf-in-header",
|
||||
method = { RequestMethod.HEAD, RequestMethod.TRACE, RequestMethod.OPTIONS })
|
||||
@ResponseBody
|
||||
String csrfInHeaderAndBody(CsrfToken token, HttpServletResponse response) {
|
||||
response.setHeader(token.getHeaderName(), token.getToken());
|
||||
return csrfInBody(token);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/csrf", method = { POST, PUT, PATCH, DELETE, GET })
|
||||
@RequestMapping(value = "/csrf", method = { RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH,
|
||||
RequestMethod.DELETE, RequestMethod.GET })
|
||||
@ResponseBody
|
||||
String csrfInBody(CsrfToken token) {
|
||||
return token.getToken();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/ok", method = { POST, GET })
|
||||
@RequestMapping(value = "/ok", method = { RequestMethod.POST, RequestMethod.GET })
|
||||
@ResponseBody
|
||||
String ok() {
|
||||
return "ok";
|
||||
|
||||
@@ -24,8 +24,8 @@ import org.springframework.security.web.WebAttributes;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.core.IsNot.not;
|
||||
import static org.hamcrest.core.IsNull.nullValue;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.CoreMatchers.nullValue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
|
||||
@@ -102,6 +102,7 @@ import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
|
||||
import org.springframework.security.web.session.SessionManagementFilter;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -120,7 +121,6 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.x509;
|
||||
import static org.springframework.test.util.ReflectionTestUtils.getField;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
@@ -618,8 +618,8 @@ public class MiscHttpConfigTests {
|
||||
|
||||
this.mvc.perform(get("/details").session(session)).andExpect(content().string(details.getClass().getName()));
|
||||
|
||||
assertThat(getField(getFilter(OpenIDAuthenticationFilter.class), "authenticationDetailsSource"))
|
||||
.isEqualTo(source);
|
||||
assertThat(ReflectionTestUtils.getField(getFilter(OpenIDAuthenticationFilter.class),
|
||||
"authenticationDetailsSource")).isEqualTo(source);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -40,6 +40,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
|
||||
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
@@ -55,7 +56,6 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
@@ -153,7 +153,7 @@ public class OAuth2ClientBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
@@ -183,7 +183,7 @@ public class OAuth2ClientBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
|
||||
@@ -52,6 +52,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
|
||||
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
|
||||
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
|
||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||
@@ -78,8 +79,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse;
|
||||
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.oidcAccessTokenResponse;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
@@ -214,7 +213,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -243,7 +242,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -269,7 +268,8 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = oidcAccessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse()
|
||||
.build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
Jwt jwt = TestJwts.user();
|
||||
@@ -297,7 +297,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -326,7 +326,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
accessTokenResponse = oidcAccessTokenResponse().build();
|
||||
accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
Jwt jwt = TestJwts.user();
|
||||
@@ -359,7 +359,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -428,7 +428,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -456,7 +456,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
@@ -484,7 +484,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
|
||||
given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any()))
|
||||
.willReturn(authorizationRequest);
|
||||
|
||||
OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
|
||||
|
||||
OAuth2User oauth2User = TestOAuth2Users.create();
|
||||
|
||||
@@ -76,9 +76,11 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidator;
|
||||
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
|
||||
import org.springframework.security.oauth2.jose.TestKeys;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtClaimNames;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtException;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.TestJwts;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
|
||||
@@ -96,23 +98,15 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
import static org.hamcrest.CoreMatchers.startsWith;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF;
|
||||
import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.JwtBeanDefinitionParser.DECODER_REF;
|
||||
import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.JwtBeanDefinitionParser.JWK_SET_URI;
|
||||
import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI;
|
||||
import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF;
|
||||
import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS;
|
||||
import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB;
|
||||
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
@@ -435,10 +429,10 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
.autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
when(decoder.decode("token")).thenReturn(jwt().build());
|
||||
given(decoder.decode("token")).willReturn(TestJwts.jwt().build());
|
||||
|
||||
BearerTokenResolver bearerTokenResolver = this.spring.getContext().getBean(BearerTokenResolver.class);
|
||||
when(bearerTokenResolver.resolve(any(HttpServletRequest.class))).thenReturn("token");
|
||||
given(bearerTokenResolver.resolve(any(HttpServletRequest.class))).willReturn("token");
|
||||
|
||||
this.mvc.perform(get("/")).andExpect(status().isNotFound());
|
||||
|
||||
@@ -453,7 +447,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
this.spring.configLocations(xml("MockJwtDecoder"), xml("AllowBearerTokenInBody")).autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
when(decoder.decode(anyString())).thenReturn(jwt().build());
|
||||
given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build());
|
||||
|
||||
this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isNotFound());
|
||||
@@ -468,7 +462,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
this.spring.configLocations(xml("MockJwtDecoder"), xml("AllowBearerTokenInQuery")).autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
Mockito.when(decoder.decode(anyString())).thenReturn(jwt().build());
|
||||
given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build());
|
||||
|
||||
this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isNotFound());
|
||||
@@ -517,7 +511,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
|
||||
when(decoder.decode(anyString())).thenReturn(jwt().build());
|
||||
given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build());
|
||||
|
||||
this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token"))
|
||||
.andExpect(status().isNotFound());
|
||||
@@ -552,7 +546,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
this.spring.configLocations(xml("MockJwtDecoder"), xml("AccessDeniedHandler")).autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
Mockito.when(decoder.decode(anyString())).thenReturn(jwt().build());
|
||||
given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build());
|
||||
|
||||
this.mvc.perform(get("/authenticated").header("Authorization", "Bearer insufficiently_scoped"))
|
||||
.andExpect(status().isForbidden())
|
||||
@@ -572,7 +566,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
|
||||
OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
|
||||
|
||||
when(jwtValidator.validate(any(Jwt.class))).thenReturn(OAuth2TokenValidatorResult.failure(error));
|
||||
given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
|
||||
|
||||
this.mvc.perform(get("/").header("Authorization", "Bearer " + token)).andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description")));
|
||||
@@ -609,11 +603,11 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
|
||||
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = (Converter<Jwt, JwtAuthenticationToken>) this.spring
|
||||
.getContext().getBean("jwtAuthenticationConverter");
|
||||
when(jwtAuthenticationConverter.convert(any(Jwt.class)))
|
||||
.thenReturn(new JwtAuthenticationToken(jwt().build(), Collections.emptyList()));
|
||||
given(jwtAuthenticationConverter.convert(any(Jwt.class)))
|
||||
.willReturn(new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
|
||||
|
||||
JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
Mockito.when(jwtDecoder.decode(anyString())).thenReturn(jwt().build());
|
||||
given(jwtDecoder.decode(anyString())).willReturn(TestJwts.jwt().build());
|
||||
|
||||
this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());
|
||||
|
||||
@@ -702,8 +696,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
|
||||
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver = this.spring.getContext()
|
||||
.getBean(AuthenticationManagerResolver.class);
|
||||
when(authenticationManagerResolver.resolve(any(HttpServletRequest.class)))
|
||||
.thenReturn(authentication -> new JwtAuthenticationToken(jwt().build(), Collections.emptyList()));
|
||||
given(authenticationManagerResolver.resolve(any(HttpServletRequest.class))).willReturn(
|
||||
authentication -> new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
|
||||
|
||||
this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());
|
||||
|
||||
@@ -754,7 +748,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
this.spring.configLocations(xml("MockJwtDecoder"), xml("BasicAndResourceServer")).autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
when(decoder.decode(anyString())).thenThrow(JwtException.class);
|
||||
given(decoder.decode(anyString())).willThrow(JwtException.class);
|
||||
|
||||
this.mvc.perform(get("/authenticated").with(httpBasic("some", "user"))).andExpect(status().isUnauthorized())
|
||||
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Basic")));
|
||||
@@ -775,7 +769,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
this.spring.configLocations(xml("MockJwtDecoder"), xml("FormAndResourceServer")).autowire();
|
||||
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
when(decoder.decode(anyString())).thenThrow(JwtException.class);
|
||||
given(decoder.decode(anyString())).willThrow(JwtException.class);
|
||||
|
||||
MvcResult result = this.mvc.perform(get("/authenticated")).andExpect(status().isUnauthorized()).andReturn();
|
||||
|
||||
@@ -827,7 +821,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
OAuth2ResourceServerBeanDefinitionParser parser = new OAuth2ResourceServerBeanDefinitionParser(null, null, null,
|
||||
null, null);
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)).thenReturn(true);
|
||||
given(element.hasAttribute(OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF))
|
||||
.willReturn(true);
|
||||
Element child = mock(Element.class);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
|
||||
@@ -844,7 +839,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
OAuth2ResourceServerBeanDefinitionParser parser = new OAuth2ResourceServerBeanDefinitionParser(null, null, null,
|
||||
null, null);
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)).thenReturn(false);
|
||||
given(element.hasAttribute(OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF))
|
||||
.willReturn(false);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
parser.validateConfiguration(element, null, null, pc);
|
||||
verify(pc.getReaderContext()).error(anyString(), eq(element));
|
||||
@@ -854,8 +850,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
public void validateConfigurationWhenBothJwtAttributesThenError() {
|
||||
JwtBeanDefinitionParser parser = new JwtBeanDefinitionParser();
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(JWK_SET_URI)).thenReturn(true);
|
||||
when(element.hasAttribute(DECODER_REF)).thenReturn(true);
|
||||
given(element.hasAttribute(JwtBeanDefinitionParser.JWK_SET_URI)).willReturn(true);
|
||||
given(element.hasAttribute(JwtBeanDefinitionParser.DECODER_REF)).willReturn(true);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
parser.validateConfiguration(element, pc);
|
||||
verify(pc.getReaderContext()).error(anyString(), eq(element));
|
||||
@@ -865,8 +861,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
public void validateConfigurationWhenNoJwtAttributesThenError() {
|
||||
JwtBeanDefinitionParser parser = new JwtBeanDefinitionParser();
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(JWK_SET_URI)).thenReturn(false);
|
||||
when(element.hasAttribute(DECODER_REF)).thenReturn(false);
|
||||
given(element.hasAttribute(JwtBeanDefinitionParser.JWK_SET_URI)).willReturn(false);
|
||||
given(element.hasAttribute(JwtBeanDefinitionParser.DECODER_REF)).willReturn(false);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
parser.validateConfiguration(element, pc);
|
||||
verify(pc.getReaderContext()).error(anyString(), eq(element));
|
||||
@@ -876,8 +872,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
public void validateConfigurationWhenBothOpaqueTokenModesThenError() {
|
||||
OpaqueTokenBeanDefinitionParser parser = new OpaqueTokenBeanDefinitionParser();
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(INTROSPECTION_URI)).thenReturn(true);
|
||||
when(element.hasAttribute(INTROSPECTOR_REF)).thenReturn(true);
|
||||
given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI)).willReturn(true);
|
||||
given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF)).willReturn(true);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
parser.validateConfiguration(element, pc);
|
||||
verify(pc.getReaderContext()).error(anyString(), eq(element));
|
||||
@@ -887,8 +883,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
public void validateConfigurationWhenNoOpaqueTokenModeThenError() {
|
||||
OpaqueTokenBeanDefinitionParser parser = new OpaqueTokenBeanDefinitionParser();
|
||||
Element element = mock(Element.class);
|
||||
when(element.hasAttribute(INTROSPECTION_URI)).thenReturn(false);
|
||||
when(element.hasAttribute(INTROSPECTOR_REF)).thenReturn(false);
|
||||
given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI)).willReturn(false);
|
||||
given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF)).willReturn(false);
|
||||
ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class));
|
||||
parser.validateConfiguration(element, pc);
|
||||
verify(pc.getReaderContext()).error(anyString(), eq(element));
|
||||
@@ -920,8 +916,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
|
||||
private String jwtFromIssuer(String issuer) throws Exception {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(ISS, issuer);
|
||||
claims.put(SUB, "test-subject");
|
||||
claims.put(JwtClaimNames.ISS, issuer);
|
||||
claims.put(JwtClaimNames.SUB, "test-subject");
|
||||
claims.put("scope", "message:read");
|
||||
JWSObject jws = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("1").build(),
|
||||
new Payload(new JSONObject(claims)));
|
||||
@@ -939,7 +935,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
ResponseEntity<String> entity = new ResponseEntity<>(response, headers, HttpStatus.OK);
|
||||
Mockito.when(rest.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(entity);
|
||||
given(rest.exchange(any(RequestEntity.class), eq(String.class))).willReturn(entity);
|
||||
}
|
||||
|
||||
private String json(String name) throws IOException {
|
||||
|
||||
@@ -26,6 +26,7 @@ import okhttp3.mockwebserver.MockWebServer;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.openid4java.consumer.ConsumerManager;
|
||||
import org.openid4java.discovery.yadis.YadisResolver;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
|
||||
@@ -48,7 +49,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
@@ -147,7 +147,7 @@ public class OpenIDConfigTests {
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
|
||||
server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ import org.springframework.security.TestDataSource;
|
||||
import org.springframework.security.config.test.SpringTestRule;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
|
||||
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
@@ -43,9 +45,6 @@ import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER;
|
||||
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
|
||||
import static org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl.CREATE_TABLE_SQL;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
|
||||
@@ -73,7 +72,8 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("WithTokenRepository")).autowire();
|
||||
|
||||
MvcResult result = this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn();
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false))
|
||||
.andReturn();
|
||||
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
@@ -91,10 +91,11 @@ public class RememberMeConfigTests {
|
||||
|
||||
TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
template.execute(CREATE_TABLE_SQL);
|
||||
template.execute(JdbcTokenRepositoryImpl.CREATE_TABLE_SQL);
|
||||
|
||||
MvcResult result = this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn();
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false))
|
||||
.andReturn();
|
||||
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
@@ -111,10 +112,11 @@ public class RememberMeConfigTests {
|
||||
|
||||
TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
template.execute(CREATE_TABLE_SQL);
|
||||
template.execute(JdbcTokenRepositoryImpl.CREATE_TABLE_SQL);
|
||||
|
||||
MvcResult result = this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn();
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false))
|
||||
.andReturn();
|
||||
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
@@ -130,8 +132,9 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("WithServicesRef")).autowire();
|
||||
|
||||
MvcResult result = this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false))
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 5000)).andReturn();
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false))
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 5000))
|
||||
.andReturn();
|
||||
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
@@ -139,7 +142,8 @@ public class RememberMeConfigTests {
|
||||
|
||||
// SEC-909
|
||||
this.mvc.perform(post("/logout").cookie(cookie).with(csrf()))
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)).andReturn();
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -152,7 +156,7 @@ public class RememberMeConfigTests {
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
this.mvc.perform(post("/logout").cookie(cookie).with(csrf()))
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0));
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -162,7 +166,8 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("TokenValidity")).autowire();
|
||||
|
||||
MvcResult result = this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 10000)).andReturn();
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 10000))
|
||||
.andReturn();
|
||||
|
||||
Cookie cookie = rememberMeCookie(result);
|
||||
|
||||
@@ -175,7 +180,7 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("NegativeTokenValidity")).autowire();
|
||||
|
||||
this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, -1));
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, -1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -191,7 +196,7 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("Sec2165")).autowire();
|
||||
|
||||
this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 30));
|
||||
.andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,7 +205,7 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("SecureCookie")).autowire();
|
||||
|
||||
this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, true));
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, true));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,7 +217,7 @@ public class RememberMeConfigTests {
|
||||
this.spring.configLocations(this.xml("Sec1827")).autowire();
|
||||
|
||||
this.rememberAuthentication("user", "password")
|
||||
.andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false));
|
||||
.andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -304,7 +309,8 @@ public class RememberMeConfigTests {
|
||||
|
||||
private ResultActions rememberAuthentication(String username, String password) throws Exception {
|
||||
|
||||
return this.mvc.perform(login(username, password).param(DEFAULT_PARAMETER, "true").with(csrf()))
|
||||
return this.mvc.perform(
|
||||
login(username, password).param(AbstractRememberMeServices.DEFAULT_PARAMETER, "true").with(csrf()))
|
||||
.andExpect(redirectedUrl("/"));
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.hamcrest.core.StringContains.containsString;
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.security.web.context.HttpRequestResponseHolder;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -48,6 +48,7 @@ import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
import org.springframework.security.web.authentication.logout.LogoutSuccessEventPublishingLogoutHandler;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
import org.springframework.security.web.session.SessionManagementFilter;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
@@ -60,7 +61,6 @@ import org.springframework.web.context.WebApplicationContext;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
|
||||
import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
@@ -139,7 +139,8 @@ public class SessionManagementConfigTests {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_MOVED_TEMPORARILY);
|
||||
assertThat(request.getSession(false)).isNotNull();
|
||||
assertThat(request.getSession(false).getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNotNull();
|
||||
assertThat(request.getSession(false)
|
||||
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -169,7 +170,8 @@ public class SessionManagementConfigTests {
|
||||
.session(new MockHttpSession()).with(csrf()))
|
||||
.andExpect(status().isFound()).andExpect(session()).andReturn();
|
||||
|
||||
assertThat(result.getRequest().getSession(false).getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
assertThat(result.getRequest().getSession(false)
|
||||
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -37,7 +37,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.security.config.http.customconfigurer.CustomConfigurer.customConfigurer;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -126,7 +125,7 @@ public class CustomHttpSecurityConfigurerTests {
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.apply(customConfigurer())
|
||||
.apply(CustomConfigurer.customConfigurer())
|
||||
.loginPage("/custom");
|
||||
// @formatter:on
|
||||
}
|
||||
@@ -151,7 +150,7 @@ public class CustomHttpSecurityConfigurerTests {
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
http
|
||||
.apply(customConfigurer())
|
||||
.apply(CustomConfigurer.customConfigurer())
|
||||
.and()
|
||||
.csrf().disable()
|
||||
.formLogin()
|
||||
|
||||
@@ -59,7 +59,6 @@ import org.springframework.security.util.FieldUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML;
|
||||
|
||||
/**
|
||||
* @author Ben Alex
|
||||
@@ -185,7 +184,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ "<global-method-security>" + " <protect-pointcut expression="
|
||||
+ " 'execution(* org.springframework.security.access.annotation.BusinessService.*(..)) "
|
||||
+ " and not execution(* org.springframework.security.access.annotation.BusinessService.someOther(String)))' "
|
||||
+ " access='ROLE_USER'/>" + "</global-method-security>" + AUTH_PROVIDER_XML);
|
||||
+ " access='ROLE_USER'/>" + "</global-method-security>"
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
this.target = (BusinessService) this.appContext.getBean("target");
|
||||
// String method should not be protected
|
||||
this.target.someOther("somestring");
|
||||
@@ -215,7 +215,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ "<b:bean id='businessService' class='org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean'>"
|
||||
+ " <b:property name='serviceUrl' value='http://localhost:8080/SomeService'/>"
|
||||
+ " <b:property name='serviceInterface' value='org.springframework.security.access.annotation.BusinessService'/>"
|
||||
+ "</b:bean>" + AUTH_PROVIDER_XML);
|
||||
+ "</b:bean>" + ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
|
||||
@@ -229,7 +229,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception {
|
||||
setContext("<global-method-security pre-post-annotations='enabled'/>" + AUTH_PROVIDER_XML);
|
||||
setContext("<global-method-security pre-post-annotations='enabled'/>" + ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
AffirmativeBased adm = (AffirmativeBased) this.appContext.getBeansOfType(AffirmativeBased.class).values()
|
||||
.toArray()[0];
|
||||
List voters = (List) FieldUtils.getFieldValue(adm, "decisionVoters");
|
||||
@@ -247,7 +247,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
public void accessIsDeniedForHasRoleExpression() {
|
||||
setContext("<global-method-security pre-post-annotations='enabled'/>"
|
||||
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
this.target = (BusinessService) this.appContext.getBean("target");
|
||||
this.target.someAdminMethod();
|
||||
@@ -259,7 +259,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ "<b:bean id='number' class='java.lang.Integer'>" + " <b:constructor-arg value='1294'/>"
|
||||
+ "</b:bean>"
|
||||
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
ExpressionProtectedBusinessServiceImpl target = (ExpressionProtectedBusinessServiceImpl) this.appContext
|
||||
.getBean("target");
|
||||
@@ -270,7 +270,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
public void preAndPostFilterAnnotationsWorkWithLists() {
|
||||
setContext("<global-method-security pre-post-annotations='enabled'/>"
|
||||
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
this.target = (BusinessService) this.appContext.getBean("target");
|
||||
List<String> arg = new ArrayList<>();
|
||||
@@ -289,7 +289,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
public void prePostFilterAnnotationWorksWithArrays() {
|
||||
setContext("<global-method-security pre-post-annotations='enabled'/>"
|
||||
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
this.target = (BusinessService) this.appContext.getBean("target");
|
||||
Object[] arg = new String[] { "joe", "bob", "sam" };
|
||||
@@ -306,7 +306,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ "<b:bean id='expressionHandler' class='org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler'>"
|
||||
+ " <b:property name='permissionEvaluator' ref='myPermissionEvaluator'/>" + "</b:bean>"
|
||||
+ "<b:bean id='myPermissionEvaluator' class='org.springframework.security.config.method.TestPermissionEvaluator'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
}
|
||||
|
||||
// SEC-1450
|
||||
@@ -317,7 +317,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
"<b:bean id='target' class='org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParserTests$ConcreteFoo'/>"
|
||||
+ "<global-method-security>"
|
||||
+ " <protect-pointcut expression='execution(* org..*Foo.foo(..))' access='ROLE_USER'/>"
|
||||
+ "</global-method-security>" + AUTH_PROVIDER_XML);
|
||||
+ "</global-method-security>" + ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
Foo foo = (Foo) this.appContext.getBean("target");
|
||||
foo.foo(new SecurityConfig("A"));
|
||||
}
|
||||
@@ -327,7 +327,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
@SuppressWarnings("unchecked")
|
||||
public void genericsMethodArgumentNamesAreResolved() {
|
||||
setContext("<b:bean id='target' class='" + ConcreteFoo.class.getName() + "'/>"
|
||||
+ "<global-method-security pre-post-annotations='enabled'/>" + AUTH_PROVIDER_XML);
|
||||
+ "<global-method-security pre-post-annotations='enabled'/>" + ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
Foo foo = (Foo) this.appContext.getBean("target");
|
||||
foo.foo(new SecurityConfig("A"));
|
||||
@@ -341,7 +341,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
parent.registerSingleton("runAsMgr", RunAsManagerImpl.class, props);
|
||||
parent.refresh();
|
||||
|
||||
setContext("<global-method-security run-as-manager-ref='runAsMgr'/>" + AUTH_PROVIDER_XML, parent);
|
||||
setContext("<global-method-security run-as-manager-ref='runAsMgr'/>" + ConfigTestUtils.AUTH_PROVIDER_XML,
|
||||
parent);
|
||||
RunAsManagerImpl ram = (RunAsManagerImpl) this.appContext.getBean("runAsMgr");
|
||||
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) this.appContext
|
||||
.getBeansOfType(MethodSecurityMetadataSourceAdvisor.class).values().toArray()[0];
|
||||
@@ -355,7 +356,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ "<method-security-metadata-source id='mds'>" + " <protect method='" + Foo.class.getName()
|
||||
+ ".foo' access='ROLE_ADMIN'/>" + "</method-security-metadata-source>"
|
||||
+ "<global-method-security pre-post-annotations='enabled' metadata-source-ref='mds'/>"
|
||||
+ AUTH_PROVIDER_XML);
|
||||
+ ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
// External MDS should take precedence over PreAuthorize
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
Foo foo = (Foo) this.appContext.getBean("target");
|
||||
@@ -377,7 +378,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
|
||||
+ ".foo' access='ROLE_ADMIN'/>" + "</method-security-metadata-source>"
|
||||
+ "<global-method-security pre-post-annotations='enabled' metadata-source-ref='mds' authentication-manager-ref='customAuthMgr'/>"
|
||||
+ "<b:bean id='customAuthMgr' class='org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParserTests$CustomAuthManager'>"
|
||||
+ " <b:constructor-arg value='authManager'/>" + "</b:bean>" + AUTH_PROVIDER_XML);
|
||||
+ " <b:constructor-arg value='authManager'/>" + "</b:bean>" + ConfigTestUtils.AUTH_PROVIDER_XML);
|
||||
SecurityContextHolder.getContext().setAuthentication(this.bob);
|
||||
Foo foo = (Foo) this.appContext.getBean("target");
|
||||
try {
|
||||
|
||||
@@ -26,7 +26,7 @@ import org.springframework.security.provisioning.UserDetailsManager;
|
||||
import org.springframework.security.util.InMemoryResource;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.provisioning.UserDetailsManager;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.provisioning.UserDetailsManager;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
|
||||
@@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
|
||||
import org.springframework.mock.web.MockServletConfig;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.security.config.BeanIds;
|
||||
import org.springframework.security.config.util.InMemoryXmlWebApplicationContext;
|
||||
import org.springframework.test.context.web.GenericXmlWebContextLoader;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
@@ -41,7 +42,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN;
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
|
||||
/**
|
||||
@@ -129,7 +129,7 @@ public class SpringTestContext implements Closeable {
|
||||
this.context.setServletConfig(new MockServletConfig());
|
||||
this.context.refresh();
|
||||
|
||||
if (this.context.containsBean(SPRING_SECURITY_FILTER_CHAIN)) {
|
||||
if (this.context.containsBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)) {
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity())
|
||||
.apply(new AddFilter()).build();
|
||||
this.context.getBeanFactory().registerResolvableDependency(MockMvc.class, mockMvc);
|
||||
|
||||
@@ -23,10 +23,6 @@ import org.springframework.core.io.Resource;
|
||||
import org.springframework.security.util.InMemoryResource;
|
||||
import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext;
|
||||
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_CLOSE;
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_OPENING;
|
||||
import static org.springframework.security.config.util.InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION;
|
||||
|
||||
/**
|
||||
* @author Joe Grandja
|
||||
*/
|
||||
@@ -35,15 +31,16 @@ public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebAppl
|
||||
private Resource inMemoryXml;
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml) {
|
||||
this(xml, SPRING_SECURITY_VERSION, null);
|
||||
this(xml, InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION, null);
|
||||
}
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml, ApplicationContext parent) {
|
||||
this(xml, SPRING_SECURITY_VERSION, parent);
|
||||
this(xml, InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION, parent);
|
||||
}
|
||||
|
||||
public InMemoryXmlWebApplicationContext(String xml, String secVersion, ApplicationContext parent) {
|
||||
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
|
||||
String fullXml = InMemoryXmlApplicationContext.BEANS_OPENING + secVersion + ".xsd'>\n" + xml
|
||||
+ InMemoryXmlApplicationContext.BEANS_CLOSE;
|
||||
this.inMemoryXml = new InMemoryResource(fullXml);
|
||||
setAllowBeanDefinitionOverriding(true);
|
||||
setParent(parent);
|
||||
|
||||
@@ -37,7 +37,7 @@ import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.reactive.CorsConfigurationSource;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.security.web.server.header.XXssProtectionServerHttpHe
|
||||
import org.springframework.test.web.reactive.server.FluxExchangeResult;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
|
||||
/**
|
||||
|
||||
@@ -80,6 +80,7 @@ import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.JwtValidationException;
|
||||
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory;
|
||||
import org.springframework.security.oauth2.jwt.TestJwts;
|
||||
import org.springframework.security.test.web.reactive.server.WebTestClientBuilder;
|
||||
import org.springframework.security.web.server.SecurityWebFilterChain;
|
||||
import org.springframework.security.web.server.WebFilterChainProxy;
|
||||
@@ -108,7 +109,6 @@ import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -680,7 +680,7 @@ public class OAuth2LoginTests {
|
||||
claims.put(IdTokenClaimNames.ISS, "http://localhost/issuer");
|
||||
claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client"));
|
||||
claims.put(IdTokenClaimNames.AZP, "client");
|
||||
Jwt jwt = jwt().claims(c -> c.putAll(claims)).build();
|
||||
Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build();
|
||||
return Mono.just(jwt);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.TestJwts;
|
||||
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter;
|
||||
@@ -80,13 +81,12 @@ import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
import static org.hamcrest.CoreMatchers.startsWith;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.springframework.security.oauth2.jwt.TestJwts.jwt;
|
||||
|
||||
/**
|
||||
* Tests for
|
||||
@@ -108,7 +108,7 @@ public class OAuth2ResourceServerSpecTests {
|
||||
+ " \"n\":\"0IUjrPZDz-3z0UE4ppcKU36v7hnh8FJjhu3lbJYj0qj9eZiwEJxi9HHUfSK1DhUQG7mJBbYTK1tPYCgre5EkfKh-64VhYUa-vz17zYCmuB8fFj4XHE3MLkWIG-AUn8hNbPzYYmiBTjfGnMKxLHjsbdTiF4mtn-85w366916R6midnAuiPD4HjZaZ1PAsuY60gr8bhMEDtJ8unz81hoQrozpBZJ6r8aR1PrsWb1OqPMloK9kAIutJNvWYKacp8WYAp2WWy72PxQ7Fb0eIA1br3A5dnp-Cln6JROJcZUIRJ-QvS6QONWeS2407uQmS-i-lybsqaH0ldYC7NBEBA5inPQ\"\n"
|
||||
+ " }\n" + " ]\n" + "}\n";
|
||||
|
||||
private Jwt jwt = jwt().build();
|
||||
private Jwt jwt = TestJwts.jwt().build();
|
||||
|
||||
private String clientId = "client";
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ import org.springframework.security.web.server.csrf.CsrfWebFilter;
|
||||
import org.springframework.security.web.server.csrf.ServerCsrfTokenRepository;
|
||||
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
|
||||
import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.reactive.server.EntityExchangeResult;
|
||||
import org.springframework.test.web.reactive.server.FluxExchangeResult;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
@@ -78,7 +79,6 @@ import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
import static org.springframework.security.config.Customizer.withDefaults;
|
||||
import static org.springframework.test.util.ReflectionTestUtils.getField;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
@@ -187,8 +187,8 @@ public class ServerHttpSecurityTests {
|
||||
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).isNotPresent();
|
||||
|
||||
Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class)
|
||||
.map(logoutWebFilter -> (ServerLogoutHandler) getField(logoutWebFilter, LogoutWebFilter.class,
|
||||
"logoutHandler"));
|
||||
.map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
|
||||
LogoutWebFilter.class, "logoutHandler"));
|
||||
|
||||
assertThat(logoutHandler).get().isExactlyInstanceOf(SecurityContextServerLogoutHandler.class);
|
||||
}
|
||||
@@ -199,17 +199,17 @@ public class ServerHttpSecurityTests {
|
||||
.and().build();
|
||||
|
||||
assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).get()
|
||||
.extracting(csrfWebFilter -> getField(csrfWebFilter, "csrfTokenRepository"))
|
||||
.extracting(csrfWebFilter -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository"))
|
||||
.isEqualTo(this.csrfTokenRepository);
|
||||
|
||||
Optional<ServerLogoutHandler> logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class)
|
||||
.map(logoutWebFilter -> (ServerLogoutHandler) getField(logoutWebFilter, LogoutWebFilter.class,
|
||||
"logoutHandler"));
|
||||
.map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter,
|
||||
LogoutWebFilter.class, "logoutHandler"));
|
||||
|
||||
assertThat(logoutHandler).get().isExactlyInstanceOf(DelegatingServerLogoutHandler.class)
|
||||
.extracting(delegatingLogoutHandler -> ((List<ServerLogoutHandler>) getField(delegatingLogoutHandler,
|
||||
DelegatingServerLogoutHandler.class, "delegates")).stream().map(ServerLogoutHandler::getClass)
|
||||
.collect(Collectors.toList()))
|
||||
.extracting(delegatingLogoutHandler -> ((List<ServerLogoutHandler>) ReflectionTestUtils
|
||||
.getField(delegatingLogoutHandler, DelegatingServerLogoutHandler.class, "delegates")).stream()
|
||||
.map(ServerLogoutHandler::getClass).collect(Collectors.toList()))
|
||||
.isEqualTo(Arrays.asList(SecurityContextServerLogoutHandler.class, CsrfServerLogoutHandler.class));
|
||||
}
|
||||
|
||||
@@ -439,8 +439,8 @@ public class ServerHttpSecurityTests {
|
||||
|
||||
OAuth2LoginAuthenticationWebFilter authenticationWebFilter = getWebFilter(securityFilterChain,
|
||||
OAuth2LoginAuthenticationWebFilter.class).get();
|
||||
Object handler = getField(authenticationWebFilter, "authenticationSuccessHandler");
|
||||
assertThat(getField(handler, "requestCache")).isSameAs(requestCache);
|
||||
Object handler = ReflectionTestUtils.getField(authenticationWebFilter, "authenticationSuccessHandler");
|
||||
assertThat(ReflectionTestUtils.getField(handler, "requestCache")).isSameAs(requestCache);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -467,7 +467,7 @@ public class ServerHttpSecurityTests {
|
||||
|
||||
private boolean isX509Filter(WebFilter filter) {
|
||||
try {
|
||||
Object converter = getField(filter, "authenticationConverter");
|
||||
Object converter = ReflectionTestUtils.getField(filter, "authenticationConverter");
|
||||
return converter.getClass().isAssignableFrom(ServerX509AuthenticationConverter.class);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
|
||||
Reference in New Issue
Block a user