Always use 'this.' when accessing fields

Apply an Eclipse cleanup rules to ensure that fields are always accessed
using `this.`. This aligns with the style used by Spring Framework and
helps users quickly see the difference between a local and member
variable.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-26 11:51:05 -07:00
committed by Rob Winch
parent 6894ff5d12
commit 8866fa6fb0
793 changed files with 8689 additions and 8459 deletions

View File

@@ -32,24 +32,24 @@ public class BeanNameCollectingPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (beanName != null) {
beforeInitPostProcessedBeans.add(beanName);
this.beforeInitPostProcessedBeans.add(beanName);
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanName != null) {
afterInitPostProcessedBeans.add(beanName);
this.afterInitPostProcessedBeans.add(beanName);
}
return bean;
}
public Set<String> getBeforeInitPostProcessedBeans() {
return beforeInitPostProcessedBeans;
return this.beforeInitPostProcessedBeans;
}
public Set<String> getAfterInitPostProcessedBeans() {
return afterInitPostProcessedBeans;
return this.afterInitPostProcessedBeans;
}
}

View File

@@ -42,33 +42,33 @@ public class CollectingAppListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AbstractAuthenticationEvent) {
events.add(event);
authenticationEvents.add((AbstractAuthenticationEvent) event);
this.events.add(event);
this.authenticationEvents.add((AbstractAuthenticationEvent) event);
}
if (event instanceof AbstractAuthenticationFailureEvent) {
events.add(event);
authenticationFailureEvents.add((AbstractAuthenticationFailureEvent) event);
this.events.add(event);
this.authenticationFailureEvents.add((AbstractAuthenticationFailureEvent) event);
}
if (event instanceof AbstractAuthorizationEvent) {
events.add(event);
authorizationEvents.add((AbstractAuthorizationEvent) event);
this.events.add(event);
this.authorizationEvents.add((AbstractAuthorizationEvent) event);
}
}
public Set<ApplicationEvent> getEvents() {
return events;
return this.events;
}
public Set<AbstractAuthenticationEvent> getAuthenticationEvents() {
return authenticationEvents;
return this.authenticationEvents;
}
public Set<AbstractAuthenticationFailureEvent> getAuthenticationFailureEvents() {
return authenticationFailureEvents;
return this.authenticationFailureEvents;
}
public Set<AbstractAuthorizationEvent> getAuthorizationEvents() {
return authorizationEvents;
return this.authorizationEvents;
}
}

View File

@@ -31,13 +31,13 @@ public class DataSourcePopulator implements InitializingBean {
JdbcTemplate template;
public void afterPropertiesSet() {
Assert.notNull(template, "dataSource required");
Assert.notNull(this.template, "dataSource required");
template.execute(
this.template.execute(
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);");
template.execute(
this.template.execute(
"CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));");
template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");
this.template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");
/*
* Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
@@ -46,21 +46,21 @@ public class DataSourcePopulator implements InitializingBean {
* is disabled) Encoded password for bill is "wombat" Encoded password for bob is
* "wombat" Encoded password for jane is "wombat"
*/
template.execute("INSERT INTO USERS VALUES('rod','{noop}koala',TRUE);");
template.execute("INSERT INTO USERS VALUES('dianne','{MD5}65d15fe9156f9c4bbffd98085992a44e',TRUE);");
template.execute("INSERT INTO USERS VALUES('scott','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
template.execute("INSERT INTO USERS VALUES('peter','{MD5}22b5c9accc6e1ba628cedc63a72d57f8',FALSE);");
template.execute("INSERT INTO USERS VALUES('bill','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
template.execute("INSERT INTO USERS VALUES('bob','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
template.execute("INSERT INTO USERS VALUES('jane','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');");
template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
this.template.execute("INSERT INTO USERS VALUES('rod','{noop}koala',TRUE);");
this.template.execute("INSERT INTO USERS VALUES('dianne','{MD5}65d15fe9156f9c4bbffd98085992a44e',TRUE);");
this.template.execute("INSERT INTO USERS VALUES('scott','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
this.template.execute("INSERT INTO USERS VALUES('peter','{MD5}22b5c9accc6e1ba628cedc63a72d57f8',FALSE);");
this.template.execute("INSERT INTO USERS VALUES('bill','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
this.template.execute("INSERT INTO USERS VALUES('bob','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
this.template.execute("INSERT INTO USERS VALUES('jane','{MD5}2b58af6dddbd072ed27ffc86725d7d3a',TRUE);");
this.template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('rod','ROLE_SUPERVISOR');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('dianne','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('scott','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('peter','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('bill','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('bob','ROLE_USER');");
this.template.execute("INSERT INTO AUTHORITIES VALUES('jane','ROLE_USER');");
}
public void setDataSource(DataSource dataSource) {

View File

@@ -59,25 +59,25 @@ public class FilterChainProxyConfigTests {
public void loadContext() {
System.setProperty("sec1235.pattern1", "/login");
System.setProperty("sec1235.pattern2", "/logout");
appCtx = new ClassPathXmlApplicationContext("org/springframework/security/util/filtertest-valid.xml");
this.appCtx = new ClassPathXmlApplicationContext("org/springframework/security/util/filtertest-valid.xml");
}
@After
public void closeContext() {
if (appCtx != null) {
appCtx.close();
if (this.appCtx != null) {
this.appCtx.close();
}
}
@Test
public void normalOperation() throws Exception {
FilterChainProxy filterChainProxy = appCtx.getBean("filterChain", FilterChainProxy.class);
FilterChainProxy filterChainProxy = this.appCtx.getBean("filterChain", FilterChainProxy.class);
doNormalOperation(filterChainProxy);
}
@Test
public void normalOperationWithNewConfig() throws Exception {
FilterChainProxy filterChainProxy = appCtx.getBean("newFilterChainProxy", FilterChainProxy.class);
FilterChainProxy filterChainProxy = this.appCtx.getBean("newFilterChainProxy", FilterChainProxy.class);
filterChainProxy.setFirewall(new DefaultHttpFirewall());
checkPathAndFilterOrder(filterChainProxy);
doNormalOperation(filterChainProxy);
@@ -85,7 +85,7 @@ public class FilterChainProxyConfigTests {
@Test
public void normalOperationWithNewConfigRegex() throws Exception {
FilterChainProxy filterChainProxy = appCtx.getBean("newFilterChainProxyRegex", FilterChainProxy.class);
FilterChainProxy filterChainProxy = this.appCtx.getBean("newFilterChainProxyRegex", FilterChainProxy.class);
filterChainProxy.setFirewall(new DefaultHttpFirewall());
checkPathAndFilterOrder(filterChainProxy);
doNormalOperation(filterChainProxy);
@@ -93,7 +93,8 @@ public class FilterChainProxyConfigTests {
@Test
public void normalOperationWithNewConfigNonNamespace() throws Exception {
FilterChainProxy filterChainProxy = appCtx.getBean("newFilterChainProxyNonNamespace", FilterChainProxy.class);
FilterChainProxy filterChainProxy = this.appCtx.getBean("newFilterChainProxyNonNamespace",
FilterChainProxy.class);
filterChainProxy.setFirewall(new DefaultHttpFirewall());
checkPathAndFilterOrder(filterChainProxy);
doNormalOperation(filterChainProxy);
@@ -101,14 +102,15 @@ public class FilterChainProxyConfigTests {
@Test
public void pathWithNoMatchHasNoFilters() {
FilterChainProxy filterChainProxy = appCtx.getBean("newFilterChainProxyNoDefaultPath", FilterChainProxy.class);
FilterChainProxy filterChainProxy = this.appCtx.getBean("newFilterChainProxyNoDefaultPath",
FilterChainProxy.class);
assertThat(filterChainProxy.getFilters("/nomatch")).isNull();
}
// SEC-1235
@Test
public void mixingPatternsAndPlaceholdersDoesntCauseOrderingIssues() {
FilterChainProxy fcp = appCtx.getBean("sec1235FilterChainProxy", FilterChainProxy.class);
FilterChainProxy fcp = this.appCtx.getBean("sec1235FilterChainProxy", FilterChainProxy.class);
List<SecurityFilterChain> chains = fcp.getFilterChains();
assertThat(getPattern(chains.get(0))).isEqualTo("/login*");

View File

@@ -40,8 +40,8 @@ public class InvalidConfigurationTests {
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
}
@@ -79,7 +79,7 @@ public class InvalidConfigurationTests {
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
this.appContext = new InMemoryXmlApplicationContext(context);
}
}

View File

@@ -27,7 +27,7 @@ public class PostProcessedMockUserDetailsService implements UserDetailsService {
}
public String getPostProcessorWasHere() {
return postProcessorWasHere;
return this.postProcessorWasHere;
}
public void setPostProcessorWasHere(String postProcessorWasHere) {

View File

@@ -106,8 +106,8 @@ public class SecurityNamespaceHandlerTests {
@Test
public void filterNoClassDefFoundError() throws Exception {
String className = "javax.servlet.Filter";
thrown.expect(BeanDefinitionParsingException.class);
thrown.expectMessage("NoClassDefFoundError: " + className);
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));
@@ -127,8 +127,8 @@ public class SecurityNamespaceHandlerTests {
@Test
public void filterChainProxyClassNotFoundException() throws Exception {
String className = FILTER_CHAIN_PROXY_CLASSNAME;
thrown.expect(BeanDefinitionParsingException.class);
thrown.expectMessage("ClassNotFoundException: " + className);
this.thrown.expect(BeanDefinitionParsingException.class);
this.thrown.expectMessage("ClassNotFoundException: " + className);
spy(ClassUtils.class);
doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));

View File

@@ -28,7 +28,7 @@ class ConcereteSecurityConfigurerAdapter extends SecurityConfigurerAdapter<Objec
@Override
public void configure(SecurityBuilder<Object> builder) {
list = postProcess(list);
this.list = postProcess(this.list);
}
public ConcereteSecurityConfigurerAdapter list(List<Object> l) {

View File

@@ -28,15 +28,15 @@ public class SecurityConfigurerAdapterTests {
@Before
public void setup() {
adapter = new ConcereteSecurityConfigurerAdapter();
this.adapter = new ConcereteSecurityConfigurerAdapter();
}
@Test
public void postProcessObjectPostProcessorsAreSorted() {
adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.LOWEST_PRECEDENCE));
adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.HIGHEST_PRECEDENCE));
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.LOWEST_PRECEDENCE));
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.HIGHEST_PRECEDENCE));
assertThat(adapter.postProcess("hi"))
assertThat(this.adapter.postProcess("hi"))
.isEqualTo("hi " + Ordered.HIGHEST_PRECEDENCE + " " + Ordered.LOWEST_PRECEDENCE);
}
@@ -49,12 +49,12 @@ public class SecurityConfigurerAdapterTests {
}
public int getOrder() {
return order;
return this.order;
}
@SuppressWarnings("unchecked")
public String postProcess(String object) {
return object + " " + order;
return object + " " + this.order;
}
}

View File

@@ -40,7 +40,7 @@ public class EnableGlobalAuthenticationTests {
public void authenticationConfigurationWhenGetAuthenticationManagerThenNotNull() throws Exception {
this.spring.register(Config.class).autowire();
AuthenticationConfiguration auth = spring.getContext().getBean(AuthenticationConfiguration.class);
AuthenticationConfiguration auth = this.spring.getContext().getBean(AuthenticationConfiguration.class);
assertThat(auth.getAuthenticationManager()).isNotNull();
}
@@ -116,7 +116,7 @@ public class EnableGlobalAuthenticationTests {
}
public Child getChild() {
return child;
return this.child;
}
}

View File

@@ -30,15 +30,15 @@ public class LdapAuthenticationProviderConfigurerTests {
@Before
public void setUp() {
configurer = new LdapAuthenticationProviderConfigurer<>();
this.configurer = new LdapAuthenticationProviderConfigurer<>();
}
// SEC-2557
@Test
public void getAuthoritiesMapper() throws Exception {
assertThat(configurer.getAuthoritiesMapper()).isInstanceOf(SimpleAuthorityMapper.class);
configurer.authoritiesMapper(new NullAuthoritiesMapper());
assertThat(configurer.getAuthoritiesMapper()).isInstanceOf(NullAuthoritiesMapper.class);
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(SimpleAuthorityMapper.class);
this.configurer.authoritiesMapper(new NullAuthoritiesMapper());
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(NullAuthoritiesMapper.class);
}

View File

@@ -38,13 +38,13 @@ public class UserDetailsManagerConfigurerTests {
@Before
public void setup() {
userDetailsManager = new InMemoryUserDetailsManager();
this.userDetailsManager = new InMemoryUserDetailsManager();
}
@Test
public void allAttributesSupported() {
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
userDetailsManager).withUser("user").password("password").roles("USER").disabled(true)
this.userDetailsManager).withUser("user").password("password").roles("USER").disabled(true)
.accountExpired(true).accountLocked(true).credentialsExpired(true).build();
assertThat(userDetails.getUsername()).isEqualTo("user");
@@ -61,7 +61,7 @@ public class UserDetailsManagerConfigurerTests {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
userDetailsManager).withUser("user").password("password").authorities(authority).build();
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}
@@ -71,7 +71,7 @@ public class UserDetailsManagerConfigurerTests {
String authority = "ROLE_USER";
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
userDetailsManager).withUser("user").password("password").authorities(authority).build();
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get().getAuthority()).isEqualTo(authority);
}
@@ -81,7 +81,8 @@ public class UserDetailsManagerConfigurerTests {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
userDetailsManager).withUser("user").password("password").authorities(Arrays.asList(authority)).build();
this.userDetailsManager).withUser("user").password("password").authorities(Arrays.asList(authority))
.build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}

View File

@@ -71,7 +71,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationProvider authenticationProvider() {
Assert.notNull(myUserRepository);
Assert.notNull(this.myUserRepository);
return new AuthenticationProvider() {
public boolean supports(Class<?> authentication) {
return true;
@@ -80,7 +80,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Object principal = authentication.getPrincipal();
String username = String.valueOf(principal);
User user = myUserRepository.findByUsername(username);
User user = SecurityConfig.this.myUserRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("No user for principal " + principal);
}

View File

@@ -36,7 +36,7 @@ public class User {
private String password;
public Long getId() {
return id;
return this.id;
}
public void setId(Long id) {
@@ -44,7 +44,7 @@ public class User {
}
public String getUsername() {
return username;
return this.username;
}
public void setUsername(String username) {
@@ -52,7 +52,7 @@ public class User {
}
public String getPassword() {
return password;
return this.password;
}
public void setPassword(String password) {

View File

@@ -38,89 +38,89 @@ public class DelegatingReactiveMessageService implements ReactiveMessageService
@Override
public Mono<String> monoFindById(long id) {
return delegate.monoFindById(id);
return this.delegate.monoFindById(id);
}
@Override
@PreAuthorize("hasRole('ADMIN')")
public Mono<String> monoPreAuthorizeHasRoleFindById(long id) {
return delegate.monoPreAuthorizeHasRoleFindById(id);
return this.delegate.monoPreAuthorizeHasRoleFindById(id);
}
@Override
@PostAuthorize("returnObject?.contains(authentication?.name)")
public Mono<String> monoPostAuthorizeFindById(long id) {
return delegate.monoPostAuthorizeFindById(id);
return this.delegate.monoPostAuthorizeFindById(id);
}
@Override
@PreAuthorize("@authz.check(#id)")
public Mono<String> monoPreAuthorizeBeanFindById(long id) {
return delegate.monoPreAuthorizeBeanFindById(id);
return this.delegate.monoPreAuthorizeBeanFindById(id);
}
@Override
@PostAuthorize("@authz.check(authentication, returnObject)")
public Mono<String> monoPostAuthorizeBeanFindById(long id) {
return delegate.monoPostAuthorizeBeanFindById(id);
return this.delegate.monoPostAuthorizeBeanFindById(id);
}
@Override
public Flux<String> fluxFindById(long id) {
return delegate.fluxFindById(id);
return this.delegate.fluxFindById(id);
}
@Override
@PreAuthorize("hasRole('ADMIN')")
public Flux<String> fluxPreAuthorizeHasRoleFindById(long id) {
return delegate.fluxPreAuthorizeHasRoleFindById(id);
return this.delegate.fluxPreAuthorizeHasRoleFindById(id);
}
@Override
@PostAuthorize("returnObject?.contains(authentication?.name)")
public Flux<String> fluxPostAuthorizeFindById(long id) {
return delegate.fluxPostAuthorizeFindById(id);
return this.delegate.fluxPostAuthorizeFindById(id);
}
@Override
@PreAuthorize("@authz.check(#id)")
public Flux<String> fluxPreAuthorizeBeanFindById(long id) {
return delegate.fluxPreAuthorizeBeanFindById(id);
return this.delegate.fluxPreAuthorizeBeanFindById(id);
}
@Override
@PostAuthorize("@authz.check(authentication, returnObject)")
public Flux<String> fluxPostAuthorizeBeanFindById(long id) {
return delegate.fluxPostAuthorizeBeanFindById(id);
return this.delegate.fluxPostAuthorizeBeanFindById(id);
}
@Override
public Publisher<String> publisherFindById(long id) {
return delegate.publisherFindById(id);
return this.delegate.publisherFindById(id);
}
@Override
@PreAuthorize("hasRole('ADMIN')")
public Publisher<String> publisherPreAuthorizeHasRoleFindById(long id) {
return delegate.publisherPreAuthorizeHasRoleFindById(id);
return this.delegate.publisherPreAuthorizeHasRoleFindById(id);
}
@Override
@PostAuthorize("returnObject?.contains(authentication?.name)")
public Publisher<String> publisherPostAuthorizeFindById(long id) {
return delegate.publisherPostAuthorizeFindById(id);
return this.delegate.publisherPostAuthorizeFindById(id);
}
@Override
@PreAuthorize("@authz.check(#id)")
public Publisher<String> publisherPreAuthorizeBeanFindById(long id) {
return delegate.publisherPreAuthorizeBeanFindById(id);
return this.delegate.publisherPreAuthorizeBeanFindById(id);
}
@Override
@PostAuthorize("@authz.check(authentication, returnObject)")
public Publisher<String> publisherPostAuthorizeBeanFindById(long id) {
return delegate.publisherPostAuthorizeBeanFindById(id);
return this.delegate.publisherPostAuthorizeBeanFindById(id);
}
}

View File

@@ -63,7 +63,7 @@ public class EnableReactiveMethodSecurityTests {
@After
public void cleanup() {
reset(delegate);
reset(this.delegate);
}
@Autowired
@@ -80,11 +80,11 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.monoFindById(1L)).thenReturn(Mono.from(result));
when(this.delegate.monoFindById(1L)).thenReturn(Mono.from(this.result));
this.delegate.monoFindById(1L);
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
@@ -98,35 +98,37 @@ public class EnableReactiveMethodSecurityTests {
public void monoPreAuthorizeHasRoleWhenGrantedThenSuccess() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L).subscriberContext(withAdmin);
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@Test
public void monoPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(result));
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(result));
when(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).thenReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenGrantedThenSuccess() {
when(this.delegate.monoPreAuthorizeBeanFindById(2L)).thenReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L).subscriberContext(withAdmin);
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -140,29 +142,29 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(result));
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(result));
when(this.delegate.monoPreAuthorizeBeanFindById(1L)).thenReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void monoPostAuthorizeWhenAuthorizedThenSuccess() {
when(this.delegate.monoPostAuthorizeFindById(1L)).thenReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeFindById(1L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -170,7 +172,7 @@ public class EnableReactiveMethodSecurityTests {
public void monoPostAuthorizeWhenNotAuthorizedThenDenied() {
when(this.delegate.monoPostAuthorizeBeanFindById(1L)).thenReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -178,7 +180,7 @@ public class EnableReactiveMethodSecurityTests {
public void monoPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
when(this.delegate.monoPostAuthorizeBeanFindById(2L)).thenReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -194,7 +196,7 @@ public class EnableReactiveMethodSecurityTests {
public void monoPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
when(this.delegate.monoPostAuthorizeBeanFindById(1L)).thenReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(withUser);
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -202,11 +204,11 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.fluxFindById(1L)).thenReturn(Flux.from(result));
when(this.delegate.fluxFindById(1L)).thenReturn(Flux.from(this.result));
this.delegate.fluxFindById(1L);
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
@@ -220,36 +222,38 @@ public class EnableReactiveMethodSecurityTests {
public void fluxPreAuthorizeHasRoleWhenGrantedThenSuccess() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L).subscriberContext(withAdmin);
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
.verifyComplete();
}
@Test
public void fluxPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(result));
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(result));
when(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).thenReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenGrantedThenSuccess() {
when(this.delegate.fluxPreAuthorizeBeanFindById(2L)).thenReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L).subscriberContext(withAdmin);
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -263,29 +267,29 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(result));
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(result));
when(this.delegate.fluxPreAuthorizeBeanFindById(1L)).thenReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void fluxPostAuthorizeWhenAuthorizedThenSuccess() {
when(this.delegate.fluxPostAuthorizeFindById(1L)).thenReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeFindById(1L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -293,7 +297,7 @@ public class EnableReactiveMethodSecurityTests {
public void fluxPostAuthorizeWhenNotAuthorizedThenDenied() {
when(this.delegate.fluxPostAuthorizeBeanFindById(1L)).thenReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -301,7 +305,7 @@ public class EnableReactiveMethodSecurityTests {
public void fluxPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
when(this.delegate.fluxPostAuthorizeBeanFindById(2L)).thenReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -317,7 +321,7 @@ public class EnableReactiveMethodSecurityTests {
public void fluxPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
when(this.delegate.fluxPostAuthorizeBeanFindById(1L)).thenReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(withUser);
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -325,11 +329,11 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherWhenPermitAllThenAopDoesNotSubscribe() {
when(this.delegate.publisherFindById(1L)).thenReturn(result);
when(this.delegate.publisherFindById(1L)).thenReturn(this.result);
this.delegate.publisherFindById(1L);
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
@@ -344,30 +348,30 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(withAdmin);
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith(s -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
.verifyComplete();
}
@Test
public void publisherPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(result);
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(result);
when(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).thenReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
@@ -375,7 +379,7 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPreAuthorizeBeanFindById(2L)).thenReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
.subscriberContext(withAdmin);
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -389,23 +393,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(result);
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(result);
when(this.delegate.publisherPreAuthorizeBeanFindById(1L)).thenReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
result.assertNoSubscribers();
this.result.assertNoSubscribers();
}
@Test
@@ -413,7 +417,7 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPostAuthorizeFindById(1L)).thenReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -422,7 +426,7 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPostAuthorizeBeanFindById(1L)).thenReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -431,7 +435,7 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPostAuthorizeBeanFindById(2L)).thenReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -448,7 +452,7 @@ public class EnableReactiveMethodSecurityTests {
when(this.delegate.publisherPostAuthorizeBeanFindById(1L)).thenReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(withUser);
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -467,7 +471,7 @@ public class EnableReactiveMethodSecurityTests {
@Bean
public DelegatingReactiveMessageService defaultMessageService() {
return new DelegatingReactiveMessageService(delegate);
return new DelegatingReactiveMessageService(this.delegate);
}
@Bean

View File

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

View File

@@ -78,9 +78,9 @@ public class Sec2758Tests {
this.spring.register(SecurityConfig.class).autowire();
assertThatCode(() -> service.doJsr250()).doesNotThrowAnyException();
assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException();
assertThatCode(() -> service.doPreAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException();
}
@EnableWebSecurity

View File

@@ -60,14 +60,14 @@ public class HttpSecurityHeadersTests {
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.springSecurityFilterChain).build();
}
// gh-2953
// gh-3975
@Test
public void headerWhenSpringMvcResourceThenCacheRelatedHeadersReset() throws Exception {
mockMvc.perform(get("/resources/file.js")).andExpect(status().isOk())
this.mockMvc.perform(get("/resources/file.js")).andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "max-age=12345"))
.andExpect(header().doesNotExist(HttpHeaders.PRAGMA))
.andExpect(header().doesNotExist(HttpHeaders.EXPIRES));
@@ -75,7 +75,7 @@ public class HttpSecurityHeadersTests {
@Test
public void headerWhenNotSpringResourceThenCacheRelatedHeadersSet() throws Exception {
mockMvc.perform(get("/notresource"))
this.mockMvc.perform(get("/notresource"))
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
.andExpect(header().string(HttpHeaders.EXPIRES, "0"));

View File

@@ -72,8 +72,8 @@ public class WebSecurityConfigurerAdapterPowermockTests {
@After
public void close() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}

View File

@@ -67,7 +67,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockMvc.perform(get("/users/self")).andExpect(status().isOk()).andExpect(content().string("extracted-user"));
}

View File

@@ -227,7 +227,7 @@ public class EnableWebSecurityTests {
}
public Child getChild() {
return child;
return this.child;
}
}

View File

@@ -64,10 +64,10 @@ public class WebMvcSecurityConfigurationTests {
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
authentication = new TestingAuthenticationToken("user", "password",
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
this.authentication = new TestingAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);
SecurityContextHolder.getContext().setAuthentication(this.authentication);
}
@After
@@ -77,14 +77,15 @@ public class WebMvcSecurityConfigurationTests {
@Test
public void authenticationPrincipalResolved() throws Exception {
mockMvc.perform(get("/authentication-principal")).andExpect(assertResult(authentication.getPrincipal()))
this.mockMvc.perform(get("/authentication-principal"))
.andExpect(assertResult(this.authentication.getPrincipal()))
.andExpect(view().name("authentication-principal-view"));
}
@Test
public void deprecatedAuthenticationPrincipalResolved() throws Exception {
mockMvc.perform(get("/deprecated-authentication-principal"))
.andExpect(assertResult(authentication.getPrincipal()))
this.mockMvc.perform(get("/deprecated-authentication-principal"))
.andExpect(assertResult(this.authentication.getPrincipal()))
.andExpect(view().name("deprecated-authentication-principal-view"));
}
@@ -93,7 +94,7 @@ public class WebMvcSecurityConfigurationTests {
CsrfToken csrfToken = new DefaultCsrfToken("headerName", "paramName", "token");
MockHttpServletRequestBuilder request = get("/csrf").requestAttr(CsrfToken.class.getName(), csrfToken);
mockMvc.perform(request).andExpect(assertResult(csrfToken));
this.mockMvc.perform(request).andExpect(assertResult(csrfToken));
}
private ResultMatcher assertResult(Object expected) {

View File

@@ -35,12 +35,12 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Before
public void setup() {
registry = new ConcreteAbstractRequestMatcherMappingConfigurer();
this.registry = new ConcreteAbstractRequestMatcherMappingConfigurer();
}
@Test
public void testGetRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = registry.regexMatchers(HttpMethod.GET, "/a.*");
List<RequestMatcher> requestMatchers = this.registry.regexMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
@@ -49,7 +49,7 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = registry.regexMatchers("/a.*");
List<RequestMatcher> requestMatchers = this.registry.regexMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
@@ -58,7 +58,7 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testGetRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = registry.antMatchers(HttpMethod.GET, "/a.*");
List<RequestMatcher> requestMatchers = this.registry.antMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
@@ -67,7 +67,7 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = registry.antMatchers("/a.*");
List<RequestMatcher> requestMatchers = this.registry.antMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);

View File

@@ -118,7 +118,7 @@ public class ChannelSecurityConfigurerTests {
public void requiresChannelWhenInvokesTwiceThenUsesOriginalRequiresSecure() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class).autowire();
mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}
@EnableWebSecurity
@@ -141,7 +141,7 @@ public class ChannelSecurityConfigurerTests {
public void requestWhenRequiresChannelConfiguredInLambdaThenRedirectsToHttps() throws Exception {
this.spring.register(RequiresChannelInLambdaConfig.class).autowire();
mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}
@EnableWebSecurity

View File

@@ -41,8 +41,8 @@ public class CsrfConfigurerNoWebMvcTests {
@After
public void teardown() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -50,21 +50,21 @@ public class CsrfConfigurerNoWebMvcTests {
public void missingDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebConfig.class);
assertThat(context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void findDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebMvcConfig.class);
assertThat(context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void overrideCsrfRequestDataValueProcessor() {
loadContext(EnableWebOverrideRequestDataConfig.class);
assertThat(context.getBean(RequestDataValueProcessor.class).getClass())
assertThat(this.context.getBean(RequestDataValueProcessor.class).getClass())
.isNotEqualTo(CsrfRequestDataValueProcessor.class);
}

View File

@@ -55,15 +55,15 @@ public class HttpSecurityAntMatchersTests {
@Before
public void setup() {
request = new MockHttpServletRequest("GET", "");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
public void cleanup() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -71,11 +71,11 @@ public class HttpSecurityAntMatchersTests {
@Test
public void antMatchersMethodAndNoPatterns() throws Exception {
loadConfig(AntMatchersNoPatternsConfig.class);
request.setMethod("POST");
this.request.setMethod("POST");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@EnableWebSecurity
@@ -107,11 +107,11 @@ public class HttpSecurityAntMatchersTests {
@Test
public void antMatchersMethodAndEmptyPatterns() throws Exception {
loadConfig(AntMatchersEmptyPatternsConfig.class);
request.setMethod("POST");
this.request.setMethod("POST");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@EnableWebSecurity
@@ -141,11 +141,11 @@ public class HttpSecurityAntMatchersTests {
}
public void loadConfig(Class<?>... configs) {
context = new AnnotationConfigWebApplicationContext();
context.register(configs);
context.refresh();
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
context.getAutowireCapableBeanFactory().autowireBean(this);
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}
}

View File

@@ -56,15 +56,15 @@ public class HttpSecurityLogoutTests {
@Before
public void setup() {
request = new MockHttpServletRequest("GET", "");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
public void cleanup() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -76,12 +76,12 @@ public class HttpSecurityLogoutTests {
SecurityContext currentContext = SecurityContextHolder.createEmptyContext();
currentContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
currentContext);
request.setMethod("POST");
request.setServletPath("/logout");
this.request.setMethod("POST");
this.request.setServletPath("/logout");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(currentContext.getAuthentication()).isNotNull();
}
@@ -110,11 +110,11 @@ public class HttpSecurityLogoutTests {
}
public void loadConfig(Class<?>... configs) {
context = new AnnotationConfigWebApplicationContext();
context.register(configs);
context.refresh();
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
context.getAutowireCapableBeanFactory().autowireBean(this);
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}
}

View File

@@ -102,7 +102,7 @@ public class HttpSecurityRequestMatchersTests {
public void mvcMatcherGetFiltersNoUnsupportedMethodExceptionFromDummyRequest() {
loadConfig(MvcMatcherConfig.class);
assertThat(springSecurityFilterChain.getFilters("/path")).isNotEmpty();
assertThat(this.springSecurityFilterChain.getFilters("/path")).isNotEmpty();
}
@EnableWebSecurity

View File

@@ -82,7 +82,7 @@ public class RememberMeConfigurerTests {
public void postWhenNoUserDetailsServiceThenException() {
this.spring.register(NullUserDetailsConfig.class).autowire();
assertThatThrownBy(() -> mvc.perform(post("/login").param("username", "user").param("password", "password")
assertThatThrownBy(() -> this.mvc.perform(post("/login").param("username", "user").param("password", "password")
.param("remember-me", "true").with(csrf()))).hasMessageContaining("UserDetailsService is required");
}

View File

@@ -68,15 +68,15 @@ public class SessionManagementConfigurerServlet31Tests {
@Before
public void setup() {
request = new MockHttpServletRequest("GET", "");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
public void teardown() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -91,13 +91,13 @@ public class SessionManagementConfigurerServlet31Tests {
request.setParameter("password", "password");
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
CsrfToken token = repository.generateToken(request);
repository.saveToken(token, request, response);
repository.saveToken(token, request, this.response);
request.setParameter(token.getParameterName(), token.getToken());
request.getSession().setAttribute("attribute1", "value1");
loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(request, this.response, this.chain);
assertThat(request.getSession().getId()).isNotEqualTo(id);
assertThat(request.getSession().getAttribute("attribute1")).isEqualTo("value1");
@@ -137,7 +137,7 @@ public class SessionManagementConfigurerServlet31Tests {
private void login(Authentication auth) {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response);
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(this.request, this.response);
repo.loadContext(requestResponseHolder);
SecurityContextImpl securityContextImpl = new SecurityContextImpl();

View File

@@ -47,8 +47,9 @@ public class MessageSecurityMetadataSourceRegistryTests {
@Before
public void setup() {
messages = new MessageSecurityMetadataSourceRegistry();
message = MessageBuilder.withPayload("Hi").setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "location")
this.messages = new MessageSecurityMetadataSourceRegistry();
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "location")
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE).build();
}
@@ -57,85 +58,85 @@ public class MessageSecurityMetadataSourceRegistryTests {
// https://jira.spring.io/browse/SPR-11660
@Test
public void simpDestMatchersCustom() {
message = MessageBuilder.withPayload("Hi")
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.*").permitAll();
this.messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.*").permitAll();
assertThat(getAttribute()).isNull();
message = MessageBuilder.withPayload("Hi")
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.**").permitAll();
this.messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.**").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersCustomSetAfterMatchersDoesNotMatter() {
message = MessageBuilder.withPayload("Hi")
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
messages.simpDestMatchers("price.stock.*").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
this.messages.simpDestMatchers("price.stock.*").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isNull();
message = MessageBuilder.withPayload("Hi")
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
messages.simpDestMatchers("price.stock.**").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
this.messages.simpDestMatchers("price.stock.**").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test(expected = IllegalArgumentException.class)
public void pathMatcherNull() {
messages.simpDestPathMatcher(null);
this.messages.simpDestPathMatcher(null);
}
@Test
public void matchersFalse() {
messages.matchers(matcher).permitAll();
this.messages.matchers(this.matcher).permitAll();
assertThat(getAttribute()).isNull();
}
@Test
public void matchersTrue() {
when(matcher.matches(message)).thenReturn(true);
messages.matchers(matcher).permitAll();
when(this.matcher.matches(this.message)).thenReturn(true);
this.messages.matchers(this.matcher).permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersExact() {
messages.simpDestMatchers("location").permitAll();
this.messages.simpDestMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersMulti() {
messages.simpDestMatchers("admin/**", "api/**").hasRole("ADMIN").simpDestMatchers("location").permitAll();
this.messages.simpDestMatchers("admin/**", "api/**").hasRole("ADMIN").simpDestMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersRole() {
messages.simpDestMatchers("admin/**", "location/**").hasRole("ADMIN").anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").hasRole("ADMIN").anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasRole('ROLE_ADMIN')");
}
@Test
public void simpDestMatchersAnyRole() {
messages.simpDestMatchers("admin/**", "location/**").hasAnyRole("ADMIN", "ROOT").anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").hasAnyRole("ADMIN", "ROOT").anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyRole('ROLE_ADMIN','ROLE_ROOT')");
}
@Test
public void simpDestMatchersAuthority() {
messages.simpDestMatchers("admin/**", "location/**").hasAuthority("ROLE_ADMIN").anyMessage()
this.messages.simpDestMatchers("admin/**", "location/**").hasAuthority("ROLE_ADMIN").anyMessage()
.fullyAuthenticated();
assertThat(getAttribute()).isEqualTo("hasAuthority('ROLE_ADMIN')");
@@ -144,127 +145,128 @@ public class MessageSecurityMetadataSourceRegistryTests {
@Test
public void simpDestMatchersAccess() {
String expected = "hasRole('ROLE_ADMIN') and fullyAuthenticated";
messages.simpDestMatchers("admin/**", "location/**").access(expected).anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").access(expected).anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo(expected);
}
@Test
public void simpDestMatchersAnyAuthority() {
messages.simpDestMatchers("admin/**", "location/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_ROOT").anyMessage()
.denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_ROOT")
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyAuthority('ROLE_ADMIN','ROLE_ROOT')");
}
@Test
public void simpDestMatchersRememberMe() {
messages.simpDestMatchers("admin/**", "location/**").rememberMe().anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").rememberMe().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("rememberMe");
}
@Test
public void simpDestMatchersAnonymous() {
messages.simpDestMatchers("admin/**", "location/**").anonymous().anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").anonymous().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("anonymous");
}
@Test
public void simpDestMatchersFullyAuthenticated() {
messages.simpDestMatchers("admin/**", "location/**").fullyAuthenticated().anyMessage().denyAll();
this.messages.simpDestMatchers("admin/**", "location/**").fullyAuthenticated().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("fullyAuthenticated");
}
@Test
public void simpDestMatchersDenyAll() {
messages.simpDestMatchers("admin/**", "location/**").denyAll().anyMessage().permitAll();
this.messages.simpDestMatchers("admin/**", "location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpDestMessageMatchersNotMatch() {
messages.simpMessageDestMatchers("admin/**").denyAll().anyMessage().permitAll();
this.messages.simpMessageDestMatchers("admin/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMessageMatchersMatch() {
messages.simpMessageDestMatchers("location/**").denyAll().anyMessage().permitAll();
this.messages.simpMessageDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpDestSubscribeMatchersNotMatch() {
messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
this.messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestSubscribeMatchersMatch() {
message = MessageBuilder.fromMessage(message)
this.message = MessageBuilder.fromMessage(this.message)
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.SUBSCRIBE).build();
messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
this.messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void nullDestMatcherNotMatches() {
messages.nullDestMatcher().denyAll().anyMessage().permitAll();
this.messages.nullDestMatcher().denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void nullDestMatcherMatch() {
message = MessageBuilder.withPayload("Hi")
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.CONNECT).build();
messages.nullDestMatcher().denyAll().anyMessage().permitAll();
this.messages.nullDestMatcher().denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpTypeMatchersMatch() {
messages.simpTypeMatchers(SimpMessageType.MESSAGE).denyAll().anyMessage().permitAll();
this.messages.simpTypeMatchers(SimpMessageType.MESSAGE).denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpTypeMatchersMatchMulti() {
messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.MESSAGE).denyAll().anyMessage().permitAll();
this.messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.MESSAGE).denyAll().anyMessage()
.permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpTypeMatchersNotMatch() {
messages.simpTypeMatchers(SimpMessageType.CONNECT).denyAll().anyMessage().permitAll();
this.messages.simpTypeMatchers(SimpMessageType.CONNECT).denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpTypeMatchersNotMatchMulti() {
messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.DISCONNECT).denyAll().anyMessage()
this.messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.DISCONNECT).denyAll().anyMessage()
.permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
private String getAttribute() {
MessageSecurityMetadataSource source = messages.createMetadataSource();
Collection<ConfigAttribute> attrs = source.getAttributes(message);
MessageSecurityMetadataSource source = this.messages.createMetadataSource();
Collection<ConfigAttribute> attrs = source.getAttributes(this.message);
if (attrs == null) {
return null;
}

View File

@@ -381,7 +381,7 @@ public class EnableWebFluxSecurityTests {
}
public Child getChild() {
return child;
return this.child;
}
}

View File

@@ -61,15 +61,15 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
sessionAttr = "sessionAttr";
messageUser = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
this.token = new DefaultCsrfToken("header", "param", "token");
this.sessionAttr = "sessionAttr";
this.messageUser = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
}
@After
public void cleanup() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -89,15 +89,15 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
}
private void loadConfig(Class<?>... configs) {
context = new AnnotationConfigWebApplicationContext();
context.register(configs);
context.register(WebSocketConfig.class, SyncExecutorConfig.class);
context.setServletConfig(new MockServletConfig());
context.refresh();
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.register(WebSocketConfig.class, SyncExecutorConfig.class);
this.context.setServletConfig(new MockServletConfig());
this.context.refresh();
}
private MessageChannel clientInboundChannel() {
return context.getBean("clientInboundChannel", MessageChannel.class);
return this.context.getBean("clientInboundChannel", MessageChannel.class);
}
private Message<String> message(String destination, SimpMessageType type) {
@@ -111,8 +111,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
if (destination != null) {
headers.setDestination(destination);
}
if (messageUser != null) {
headers.setUser(messageUser);
if (this.messageUser != null) {
headers.setUser(this.messageUser);
}
return new GenericMessage<>("hi", headers.getMessageHeaders());
}

View File

@@ -91,15 +91,15 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
@Before
public void setup() {
token = new DefaultCsrfToken("header", "param", "token");
sessionAttr = "sessionAttr";
messageUser = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
this.token = new DefaultCsrfToken("header", "param", "token");
this.sessionAttr = "sessionAttr";
this.messageUser = new TestingAuthenticationToken("user", "pass", "ROLE_USER");
}
@After
public void cleanup() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -122,7 +122,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void annonymousSupported() {
loadConfig(SockJsSecurityConfig.class);
messageUser = null;
this.messageUser = null;
clientInboundChannel().send(message("/permitAll"));
}
@@ -131,7 +131,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void beanResolver() {
loadConfig(SockJsSecurityConfig.class);
messageUser = null;
this.messageUser = null;
clientInboundChannel().send(message("/beanResolver"));
}
@@ -143,8 +143,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
Message<String> message = message("/permitAll/authentication");
messageChannel.send(message);
assertThat(context.getBean(MyController.class).authenticationPrincipal)
.isEqualTo((String) messageUser.getPrincipal());
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
.isEqualTo((String) this.messageUser.getPrincipal());
}
@Test
@@ -155,8 +155,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
Message<String> message = message("/permitAll/authentication");
messageChannel.send(message);
assertThat(context.getBean(MyController.class).authenticationPrincipal)
.isEqualTo((String) messageUser.getPrincipal());
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
.isEqualTo((String) this.messageUser.getPrincipal());
}
@Test
@@ -209,7 +209,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(SockJsProxylessSecurityConfig.class);
MessageChannel messageChannel = clientInboundChannel();
CsrfChannelInterceptor csrfChannelInterceptor = context.getBean(CsrfChannelInterceptor.class);
CsrfChannelInterceptor csrfChannelInterceptor = this.context.getBean(CsrfChannelInterceptor.class);
assertThat(((AbstractMessageChannel) messageChannel).getInterceptors()).contains(csrfChannelInterceptor);
}
@@ -432,8 +432,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(SockJsProxylessSecurityConfig.class);
ChannelSecurityInterceptor channelSecurityInterceptor = context.getBean(ChannelSecurityInterceptor.class);
MessageSecurityMetadataSource messageSecurityMetadataSource = context
ChannelSecurityInterceptor channelSecurityInterceptor = this.context.getBean(ChannelSecurityInterceptor.class);
MessageSecurityMetadataSource messageSecurityMetadataSource = this.context
.getBean(MessageSecurityMetadataSource.class);
assertThat(channelSecurityInterceptor.obtainSecurityMetadataSource()).isSameAs(messageSecurityMetadataSource);
@@ -444,7 +444,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(SockJsProxylessSecurityConfig.class);
MessageChannel messageChannel = clientInboundChannel();
SecurityContextChannelInterceptor securityContextChannelInterceptor = context
SecurityContextChannelInterceptor securityContextChannelInterceptor = this.context
.getBean(SecurityContextChannelInterceptor.class);
assertThat(((AbstractMessageChannel) messageChannel).getInterceptors())
@@ -456,7 +456,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(SockJsProxylessSecurityConfig.class);
MessageChannel messageChannel = clientInboundChannel();
ChannelSecurityInterceptor inboundChannelSecurity = context.getBean(ChannelSecurityInterceptor.class);
ChannelSecurityInterceptor inboundChannelSecurity = this.context.getBean(ChannelSecurityInterceptor.class);
assertThat(((AbstractMessageChannel) messageChannel).getInterceptors()).contains(inboundChannelSecurity);
}
@@ -512,14 +512,14 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
}
private void assertHandshake(HttpServletRequest request) {
TestHandshakeHandler handshakeHandler = context.getBean(TestHandshakeHandler.class);
assertThat(handshakeHandler.attributes.get(CsrfToken.class.getName())).isSameAs(token);
assertThat(handshakeHandler.attributes.get(sessionAttr))
.isEqualTo(request.getSession().getAttribute(sessionAttr));
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
assertThat(handshakeHandler.attributes.get(CsrfToken.class.getName())).isSameAs(this.token);
assertThat(handshakeHandler.attributes.get(this.sessionAttr))
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
}
private HttpRequestHandler handler(HttpServletRequest request) throws Exception {
HandlerMapping handlerMapping = context.getBean(HandlerMapping.class);
HandlerMapping handlerMapping = this.context.getBean(HandlerMapping.class);
return (HttpRequestHandler) handlerMapping.getHandler(request).getHandler();
}
@@ -534,9 +534,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
request.setMethod("GET");
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/289/tpyx6mde/websocket");
request.setRequestURI(mapping + "/289/tpyx6mde/websocket");
request.getSession().setAttribute(sessionAttr, "sessionValue");
request.getSession().setAttribute(this.sessionAttr, "sessionValue");
request.setAttribute(CsrfToken.class.getName(), token);
request.setAttribute(CsrfToken.class.getName(), this.token);
return request;
}
@@ -551,21 +551,21 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
if (destination != null) {
headers.setDestination(destination);
}
if (messageUser != null) {
headers.setUser(messageUser);
if (this.messageUser != null) {
headers.setUser(this.messageUser);
}
return new GenericMessage<>("hi", headers.getMessageHeaders());
}
private MessageChannel clientInboundChannel() {
return context.getBean("clientInboundChannel", MessageChannel.class);
return this.context.getBean("clientInboundChannel", MessageChannel.class);
}
private void loadConfig(Class<?>... configs) {
context = new AnnotationConfigWebApplicationContext();
context.register(configs);
context.setServletConfig(new MockServletConfig());
context.refresh();
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.setServletConfig(new MockServletConfig());
this.context.refresh();
}
@Controller
@@ -674,8 +674,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
private boolean check;
public boolean check() {
check = !check;
return check;
this.check = !this.check;
return this.check;
}
}
@@ -755,8 +755,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
private ApplicationContext context;
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setHandshakeHandler(context.getBean(TestHandshakeHandler.class)).withSockJS()
.setInterceptors(new HttpSessionHandshakeInterceptor());
registry.addEndpoint("/chat").setHandshakeHandler(this.context.getBean(TestHandshakeHandler.class))
.withSockJS().setInterceptors(new HttpSessionHandshakeInterceptor());
}
@Autowired

View File

@@ -43,8 +43,8 @@ public class AuthenticationProviderBeanDefinitionParserTests {
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
}
@@ -53,17 +53,17 @@ public class AuthenticationProviderBeanDefinitionParserTests {
setContext(" <authentication-provider>" + " <user-service>"
+ " <user name='bob' password='{noop}bobspassword' authorities='ROLE_A' />"
+ " </user-service>" + " </authentication-provider>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
@Test
public void externalUserServiceRefWorks() {
appContext = new InMemoryXmlApplicationContext(
this.appContext = new InMemoryXmlApplicationContext(
" <authentication-manager>" + " <authentication-provider user-service-ref='myUserService' />"
+ " </authentication-manager>" + " <user-service id='myUserService'>"
+ " <user name='bob' password='{noop}bobspassword' authorities='ROLE_A' />"
+ " </user-service>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
@Test
@@ -72,35 +72,35 @@ public class AuthenticationProviderBeanDefinitionParserTests {
+ " <user name='bob' password='$2a$05$dRmjl1T05J7rvCPD2NgsHesCEJHww3pdmesUhjM3PD4m/gaEYyx/G' authorities='ROLE_A' />"
+ " </user-service>" + " </authentication-provider>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
@Test
public void providerWithMd5PasswordEncoderWorks() {
appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
+ " <password-encoder ref='passwordEncoder'/>" + " <user-service>"
+ " <user name='bob' password='12b141f35d58b8b3a46eea65e6ac179e' authorities='ROLE_A' />"
+ " </user-service>" + " </authentication-provider>" + " </authentication-manager>"
+ " <b:bean id='passwordEncoder' class='" + MessageDigestPasswordEncoder.class.getName() + "'>"
+ " <b:constructor-arg value='MD5'/>" + " </b:bean>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
@Test
public void providerWithShaPasswordEncoderWorks() {
appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
+ " <password-encoder ref='passwordEncoder'/>" + " <user-service>"
+ " <user name='bob' password='{SSHA}PpuEwfdj7M1rs0C2W4ssSM2XEN/Y6S5U' authorities='ROLE_A' />"
+ " </user-service>" + " </authentication-provider>" + " </authentication-manager>"
+ " <b:bean id='passwordEncoder' class='" + LdapShaPasswordEncoder.class.getName() + "'/>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
@Test
public void passwordIsBase64EncodedWhenBase64IsEnabled() {
appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>" + " <authentication-provider>"
+ " <password-encoder ref='passwordEncoder'/>" + " <user-service>"
+ " <user name='bob' password='ErFB811YuLOkbupl5qwXng==' authorities='ROLE_A' />"
+ " </user-service>" + " </authentication-provider>" + " </authentication-manager>"
@@ -108,13 +108,13 @@ public class AuthenticationProviderBeanDefinitionParserTests {
+ " <b:constructor-arg value='MD5'/>" + " <b:property name='encodeHashAsBase64' value='true'/>"
+ " </b:bean>");
getProvider().authenticate(bob);
getProvider().authenticate(this.bob);
}
// SEC-1466
@Test(expected = BeanDefinitionParsingException.class)
public void exernalProviderDoesNotSupportChildElements() {
appContext = new InMemoryXmlApplicationContext(" <authentication-manager>"
this.appContext = new InMemoryXmlApplicationContext(" <authentication-manager>"
+ " <authentication-provider ref='aProvider'> "
+ " <password-encoder ref='customPasswordEncoder'/>" + " </authentication-provider>"
+ " </authentication-manager>"
@@ -124,14 +124,14 @@ public class AuthenticationProviderBeanDefinitionParserTests {
}
private AuthenticationProvider getProvider() {
List<AuthenticationProvider> providers = ((ProviderManager) appContext.getBean(BeanIds.AUTHENTICATION_MANAGER))
.getProviders();
List<AuthenticationProvider> providers = ((ProviderManager) this.appContext
.getBean(BeanIds.AUTHENTICATION_MANAGER)).getProviders();
return providers.get(0);
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(
this.appContext = new InMemoryXmlApplicationContext(
"<authentication-manager>" + context + "</authentication-manager>");
}

View File

@@ -53,8 +53,8 @@ public class JdbcUserServiceBeanDefinitionParserTests {
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
}
@@ -67,14 +67,14 @@ public class JdbcUserServiceBeanDefinitionParserTests {
@Test
public void validUsernameIsFound() {
setContext("<jdbc-user-service data-source-ref='dataSource'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext.getBean(BeanIds.USER_DETAILS_SERVICE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) this.appContext.getBean(BeanIds.USER_DETAILS_SERVICE);
assertThat(mgr.loadUserByUsername("rod")).isNotNull();
}
@Test
public void beanIdIsParsedCorrectly() {
setContext("<jdbc-user-service id='myUserService' data-source-ref='dataSource'/>" + DATA_SOURCE);
assertThat(appContext.getBean("myUserService") instanceof JdbcUserDetailsManager).isTrue();
assertThat(this.appContext.getBean("myUserService") instanceof JdbcUserDetailsManager).isTrue();
}
@Test
@@ -84,7 +84,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
setContext("<jdbc-user-service id='myUserService' " + "data-source-ref='dataSource' "
+ "users-by-username-query='" + userQuery + "' " + "authorities-by-username-query='" + authoritiesQuery
+ "'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext.getBean("myUserService");
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) this.appContext.getBean("myUserService");
assertThat(FieldUtils.getFieldValue(mgr, "usersByUsernameQuery")).isEqualTo(userQuery);
assertThat(FieldUtils.getFieldValue(mgr, "authoritiesByUsernameQuery")).isEqualTo(authoritiesQuery);
assertThat(mgr.loadUserByUsername("rod") != null).isTrue();
@@ -94,7 +94,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
public void groupQueryIsParsedCorrectly() throws Exception {
setContext("<jdbc-user-service id='myUserService' " + "data-source-ref='dataSource' "
+ "group-authorities-by-username-query='blah blah'/>" + DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext.getBean("myUserService");
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) this.appContext.getBean("myUserService");
assertThat(FieldUtils.getFieldValue(mgr, "groupAuthoritiesByUsernameQuery")).isEqualTo("blah blah");
assertThat((Boolean) FieldUtils.getFieldValue(mgr, "enableGroups")).isTrue();
}
@@ -103,9 +103,9 @@ public class JdbcUserServiceBeanDefinitionParserTests {
public void cacheRefIsparsedCorrectly() {
setContext("<jdbc-user-service id='myUserService' cache-ref='userCache' data-source-ref='dataSource'/>"
+ DATA_SOURCE + USER_CACHE_XML);
CachingUserDetailsService cachingUserService = (CachingUserDetailsService) appContext
CachingUserDetailsService cachingUserService = (CachingUserDetailsService) this.appContext
.getBean("myUserService" + AbstractUserDetailsServiceBeanDefinitionParser.CACHING_SUFFIX);
assertThat(appContext.getBean("userCache")).isSameAs(cachingUserService.getUserCache());
assertThat(this.appContext.getBean("userCache")).isSameAs(cachingUserService.getUserCache());
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
}
@@ -115,7 +115,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
setContext("<authentication-manager>" + " <authentication-provider>"
+ " <jdbc-user-service data-source-ref='dataSource'/>" + " </authentication-provider>"
+ "</authentication-manager>" + DATA_SOURCE);
AuthenticationManager mgr = (AuthenticationManager) appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
AuthenticationManager mgr = (AuthenticationManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
mgr.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala"));
}
@@ -124,9 +124,9 @@ public class JdbcUserServiceBeanDefinitionParserTests {
setContext("<authentication-manager>" + " <authentication-provider>"
+ " <jdbc-user-service cache-ref='userCache' data-source-ref='dataSource'/>"
+ " </authentication-provider>" + "</authentication-manager>" + DATA_SOURCE + USER_CACHE_XML);
ProviderManager mgr = (ProviderManager) appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
ProviderManager mgr = (ProviderManager) this.appContext.getBean(BeanIds.AUTHENTICATION_MANAGER);
DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr.getProviders().get(0);
assertThat(appContext.getBean("userCache")).isSameAs(provider.getUserCache());
assertThat(this.appContext.getBean("userCache")).isSameAs(provider.getUserCache());
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala"));
assertThat(provider.getUserCache().getUserFromCache("rod")).isNotNull()
.withFailMessage("Cache should contain user after authentication");
@@ -136,13 +136,13 @@ public class JdbcUserServiceBeanDefinitionParserTests {
public void rolePrefixIsUsedWhenSet() {
setContext("<jdbc-user-service id='myUserService' role-prefix='PREFIX_' data-source-ref='dataSource'/>"
+ DATA_SOURCE);
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) appContext.getBean("myUserService");
JdbcUserDetailsManager mgr = (JdbcUserDetailsManager) this.appContext.getBean("myUserService");
UserDetails rod = mgr.loadUserByUsername("rod");
assertThat(AuthorityUtils.authorityListToSet(rod.getAuthorities())).contains("PREFIX_ROLE_SUPERVISOR");
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
this.appContext = new InMemoryXmlApplicationContext(context);
}
}

View File

@@ -35,8 +35,8 @@ public class UserServiceBeanDefinitionParserTests {
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
}
@@ -44,7 +44,7 @@ public class UserServiceBeanDefinitionParserTests {
public void userServiceWithValidPropertiesFileWorksSuccessfully() {
setContext("<user-service id='service' "
+ "properties='classpath:org/springframework/security/config/users.properties'/>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
userService.loadUserByUsername("bob");
userService.loadUserByUsername("joe");
}
@@ -53,7 +53,7 @@ public class UserServiceBeanDefinitionParserTests {
public void userServiceWithEmbeddedUsersWorksSuccessfully() {
setContext("<user-service id='service'>" + " <user name='joe' password='joespassword' authorities='ROLE_A'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
userService.loadUserByUsername("joe");
}
@@ -66,7 +66,7 @@ public class UserServiceBeanDefinitionParserTests {
+ "<user-service id='service'>"
+ " <user name='${principal.name}' password='${principal.pass}' authorities='${principal.authorities}'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertThat(joe.getPassword()).isEqualTo("joespassword");
assertThat(joe.getAuthorities()).hasSize(2);
@@ -75,7 +75,7 @@ public class UserServiceBeanDefinitionParserTests {
@Test
public void embeddedUsersWithNoPasswordIsGivenGeneratedValue() {
setContext("<user-service id='service'>" + " <user name='joe' authorities='ROLE_A'/>" + "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertThat(joe.getPassword().length() > 0).isTrue();
Long.parseLong(joe.getPassword());
@@ -86,7 +86,7 @@ public class UserServiceBeanDefinitionParserTests {
setContext("<user-service id='service'>" + " <user name='https://joe.myopenid.com/' authorities='ROLE_A'/>"
+ " <user name='https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9' authorities='ROLE_A'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
assertThat(userService.loadUserByUsername("https://joe.myopenid.com/").getUsername())
.isEqualTo("https://joe.myopenid.com/");
assertThat(userService.loadUserByUsername("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9")
@@ -99,7 +99,7 @@ public class UserServiceBeanDefinitionParserTests {
+ " <user name='joe' password='joespassword' authorities='ROLE_A' locked='true'/>"
+ " <user name='Bob' password='bobspassword' authorities='ROLE_A' disabled='true'/>"
+ "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
UserDetails joe = userService.loadUserByUsername("joe");
assertThat(joe.isAccountNonLocked()).isFalse();
// Check case-sensitive lookup SEC-1432
@@ -111,7 +111,7 @@ public class UserServiceBeanDefinitionParserTests {
public void userWithBothPropertiesAndEmbeddedUsersThrowsException() {
setContext("<user-service id='service' properties='doesntmatter.props'>"
+ " <user name='joe' password='joespassword' authorities='ROLE_A'/>" + "</user-service>");
UserDetailsService userService = (UserDetailsService) appContext.getBean("service");
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
userService.loadUserByUsername("Joe");
}
@@ -128,7 +128,7 @@ public class UserServiceBeanDefinitionParserTests {
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
this.appContext = new InMemoryXmlApplicationContext(context);
}
}

View File

@@ -70,10 +70,10 @@ public class GrantedAuthorityDefaultsJcTests {
public void setup() {
setup("USER");
request = new MockHttpServletRequest("GET", "");
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.request.setMethod("GET");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
@@ -84,11 +84,12 @@ public class GrantedAuthorityDefaultsJcTests {
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
@@ -96,44 +97,46 @@ public class GrantedAuthorityDefaultsJcTests {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
this.messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
this.messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
this.messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
this.messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
chain = new MockFilterChain() {
this.chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
@@ -146,9 +149,9 @@ public class GrantedAuthorityDefaultsJcTests {
};
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(chain.getRequest()).isNotNull();
assertThat(this.chain.getRequest()).isNotNull();
}
private void setup(String role) {

View File

@@ -63,10 +63,10 @@ public class GrantedAuthorityDefaultsXmlTests {
public void setup() {
setup("USER");
request = new MockHttpServletRequest("GET", "");
request.setMethod("GET");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.request.setMethod("GET");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
@@ -77,11 +77,12 @@ public class GrantedAuthorityDefaultsXmlTests {
@Test
public void doFilter() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
@@ -89,44 +90,46 @@ public class GrantedAuthorityDefaultsXmlTests {
setup("DENIED");
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void message() {
messageService.getMessage();
this.messageService.getMessage();
}
@Test
public void jsrMessage() {
messageService.getJsrMessage();
this.messageService.getJsrMessage();
}
@Test(expected = AccessDeniedException.class)
public void messageDenied() {
setup("DENIED");
messageService.getMessage();
this.messageService.getMessage();
}
@Test(expected = AccessDeniedException.class)
public void jsrMessageDenied() {
setup("DENIED");
messageService.getJsrMessage();
this.messageService.getJsrMessage();
}
// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
context);
chain = new MockFilterChain() {
this.chain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
@@ -139,9 +142,9 @@ public class GrantedAuthorityDefaultsXmlTests {
};
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(chain.getRequest()).isNotNull();
assertThat(this.chain.getRequest()).isNotNull();
}
private void setup(String role) {

View File

@@ -40,7 +40,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceITes
@Test
public void loadUserByUsernameWhenUserFoundThenNotNull() {
assertThat(users.findByUsername("user").block()).isNotNull();
assertThat(this.users.findByUsername("user").block()).isNotNull();
}
@Configuration

View File

@@ -39,7 +39,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceLoca
@Test
public void loadUserByUsernameWhenUserFoundThenNotNull() {
assertThat(users.findByUsername("user").block()).isNotNull();
assertThat(this.users.findByUsername("user").block()).isNotNull();
}
@Configuration

View File

@@ -39,7 +39,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBeanStringITests {
@Test
public void findByUsernameWhenUserFoundThenNotNull() {
assertThat(users.findByUsername("user").block()).isNotNull();
assertThat(this.users.findByUsername("user").block()).isNotNull();
}
@Configuration

View File

@@ -45,39 +45,39 @@ public class UserDetailsResourceFactoryBeanTests {
@Test
public void setResourceLoaderWhenNullThenThrowsException() {
assertThatThrownBy(() -> factory.setResourceLoader(null)).isInstanceOf(IllegalArgumentException.class)
assertThatThrownBy(() -> this.factory.setResourceLoader(null)).isInstanceOf(IllegalArgumentException.class)
.hasStackTraceContaining("resourceLoader cannot be null");
}
@Test
public void getObjectWhenPropertiesResourceLocationNullThenThrowsIllegalStateException() {
factory.setResourceLoader(resourceLoader);
this.factory.setResourceLoader(this.resourceLoader);
assertThatThrownBy(() -> factory.getObject()).isInstanceOf(IllegalArgumentException.class)
assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalArgumentException.class)
.hasStackTraceContaining("resource cannot be null if resourceLocation is null");
}
@Test
public void getObjectWhenPropertiesResourceLocationSingleUserThenThrowsGetsSingleUser() throws Exception {
factory.setResourceLocation("classpath:users.properties");
this.factory.setResourceLocation("classpath:users.properties");
Collection<UserDetails> users = factory.getObject();
Collection<UserDetails> users = this.factory.getObject();
assertLoaded();
}
@Test
public void getObjectWhenPropertiesResourceSingleUserThenThrowsGetsSingleUser() throws Exception {
factory.setResource(new InMemoryResource("user=password,ROLE_USER"));
this.factory.setResource(new InMemoryResource("user=password,ROLE_USER"));
assertLoaded();
}
@Test
public void getObjectWhenInvalidUserThenThrowsMeaningfulException() {
factory.setResource(new InMemoryResource("user=invalidFormatHere"));
this.factory.setResource(new InMemoryResource("user=invalidFormatHere"));
assertThatThrownBy(() -> factory.getObject()).isInstanceOf(IllegalStateException.class)
assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalStateException.class)
.hasStackTraceContaining("user").hasStackTraceContaining("invalidFormatHere");
}
@@ -89,7 +89,7 @@ public class UserDetailsResourceFactoryBeanTests {
}
private void assertLoaded() throws Exception {
Collection<UserDetails> users = factory.getObject();
Collection<UserDetails> users = this.factory.getObject();
// @formatter:off
UserDetails expectedUser = User.withUsername("user")
.password("password")

View File

@@ -68,17 +68,17 @@ public class DefaultFilterChainValidatorTests {
@Before
public void setUp() {
AnonymousAuthenticationFilter aaf = new AnonymousAuthenticationFilter("anonymous");
fsi = new FilterSecurityInterceptor();
fsi.setAccessDecisionManager(accessDecisionManager);
fsi.setSecurityMetadataSource(metadataSource);
this.fsi = new FilterSecurityInterceptor();
this.fsi.setAccessDecisionManager(this.accessDecisionManager);
this.fsi.setSecurityMetadataSource(this.metadataSource);
AuthenticationEntryPoint authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint("/login");
ExceptionTranslationFilter etf = new ExceptionTranslationFilter(authenticationEntryPoint);
DefaultSecurityFilterChain securityChain = new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE, aaf, etf,
fsi);
fcp = new FilterChainProxy(securityChain);
validator = new DefaultFilterChainValidator();
this.fsi);
this.fcp = new FilterChainProxy(securityChain);
this.validator = new DefaultFilterChainValidator();
ReflectionTestUtils.setField(validator, "logger", logger);
ReflectionTestUtils.setField(this.validator, "logger", this.logger);
}
// SEC-1878
@@ -86,10 +86,10 @@ public class DefaultFilterChainValidatorTests {
@Test
public void validateCheckLoginPageIsntProtectedThrowsIllegalArgumentException() {
IllegalArgumentException toBeThrown = new IllegalArgumentException("failed to eval expression");
doThrow(toBeThrown).when(accessDecisionManager).decide(any(Authentication.class), anyObject(),
doThrow(toBeThrown).when(this.accessDecisionManager).decide(any(Authentication.class), anyObject(),
any(Collection.class));
validator.validate(fcp);
verify(logger).info(
this.validator.validate(this.fcp);
verify(this.logger).info(
"Unable to check access to the login page to determine if anonymous access is allowed. This might be an error, but can happen under normal circumstances.",
toBeThrown);
}
@@ -99,9 +99,9 @@ public class DefaultFilterChainValidatorTests {
public void validateCustomMetadataSource() {
FilterInvocationSecurityMetadataSource customMetaDataSource = mock(
FilterInvocationSecurityMetadataSource.class);
fsi.setSecurityMetadataSource(customMetaDataSource);
this.fsi.setSecurityMetadataSource(customMetaDataSource);
validator.validate(fcp);
this.validator.validate(this.fcp);
verify(customMetaDataSource).getAttributes(any());
}

View File

@@ -39,8 +39,8 @@ public class HttpInterceptUrlTests {
@After
public void close() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -48,11 +48,11 @@ public class HttpInterceptUrlTests {
public void interceptUrlWhenRequestMatcherRefThenWorks() throws Exception {
loadConfig("interceptUrlWhenRequestMatcherRefThenWorks.xml");
mockMvc.perform(get("/foo")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/foo")).andExpect(status().isUnauthorized());
mockMvc.perform(get("/FOO")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/FOO")).andExpect(status().isUnauthorized());
mockMvc.perform(get("/other")).andExpect(status().isOk());
this.mockMvc.perform(get("/other")).andExpect(status().isOk());
}
private void loadConfig(String... configLocations) {
@@ -68,7 +68,8 @@ public class HttpInterceptUrlTests {
context.getAutowireCapableBeanFactory().autowireBean(this);
Filter springSecurityFilterChain = context.getBean("springSecurityFilterChain", Filter.class);
mockMvc = MockMvcBuilders.standaloneSetup(new FooController()).addFilters(springSecurityFilterChain).build();
this.mockMvc = MockMvcBuilders.standaloneSetup(new FooController()).addFilters(springSecurityFilterChain)
.build();
}
@RestController

View File

@@ -161,7 +161,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/")).andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("http://localhost/oauth2/authorization/google-login"));
verify(requestCache).saveRequest(any(), any());
verify(this.requestCache).saveRequest(any(), any());
}
// gh-5347
@@ -196,7 +196,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
ArgumentCaptor<AuthenticationException> exceptionCaptor = ArgumentCaptor
.forClass(AuthenticationException.class);
verify(authenticationFailureHandler).onAuthenticationFailure(any(), any(), exceptionCaptor.capture());
verify(this.authenticationFailureHandler).onAuthenticationFailure(any(), any(), exceptionCaptor.capture());
AuthenticationException exception = exceptionCaptor.getValue();
assertThat(exception).isInstanceOf(OAuth2AuthenticationException.class);
assertThat(((OAuth2AuthenticationException) exception).getError().getErrorCode())
@@ -226,7 +226,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
Authentication authentication = authenticationCaptor.getValue();
assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
}
@@ -254,7 +254,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
params.add("state", authorizationRequest.getState());
this.mvc.perform(get("/login/oauth2/code/github-login").params(params));
verify(authenticationSuccessListener).onApplicationEvent(any(AuthenticationSuccessEvent.class));
verify(this.authenticationSuccessListener).onApplicationEvent(any(AuthenticationSuccessEvent.class));
}
@Test
@@ -312,7 +312,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
Authentication authentication = authenticationCaptor.getValue();
assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
assertThat(authentication.getAuthorities()).hasSize(1);
@@ -338,7 +338,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/login/oauth2/code/google-login").params(params)).andExpect(status().is2xxSuccessful());
authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(authenticationSuccessHandler, times(2)).onAuthenticationSuccess(any(), any(),
verify(this.authenticationSuccessHandler, times(2)).onAuthenticationSuccess(any(), any(),
authenticationCaptor.capture());
authentication = authenticationCaptor.getValue();
assertThat(authentication.getPrincipal()).isInstanceOf(OidcUser.class);
@@ -371,7 +371,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/login/oauth2/github-login").params(params)).andExpect(status().is2xxSuccessful());
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
Authentication authentication = authenticationCaptor.getValue();
assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
}
@@ -384,7 +384,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
this.mvc.perform(get("/oauth2/authorization/google-login")).andExpect(status().is3xxRedirection());
verify(authorizationRequestResolver).resolve(any());
verify(this.authorizationRequestResolver).resolve(any());
}
// gh-5347
@@ -439,7 +439,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
params.add("state", authorizationRequest.getState());
this.mvc.perform(get("/login/oauth2/code/" + clientRegistration.getRegistrationId()).params(params));
verify(clientRegistrationRepository).findByRegistrationId(clientRegistration.getRegistrationId());
verify(this.clientRegistrationRepository).findByRegistrationId(clientRegistration.getRegistrationId());
}
@Test
@@ -467,7 +467,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
params.add("state", authorizationRequest.getState());
this.mvc.perform(get("/login/oauth2/code/" + clientRegistration.getRegistrationId()).params(params));
verify(authorizedClientRepository).saveAuthorizedClient(any(), any(), any(), any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(), any(), any());
}
@Test
@@ -495,7 +495,7 @@ public class OAuth2LoginBeanDefinitionParserTests {
params.add("state", authorizationRequest.getState());
this.mvc.perform(get("/login/oauth2/code/" + clientRegistration.getRegistrationId()).params(params));
verify(authorizedClientService).saveAuthorizedClient(any(), any());
verify(this.authorizedClientService).saveAuthorizedClient(any(), any());
}
@WithMockUser

View File

@@ -69,15 +69,15 @@ public class SessionManagementConfigServlet31Tests {
@Before
public void setup() {
request = new MockHttpServletRequest("GET", "");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}
@After
public void teardown() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -97,7 +97,7 @@ public class SessionManagementConfigServlet31Tests {
loadContext("<http>\n" + " <form-login/>\n" + " <session-management/>\n"
+ " <csrf disabled='true'/>\n" + " </http>" + XML_AUTHENTICATION_MANAGER);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(request, this.response, this.chain);
assertThat(request.getSession().getId()).isNotEqualTo(id);
assertThat(request.getSession().getAttribute("attribute1")).isEqualTo("value1");
@@ -119,7 +119,7 @@ public class SessionManagementConfigServlet31Tests {
+ " <session-management session-fixation-protection='changeSessionId'/>\n"
+ " <csrf disabled='true'/>\n" + " </http>" + XML_AUTHENTICATION_MANAGER);
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(request, this.response, this.chain);
assertThat(request.getSession().getId()).isNotEqualTo(id);
@@ -132,7 +132,7 @@ public class SessionManagementConfigServlet31Tests {
private void login(Authentication auth) {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response);
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(this.request, this.response);
repo.loadContext(requestResponseHolder);
SecurityContextImpl securityContextImpl = new SecurityContextImpl();

View File

@@ -38,8 +38,8 @@ public class WebConfigUtilsTests {
@Test
public void validateHttpRedirectSpELNoParserWarning() {
WebConfigUtils.validateHttpRedirect("#{T(org.springframework.security.config.http.WebConfigUtilsTest).URL}",
parserContext, "fakeSource");
verifyZeroInteractions(parserContext);
this.parserContext, "fakeSource");
verifyZeroInteractions(this.parserContext);
}
}

View File

@@ -49,7 +49,7 @@ public class CustomConfigurer extends SecurityConfigurerAdapter<DefaultSecurityF
// @formatter:off
http
.authorizeRequests()
.antMatchers(permitAllPattern).permitAll()
.antMatchers(this.permitAllPattern).permitAll()
.anyRequest().authenticated();
// @formatter:on
if (http.getConfigurer(FormLoginConfigurer.class) == null) {
@@ -57,7 +57,7 @@ public class CustomConfigurer extends SecurityConfigurerAdapter<DefaultSecurityF
// @formatter:off
http
.formLogin()
.loginPage(loginPage);
.loginPage(this.loginPage);
// @formatter:on
}
}

View File

@@ -59,16 +59,16 @@ public class CustomHttpSecurityConfigurerTests {
@Before
public void setup() {
request = new MockHttpServletRequest("GET", "");
response = new MockHttpServletResponse();
chain = new MockFilterChain();
request.setMethod("GET");
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
this.request.setMethod("GET");
}
@After
public void cleanup() {
if (context != null) {
context.close();
if (this.context != null) {
this.context.close();
}
}
@@ -76,42 +76,42 @@ public class CustomHttpSecurityConfigurerTests {
public void customConfiguerPermitAll() throws Exception {
loadContext(Config.class);
request.setPathInfo("/public/something");
this.request.setPathInfo("/public/something");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void customConfiguerFormLogin() throws Exception {
loadContext(Config.class);
request.setPathInfo("/requires-authentication");
this.request.setPathInfo("/requires-authentication");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getRedirectedUrl()).endsWith("/custom");
assertThat(this.response.getRedirectedUrl()).endsWith("/custom");
}
@Test
public void customConfiguerCustomizeDisablesCsrf() throws Exception {
loadContext(ConfigCustomize.class);
request.setPathInfo("/public/something");
request.setMethod("POST");
this.request.setPathInfo("/public/something");
this.request.setMethod("POST");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void customConfiguerCustomizeFormLogin() throws Exception {
loadContext(ConfigCustomize.class);
request.setPathInfo("/requires-authentication");
this.request.setPathInfo("/requires-authentication");
springSecurityFilterChain.doFilter(request, response, chain);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(response.getRedirectedUrl()).endsWith("/other");
assertThat(this.response.getRedirectedUrl()).endsWith("/other");
}
private void loadContext(Class<?> clazz) {

View File

@@ -34,7 +34,7 @@ public class Contact {
* @return the name
*/
public String getName() {
return name;
return this.name;
}
}

View File

@@ -80,24 +80,24 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ " <protect-pointcut expression='execution(* *.someUser*(..))' access='ROLE_USER'/>"
+ " <protect-pointcut expression='execution(* *.someAdmin*(..))' access='ROLE_ADMIN'/>"
+ "</global-method-security>" + ConfigTestUtils.AUTH_PROVIDER_XML);
target = (BusinessService) appContext.getBean("target");
this.target = (BusinessService) this.appContext.getBean("target");
}
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
appContext = null;
if (this.appContext != null) {
this.appContext.close();
this.appContext = null;
}
SecurityContextHolder.clearContext();
target = null;
this.target = null;
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
loadContext();
target.someUserMethod1();
this.target.someUserMethod1();
}
@Test
@@ -106,10 +106,10 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
SecurityContextHolder.getContext().setAuthentication(token);
target.someUserMethod1();
this.target.someUserMethod1();
// SEC-1213. Check the order
Advisor[] advisors = ((Advised) target).getAdvisors();
Advisor[] advisors = ((Advised) this.target).getAdvisors();
assertThat(advisors).hasSize(1);
assertThat(((MethodSecurityMetadataSourceAdvisor) advisors[0]).getOrder()).isEqualTo(1001);
}
@@ -122,7 +122,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
SecurityContextHolder.getContext().setAuthentication(token);
target.someAdminMethod();
this.target.someAdminMethod();
}
@Test
@@ -133,7 +133,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ " <authentication-provider user-service-ref='myUserService'/>" + "</authentication-manager>"
+ "<b:bean id='beanPostProcessor' class='org.springframework.security.config.MockUserServiceBeanPostProcessor'/>");
PostProcessedMockUserDetailsService service = (PostProcessedMockUserDetailsService) appContext
PostProcessedMockUserDetailsService service = (PostProcessedMockUserDetailsService) this.appContext
.getBean("myUserService");
assertThat(service.getPostProcessorWasHere()).isEqualTo("Hello from the post processor!");
@@ -148,7 +148,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "<aop:aspectj-autoproxy />" + "<authentication-manager>"
+ " <authentication-provider user-service-ref='myUserService'/>" + "</authentication-manager>");
UserDetailsService service = (UserDetailsService) appContext.getBean("myUserService");
UserDetailsService service = (UserDetailsService) this.appContext.getBean("myUserService");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
@@ -165,14 +165,14 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "</global-method-security>" + ConfigTestUtils.AUTH_PROVIDER_XML);
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
target = (BusinessService) appContext.getBean("target");
this.target = (BusinessService) this.appContext.getBean("target");
// someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER
target.someOther(0);
this.target.someOther(0);
try {
// String version should required admin role
target.someOther("somestring");
this.target.someOther("somestring");
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
@@ -186,13 +186,13 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ " '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);
target = (BusinessService) appContext.getBean("target");
this.target = (BusinessService) this.appContext.getBean("target");
// String method should not be protected
target.someOther("somestring");
this.target.someOther("somestring");
// All others should require ROLE_USER
try {
target.someOther(0);
this.target.someOther(0);
fail("Expected AuthenticationCredentialsNotFoundException");
}
catch (AuthenticationCredentialsNotFoundException expected) {
@@ -200,7 +200,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
target.someOther(0);
this.target.someOther(0);
}
@Test(expected = BeanDefinitionParsingException.class)
@@ -220,8 +220,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
target = (BusinessService) appContext.getBean("businessService");
target.someUserMethod1();
this.target = (BusinessService) this.appContext.getBean("businessService");
this.target.someUserMethod1();
}
// Expression configuration tests
@@ -230,11 +230,11 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
@Test
public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception {
setContext("<global-method-security pre-post-annotations='enabled'/>" + AUTH_PROVIDER_XML);
AffirmativeBased adm = (AffirmativeBased) appContext.getBeansOfType(AffirmativeBased.class).values()
AffirmativeBased adm = (AffirmativeBased) this.appContext.getBeansOfType(AffirmativeBased.class).values()
.toArray()[0];
List voters = (List) FieldUtils.getFieldValue(adm, "decisionVoters");
PreInvocationAuthorizationAdviceVoter mev = (PreInvocationAuthorizationAdviceVoter) voters.get(0);
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) appContext
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) this.appContext
.getBeansOfType(MethodSecurityMetadataSourceAdvisor.class).values().toArray()[0];
AfterInvocationProviderManager pm = (AfterInvocationProviderManager) ((MethodSecurityInterceptor) msi
.getAdvice()).getAfterInvocationManager();
@@ -248,9 +248,9 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
setContext("<global-method-security pre-post-annotations='enabled'/>"
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
+ AUTH_PROVIDER_XML);
SecurityContextHolder.getContext().setAuthentication(bob);
target = (BusinessService) appContext.getBean("target");
target.someAdminMethod();
SecurityContextHolder.getContext().setAuthentication(this.bob);
this.target = (BusinessService) this.appContext.getBean("target");
this.target.someAdminMethod();
}
@Test
@@ -260,8 +260,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "</b:bean>"
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
+ AUTH_PROVIDER_XML);
SecurityContextHolder.getContext().setAuthentication(bob);
ExpressionProtectedBusinessServiceImpl target = (ExpressionProtectedBusinessServiceImpl) appContext
SecurityContextHolder.getContext().setAuthentication(this.bob);
ExpressionProtectedBusinessServiceImpl target = (ExpressionProtectedBusinessServiceImpl) this.appContext
.getBean("target");
target.methodWithBeanNamePropertyAccessExpression("x");
}
@@ -271,13 +271,13 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
setContext("<global-method-security pre-post-annotations='enabled'/>"
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
+ AUTH_PROVIDER_XML);
SecurityContextHolder.getContext().setAuthentication(bob);
target = (BusinessService) appContext.getBean("target");
SecurityContextHolder.getContext().setAuthentication(this.bob);
this.target = (BusinessService) this.appContext.getBean("target");
List<String> arg = new ArrayList<>();
arg.add("joe");
arg.add("bob");
arg.add("sam");
List<?> result = target.methodReturningAList(arg);
List<?> result = this.target.methodReturningAList(arg);
// Expression is (filterObject == name or filterObject == 'sam'), so "joe" should
// be gone after pre-filter
// PostFilter should remove sam from the return object
@@ -290,10 +290,10 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
setContext("<global-method-security pre-post-annotations='enabled'/>"
+ "<b:bean id='target' class='org.springframework.security.access.annotation.ExpressionProtectedBusinessServiceImpl'/>"
+ AUTH_PROVIDER_XML);
SecurityContextHolder.getContext().setAuthentication(bob);
target = (BusinessService) appContext.getBean("target");
SecurityContextHolder.getContext().setAuthentication(this.bob);
this.target = (BusinessService) this.appContext.getBean("target");
Object[] arg = new String[] { "joe", "bob", "sam" };
Object[] result = target.methodReturningAnArray(arg);
Object[] result = this.target.methodReturningAnArray(arg);
assertThat(result).hasSize(1);
assertThat(result[0]).isEqualTo("bob");
}
@@ -318,7 +318,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "<global-method-security>"
+ " <protect-pointcut expression='execution(* org..*Foo.foo(..))' access='ROLE_USER'/>"
+ "</global-method-security>" + AUTH_PROVIDER_XML);
Foo foo = (Foo) appContext.getBean("target");
Foo foo = (Foo) this.appContext.getBean("target");
foo.foo(new SecurityConfig("A"));
}
@@ -328,8 +328,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
public void genericsMethodArgumentNamesAreResolved() {
setContext("<b:bean id='target' class='" + ConcreteFoo.class.getName() + "'/>"
+ "<global-method-security pre-post-annotations='enabled'/>" + AUTH_PROVIDER_XML);
SecurityContextHolder.getContext().setAuthentication(bob);
Foo foo = (Foo) appContext.getBean("target");
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
foo.foo(new SecurityConfig("A"));
}
@@ -342,8 +342,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
parent.refresh();
setContext("<global-method-security run-as-manager-ref='runAsMgr'/>" + AUTH_PROVIDER_XML, parent);
RunAsManagerImpl ram = (RunAsManagerImpl) appContext.getBean("runAsMgr");
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) appContext
RunAsManagerImpl ram = (RunAsManagerImpl) this.appContext.getBean("runAsMgr");
MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) this.appContext
.getBeansOfType(MethodSecurityMetadataSourceAdvisor.class).values().toArray()[0];
assertThat(ram).isSameAs(FieldUtils.getFieldValue(msi.getAdvice(), "runAsManager"));
}
@@ -357,8 +357,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "<global-method-security pre-post-annotations='enabled' metadata-source-ref='mds'/>"
+ AUTH_PROVIDER_XML);
// External MDS should take precedence over PreAuthorize
SecurityContextHolder.getContext().setAuthentication(bob);
Foo foo = (Foo) appContext.getBean("target");
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
@@ -378,8 +378,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
+ "<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);
SecurityContextHolder.getContext().setAuthentication(bob);
Foo foo = (Foo) appContext.getBean("target");
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
@@ -402,7 +402,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return authenticationManager.authenticate(authentication);
return this.authenticationManager.authenticate(authentication);
}
/*
@@ -413,17 +413,17 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
* .springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.authenticationManager = applicationContext.getBean(beanName, AuthenticationManager.class);
this.authenticationManager = applicationContext.getBean(this.beanName, AuthenticationManager.class);
}
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
this.appContext = new InMemoryXmlApplicationContext(context);
}
private void setContext(String context, ApplicationContext parent) {
appContext = new InMemoryXmlApplicationContext(context, parent);
this.appContext = new InMemoryXmlApplicationContext(context, parent);
}
interface Foo<T extends ConfigAttribute> {

View File

@@ -70,21 +70,21 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
@Test
public void targetDoesntLoseApplicationListenerInterface() {
assertThat(appContext.getBeansOfType(ApplicationListener.class)).hasSize(1);
assertThat(appContext.getBeanNamesForType(ApplicationListener.class)).hasSize(1);
appContext.publishEvent(new AuthenticationSuccessEvent(new TestingAuthenticationToken("user", "")));
assertThat(this.appContext.getBeansOfType(ApplicationListener.class)).hasSize(1);
assertThat(this.appContext.getBeanNamesForType(ApplicationListener.class)).hasSize(1);
this.appContext.publishEvent(new AuthenticationSuccessEvent(new TestingAuthenticationToken("user", "")));
assertThat(target).isInstanceOf(ApplicationListener.class);
assertThat(this.target).isInstanceOf(ApplicationListener.class);
}
@Test
public void targetShouldAllowUnprotectedMethodInvocationWithNoContext() {
target.unprotected();
this.target.unprotected();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
target.doSomething();
this.target.doSomething();
}
@Test
@@ -93,7 +93,7 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.doSomething();
this.target.doSomething();
}
@Test(expected = AccessDeniedException.class)
@@ -102,12 +102,12 @@ public class InterceptMethodsBeanDefinitionDecoratorTests implements Application
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
target.doSomething();
this.target.doSomething();
}
@Test(expected = AuthenticationException.class)
public void transactionalMethodsShouldBeSecured() {
transactionalTarget.doSomething();
this.transactionalTarget.doSomething();
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

View File

@@ -39,23 +39,23 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
@Before
public void loadContext() {
appContext = new InMemoryXmlApplicationContext(
this.appContext = new InMemoryXmlApplicationContext(
"<b:bean id='target' class='org.springframework.security.access.annotation.Jsr250BusinessServiceImpl'/>"
+ "<global-method-security jsr250-annotations='enabled'/>" + ConfigTestUtils.AUTH_PROVIDER_XML);
target = (BusinessService) appContext.getBean("target");
this.target = (BusinessService) this.appContext.getBean("target");
}
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
SecurityContextHolder.clearContext();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
target.someUserMethod1();
this.target.someUserMethod1();
}
@Test
@@ -64,7 +64,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someOther(0);
this.target.someOther(0);
}
@Test
@@ -73,7 +73,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someUserMethod1();
this.target.someUserMethod1();
}
@Test(expected = AccessDeniedException.class)
@@ -82,7 +82,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someAdminMethod();
this.target.someAdminMethod();
}
@Test
@@ -91,7 +91,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.rolesAllowedUser();
this.target.rolesAllowedUser();
}
}

View File

@@ -46,28 +46,28 @@ public class PreAuthorizeTests {
public void preAuthorizeAdminRoleDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
service.preAuthorizeAdminRole();
this.service.preAuthorizeAdminRole();
}
@Test
public void preAuthorizeAdminRoleGranted() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
service.preAuthorizeAdminRole();
this.service.preAuthorizeAdminRole();
}
@Test
public void preAuthorizeContactPermissionGranted() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
service.contactPermission(new Contact("user"));
this.service.contactPermission(new Contact("user"));
}
@Test(expected = AccessDeniedException.class)
public void preAuthorizeContactPermissionDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
service.contactPermission(new Contact("admin"));
this.service.contactPermission(new Contact("admin"));
}
}

View File

@@ -40,7 +40,7 @@ public class Sec2196Tests {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("test", "pass", "ROLE_USER"));
Service service = context.getBean(Service.class);
Service service = this.context.getBean(Service.class);
service.save(new User());
}
@@ -51,7 +51,7 @@ public class Sec2196Tests {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("test", "pass", "saveUsers"));
Service service = context.getBean(Service.class);
Service service = this.context.getBean(Service.class);
service.save(new User());
}
@@ -61,9 +61,9 @@ public class Sec2196Tests {
@After
public void closeAppContext() {
if (context != null) {
context.close();
context = null;
if (this.context != null) {
this.context.close();
this.context = null;
}
SecurityContextHolder.clearContext();
}

View File

@@ -47,24 +47,24 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Before
public void loadContext() {
SecurityContextHolder.clearContext();
appContext = new InMemoryXmlApplicationContext(
this.appContext = new InMemoryXmlApplicationContext(
"<b:bean id='target' class='org.springframework.security.access.annotation.BusinessServiceImpl'/>"
+ "<global-method-security secured-annotations='enabled'/>"
+ ConfigTestUtils.AUTH_PROVIDER_XML);
target = (BusinessService) appContext.getBean("target");
this.target = (BusinessService) this.appContext.getBean("target");
}
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
if (this.appContext != null) {
this.appContext.close();
}
SecurityContextHolder.clearContext();
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void targetShouldPreventProtectedMethodInvocationWithNoContext() {
target.someUserMethod1();
this.target.someUserMethod1();
}
@Test
@@ -73,7 +73,7 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someUserMethod1();
this.target.someUserMethod1();
}
@Test(expected = AccessDeniedException.class)
@@ -82,26 +82,26 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
AuthorityUtils.createAuthorityList("ROLE_SOMEOTHER"));
SecurityContextHolder.getContext().setAuthentication(token);
target.someAdminMethod();
this.target.someAdminMethod();
}
// SEC-1387
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void targetIsSerializableBeforeUse() throws Exception {
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(target);
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();
}
@Test(expected = AccessDeniedException.class)
public void targetIsSerializableAfterUse() throws Exception {
try {
target.someAdminMethod();
this.target.someAdminMethod();
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(target);
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();
}

View File

@@ -46,14 +46,14 @@ public class SecuredTests {
public void securedAdminRoleDenied() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_USER"));
service.securedAdminRole();
this.service.securedAdminRole();
}
@Test
public void securedAdminRoleGranted() {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"));
service.securedAdminRole();
this.service.securedAdminRole();
}
}

View File

@@ -32,21 +32,21 @@ public class Sec2499Tests {
@After
public void cleanup() {
if (parent != null) {
parent.close();
if (this.parent != null) {
this.parent.close();
}
if (child != null) {
child.close();
if (this.child != null) {
this.child.close();
}
}
@Test
public void methodExpressionHandlerInParentContextLoads() {
parent = new GenericXmlApplicationContext("org/springframework/security/config/method/sec2499/parent.xml");
child = new GenericXmlApplicationContext();
child.load("org/springframework/security/config/method/sec2499/child.xml");
child.setParent(parent);
child.refresh();
this.parent = new GenericXmlApplicationContext("org/springframework/security/config/method/sec2499/parent.xml");
this.child = new GenericXmlApplicationContext();
this.child.load("org/springframework/security/config/method/sec2499/child.xml");
this.child.setParent(this.parent);
this.child.refresh();
}
}

View File

@@ -106,9 +106,9 @@ public class ClientRegistrationsBeanDefinitionParserTests {
String contextConfig = ISSUER_URI_XML_CONFIG.replace("${issuer-uri}", serverUrl);
this.spring.context(contextConfig).autowire();
assertThat(clientRegistrationRepository).isInstanceOf(InMemoryClientRegistrationRepository.class);
assertThat(this.clientRegistrationRepository).isInstanceOf(InMemoryClientRegistrationRepository.class);
ClientRegistration googleRegistration = clientRegistrationRepository.findByRegistrationId("google-login");
ClientRegistration googleRegistration = this.clientRegistrationRepository.findByRegistrationId("google-login");
assertThat(googleRegistration).isNotNull();
assertThat(googleRegistration.getRegistrationId()).isEqualTo("google-login");
assertThat(googleRegistration.getClientId()).isEqualTo("google-client-id");
@@ -137,9 +137,9 @@ public class ClientRegistrationsBeanDefinitionParserTests {
public void parseWhenMultipleClientsConfiguredThenAvailableInRepository() {
this.spring.configLocations(this.xml("MultiClientRegistration")).autowire();
assertThat(clientRegistrationRepository).isInstanceOf(InMemoryClientRegistrationRepository.class);
assertThat(this.clientRegistrationRepository).isInstanceOf(InMemoryClientRegistrationRepository.class);
ClientRegistration googleRegistration = clientRegistrationRepository.findByRegistrationId("google-login");
ClientRegistration googleRegistration = this.clientRegistrationRepository.findByRegistrationId("google-login");
assertThat(googleRegistration).isNotNull();
assertThat(googleRegistration.getRegistrationId()).isEqualTo("google-login");
assertThat(googleRegistration.getClientId()).isEqualTo("google-client-id");
@@ -164,7 +164,7 @@ public class ClientRegistrationsBeanDefinitionParserTests {
assertThat(googleProviderDetails.getJwkSetUri()).isEqualTo("https://www.googleapis.com/oauth2/v3/certs");
assertThat(googleProviderDetails.getIssuerUri()).isEqualTo("https://accounts.google.com");
ClientRegistration githubRegistration = clientRegistrationRepository.findByRegistrationId("github-login");
ClientRegistration githubRegistration = this.clientRegistrationRepository.findByRegistrationId("github-login");
assertThat(githubRegistration).isNotNull();
assertThat(githubRegistration.getRegistrationId()).isEqualTo("github-login");
assertThat(githubRegistration.getClientId()).isEqualTo("github-client-id");

View File

@@ -40,7 +40,7 @@ public class UserDetailsManagerResourceFactoryBeanPropertiesResourceITests {
@Test
public void loadUserByUsernameWhenUserFoundThenNotNull() {
assertThat(users.loadUserByUsername("user")).isNotNull();
assertThat(this.users.loadUserByUsername("user")).isNotNull();
}
@Configuration

View File

@@ -39,7 +39,7 @@ public class UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITes
@Test
public void loadUserByUsernameWhenUserFoundThenNotNull() {
assertThat(users.loadUserByUsername("user")).isNotNull();
assertThat(this.users.loadUserByUsername("user")).isNotNull();
}
@Configuration

View File

@@ -56,7 +56,7 @@ public class InMemoryXmlApplicationContext extends AbstractXmlApplicationContext
public InMemoryXmlApplicationContext(String xml, String secVersion, ApplicationContext parent) {
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
inMemoryXml = new InMemoryResource(fullXml);
this.inMemoryXml = new InMemoryResource(fullXml);
setAllowBeanDefinitionOverriding(true);
setParent(parent);
refresh();
@@ -73,7 +73,7 @@ public class InMemoryXmlApplicationContext extends AbstractXmlApplicationContext
}
protected Resource[] getConfigResources() {
return new Resource[] { inMemoryXml };
return new Resource[] { this.inMemoryXml };
}
}

View File

@@ -44,7 +44,7 @@ public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebAppl
public InMemoryXmlWebApplicationContext(String xml, String secVersion, ApplicationContext parent) {
String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE;
inMemoryXml = new InMemoryResource(fullXml);
this.inMemoryXml = new InMemoryResource(fullXml);
setAllowBeanDefinitionOverriding(true);
setParent(parent);
}
@@ -52,7 +52,7 @@ public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebAppl
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
reader.loadBeanDefinitions(new Resource[] { inMemoryXml });
reader.loadBeanDefinitions(new Resource[] { this.inMemoryXml });
}
}

View File

@@ -382,12 +382,12 @@ public class OAuth2LoginTests {
.anyExchange().authenticated()
.and()
.oauth2Login()
.authenticationConverter(authenticationConverter)
.authenticationManager(manager)
.authenticationMatcher(matcher)
.authorizationRequestResolver(resolver)
.authenticationSuccessHandler(successHandler)
.authenticationFailureHandler(failureHandler);
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authenticationMatcher(this.matcher)
.authorizationRequestResolver(this.resolver)
.authenticationSuccessHandler(this.successHandler)
.authenticationFailureHandler(this.failureHandler);
// @formatter:on
return http.build();
}
@@ -463,11 +463,11 @@ public class OAuth2LoginTests {
)
.oauth2Login(oauth2Login ->
oauth2Login
.authenticationConverter(authenticationConverter)
.authenticationManager(manager)
.authenticationMatcher(matcher)
.authorizationRequestResolver(resolver)
.authenticationSuccessHandler(successHandler)
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authenticationMatcher(this.matcher)
.authorizationRequestResolver(this.resolver)
.authenticationSuccessHandler(this.successHandler)
);
// @formatter:on
return http.build();
@@ -607,28 +607,28 @@ public class OAuth2LoginTests {
.anyExchange().authenticated()
.and()
.oauth2Login()
.authenticationConverter(authenticationConverter)
.authenticationConverter(this.authenticationConverter)
.authenticationManager(authenticationManager())
.securityContextRepository(securityContextRepository);
.securityContextRepository(this.securityContextRepository);
return http.build();
// @formatter:on
}
private ReactiveAuthenticationManager authenticationManager() {
OidcAuthorizationCodeReactiveAuthenticationManager oidc = new OidcAuthorizationCodeReactiveAuthenticationManager(
tokenResponseClient, userService);
this.tokenResponseClient, this.userService);
oidc.setJwtDecoderFactory(jwtDecoderFactory());
return oidc;
}
@Bean
public ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory() {
return jwtDecoderFactory;
return this.jwtDecoderFactory;
}
@Bean
public ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
return tokenResponseClient;
return this.tokenResponseClient;
}
private static class JwtDecoderFactory implements ReactiveJwtDecoderFactory<ClientRegistration> {

View File

@@ -390,7 +390,7 @@ public class OAuth2ResourceServerSpecTests {
public void introspectWhenValidThenReturnsOk() {
this.spring.register(IntrospectionConfig.class, RootController.class).autowire();
this.spring.getContext().getBean(MockWebServer.class)
.setDispatcher(requiresAuth(clientId, clientSecret, active));
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();
@@ -400,7 +400,7 @@ public class OAuth2ResourceServerSpecTests {
public void introspectWhenValidAndIntrospectionInLambdaThenReturnsOk() {
this.spring.register(IntrospectionInLambdaConfig.class, RootController.class).autowire();
this.spring.getContext().getBean(MockWebServer.class)
.setDispatcher(requiresAuth(clientId, clientSecret, active));
.setDispatcher(requiresAuth(this.clientId, this.clientSecret, this.active));
this.client.get().headers(headers -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus()
.isOk();

View File

@@ -30,7 +30,7 @@ public class MessageSecurityPostProcessorTests {
public void handlesBeansWithoutClass() {
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
registry.registerBeanDefinition("beanWithoutClass", new GenericBeanDefinition());
postProcessor.postProcessBeanDefinitionRegistry(registry);
this.postProcessor.postProcessBeanDefinitionRegistry(registry);
}
}

View File

@@ -64,9 +64,9 @@ public class MethodSecurityInterceptorWithAopConfigTests {
@After
public void closeAppContext() {
SecurityContextHolder.clearContext();
if (appContext != null) {
appContext.close();
appContext = null;
if (this.appContext != null) {
this.appContext.close();
this.appContext = null;
}
}
@@ -77,7 +77,7 @@ public class MethodSecurityInterceptorWithAopConfigTests {
+ " <aop:advisor advice-ref='securityInterceptor' pointcut-ref='targetMethods' />" + "</aop:config>"
+ TARGET_BEAN_AND_INTERCEPTOR + AUTH_PROVIDER_XML + ACCESS_MANAGER_XML);
ITargetObject target = (ITargetObject) appContext.getBean("target");
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
// Check both against interface and class
try {
@@ -101,7 +101,7 @@ public class MethodSecurityInterceptorWithAopConfigTests {
+ " <b:property name='proxyTargetClass' value='false'/>" + "</b:bean>"
+ TARGET_BEAN_AND_INTERCEPTOR + AUTH_PROVIDER_XML + ACCESS_MANAGER_XML);
ITargetObject target = (ITargetObject) appContext.getBean("target");
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
try {
target.makeLowerCase("TEST");
@@ -115,7 +115,7 @@ public class MethodSecurityInterceptorWithAopConfigTests {
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
this.appContext = new InMemoryXmlApplicationContext(context);
}
}