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

@@ -30,8 +30,8 @@ public class TestDataSource extends DriverManagerDataSource implements Disposabl
String name;
public TestDataSource(String databaseName) {
name = databaseName;
System.out.println("Creating database: " + name);
this.name = databaseName;
System.out.println("Creating database: " + this.name);
setDriverClassName("org.hsqldb.jdbcDriver");
setUrl("jdbc:hsqldb:mem:" + databaseName);
setUsername("sa");
@@ -39,7 +39,7 @@ public class TestDataSource extends DriverManagerDataSource implements Disposabl
}
public void destroy() {
System.out.println("Shutting down database: " + name);
System.out.println("Shutting down database: " + this.name);
new JdbcTemplate(this).execute("SHUTDOWN");
}

View File

@@ -41,30 +41,31 @@ public class AuthorizationFailureEventTests {
@Test(expected = IllegalArgumentException.class)
public void rejectsNullSecureObject() {
new AuthorizationFailureEvent(null, attributes, foo, exception);
new AuthorizationFailureEvent(null, this.attributes, this.foo, this.exception);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullAttributesList() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, foo, exception);
new AuthorizationFailureEvent(new SimpleMethodInvocation(), null, this.foo, this.exception);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullAuthentication() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, null, exception);
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, null, this.exception);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullException() {
new AuthorizationFailureEvent(new SimpleMethodInvocation(), attributes, foo, null);
new AuthorizationFailureEvent(new SimpleMethodInvocation(), this.attributes, this.foo, null);
}
@Test
public void gettersReturnCtorSuppliedData() {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(), attributes, foo, exception);
assertThat(event.getConfigAttributes()).isSameAs(attributes);
assertThat(event.getAccessDeniedException()).isSameAs(exception);
assertThat(event.getAuthentication()).isSameAs(foo);
AuthorizationFailureEvent event = new AuthorizationFailureEvent(new Object(), this.attributes, this.foo,
this.exception);
assertThat(event.getConfigAttributes()).isSameAs(this.attributes);
assertThat(event.getAccessDeniedException()).isSameAs(this.exception);
assertThat(event.getAuthentication()).isSameAs(this.foo);
}
}

View File

@@ -62,7 +62,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
fail("Should be a superMethod called 'someUserMethod3' on class!");
}
Collection<ConfigAttribute> attrs = mds.findAttributes(method, DepartmentServiceImpl.class);
Collection<ConfigAttribute> attrs = this.mds.findAttributes(method, DepartmentServiceImpl.class);
assertThat(attrs).isNotNull();
@@ -160,7 +160,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
MockMethodInvocation annotatedAtClassLevel = new MockMethodInvocation(new AnnotatedAnnotationAtClassLevel(),
ReturnVoid.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -171,7 +171,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
MockMethodInvocation annotatedAtInterfaceLevel = new MockMethodInvocation(
new AnnotatedAnnotationAtInterfaceLevel(), ReturnVoid2.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -181,7 +181,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
public void annotatedAnnotationAtMethodLevelIsDetected() throws Exception {
MockMethodInvocation annotatedAtMethodLevel = new MockMethodInvocation(new AnnotatedAnnotationAtMethodLevel(),
ReturnVoid.class, "doSomething", List.class);
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs).extracting("attribute").containsOnly("CUSTOM");
@@ -190,7 +190,7 @@ public class SecuredAnnotationSecurityMetadataSourceTests {
@Test
public void proxyFactoryInterfaceAttributesFound() throws Exception {
MockMethodInvocation mi = MethodInvocationFactory.createSec2150MethodInvocation();
Collection<ConfigAttribute> attributes = mds.getAttributes(mi);
Collection<ConfigAttribute> attributes = this.mds.getAttributes(mi);
assertThat(attributes).hasSize(1);
assertThat(attributes).extracting("attribute").containsOnly("ROLE_PERSON");
}

View File

@@ -37,7 +37,7 @@ public class AbstractSecurityExpressionHandlerTests {
@Before
public void setUp() {
handler = new AbstractSecurityExpressionHandler<Object>() {
this.handler = new AbstractSecurityExpressionHandler<Object>() {
@Override
protected SecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication,
Object o) {
@@ -49,23 +49,24 @@ public class AbstractSecurityExpressionHandlerTests {
@Test
public void beanNamesAreCorrectlyResolved() {
handler.setApplicationContext(new AnnotationConfigApplicationContext(TestConfiguration.class));
this.handler.setApplicationContext(new AnnotationConfigApplicationContext(TestConfiguration.class));
Expression expression = handler.getExpressionParser().parseExpression("@number10.compareTo(@number20) < 0");
assertThat(expression.getValue(handler.createEvaluationContext(mock(Authentication.class), new Object())))
Expression expression = this.handler.getExpressionParser()
.parseExpression("@number10.compareTo(@number20) < 0");
assertThat(expression.getValue(this.handler.createEvaluationContext(mock(Authentication.class), new Object())))
.isEqualTo(true);
}
@Test(expected = IllegalArgumentException.class)
public void setExpressionParserNull() {
handler.setExpressionParser(null);
this.handler.setExpressionParser(null);
}
@Test
public void setExpressionParser() {
SpelExpressionParser parser = new SpelExpressionParser();
handler.setExpressionParser(parser);
assertThat(parser == handler.getExpressionParser()).isTrue();
this.handler.setExpressionParser(parser);
assertThat(parser == this.handler.getExpressionParser()).isTrue();
}
}

View File

@@ -39,58 +39,58 @@ public class SecurityExpressionRootTests {
@Before
public void setup() {
root = new SecurityExpressionRoot(JOE) {
this.root = new SecurityExpressionRoot(JOE) {
};
}
@Test
public void denyAllIsFalsePermitAllTrue() {
assertThat(root.denyAll()).isFalse();
assertThat(root.denyAll).isFalse();
assertThat(root.permitAll()).isTrue();
assertThat(root.permitAll).isTrue();
assertThat(this.root.denyAll()).isFalse();
assertThat(this.root.denyAll).isFalse();
assertThat(this.root.permitAll()).isTrue();
assertThat(this.root.permitAll).isTrue();
}
@Test
public void rememberMeIsCorrectlyDetected() {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
root.setTrustResolver(atr);
this.root.setTrustResolver(atr);
when(atr.isRememberMe(JOE)).thenReturn(true);
assertThat(root.isRememberMe()).isTrue();
assertThat(root.isFullyAuthenticated()).isFalse();
assertThat(this.root.isRememberMe()).isTrue();
assertThat(this.root.isFullyAuthenticated()).isFalse();
}
@Test
public void roleHierarchySupportIsCorrectlyUsedInEvaluatingRoles() {
root.setRoleHierarchy(authorities -> AuthorityUtils.createAuthorityList("ROLE_C"));
this.root.setRoleHierarchy(authorities -> AuthorityUtils.createAuthorityList("ROLE_C"));
assertThat(root.hasRole("C")).isTrue();
assertThat(root.hasAuthority("ROLE_C")).isTrue();
assertThat(root.hasRole("A")).isFalse();
assertThat(root.hasRole("B")).isFalse();
assertThat(root.hasAnyRole("C", "A", "B")).isTrue();
assertThat(root.hasAnyAuthority("ROLE_C", "ROLE_A", "ROLE_B")).isTrue();
assertThat(root.hasAnyRole("A", "B")).isFalse();
assertThat(this.root.hasRole("C")).isTrue();
assertThat(this.root.hasAuthority("ROLE_C")).isTrue();
assertThat(this.root.hasRole("A")).isFalse();
assertThat(this.root.hasRole("B")).isFalse();
assertThat(this.root.hasAnyRole("C", "A", "B")).isTrue();
assertThat(this.root.hasAnyAuthority("ROLE_C", "ROLE_A", "ROLE_B")).isTrue();
assertThat(this.root.hasAnyRole("A", "B")).isFalse();
}
@Test
public void hasRoleAddsDefaultPrefix() {
assertThat(root.hasRole("A")).isTrue();
assertThat(root.hasRole("NO")).isFalse();
assertThat(this.root.hasRole("A")).isTrue();
assertThat(this.root.hasRole("NO")).isFalse();
}
@Test
public void hasRoleEmptyPrefixDoesNotAddsDefaultPrefix() {
root.setDefaultRolePrefix("");
assertThat(root.hasRole("A")).isFalse();
assertThat(root.hasRole("ROLE_A")).isTrue();
this.root.setDefaultRolePrefix("");
assertThat(this.root.hasRole("A")).isFalse();
assertThat(this.root.hasRole("ROLE_A")).isTrue();
}
@Test
public void hasRoleNullPrefixDoesNotAddsDefaultPrefix() {
root.setDefaultRolePrefix(null);
assertThat(root.hasRole("A")).isFalse();
assertThat(root.hasRole("ROLE_A")).isTrue();
this.root.setDefaultRolePrefix(null);
assertThat(this.root.hasRole("A")).isFalse();
assertThat(this.root.hasRole("ROLE_A")).isTrue();
}
@Test
@@ -104,35 +104,35 @@ public class SecurityExpressionRootTests {
@Test
public void hasAnyRoleAddsDefaultPrefix() {
assertThat(root.hasAnyRole("NO", "A")).isTrue();
assertThat(root.hasAnyRole("NO", "NOT")).isFalse();
assertThat(this.root.hasAnyRole("NO", "A")).isTrue();
assertThat(this.root.hasAnyRole("NO", "NOT")).isFalse();
}
@Test
public void hasAnyRoleDoesNotAddDefaultPrefixForAlreadyPrefixedRoles() {
assertThat(root.hasAnyRole("ROLE_NO", "ROLE_A")).isTrue();
assertThat(root.hasAnyRole("ROLE_NO", "ROLE_NOT")).isFalse();
assertThat(this.root.hasAnyRole("ROLE_NO", "ROLE_A")).isTrue();
assertThat(this.root.hasAnyRole("ROLE_NO", "ROLE_NOT")).isFalse();
}
@Test
public void hasAnyRoleEmptyPrefixDoesNotAddsDefaultPrefix() {
root.setDefaultRolePrefix("");
assertThat(root.hasRole("A")).isFalse();
assertThat(root.hasRole("ROLE_A")).isTrue();
this.root.setDefaultRolePrefix("");
assertThat(this.root.hasRole("A")).isFalse();
assertThat(this.root.hasRole("ROLE_A")).isTrue();
}
@Test
public void hasAnyRoleNullPrefixDoesNotAddsDefaultPrefix() {
root.setDefaultRolePrefix(null);
assertThat(root.hasAnyRole("A")).isFalse();
assertThat(root.hasAnyRole("ROLE_A")).isTrue();
this.root.setDefaultRolePrefix(null);
assertThat(this.root.hasAnyRole("A")).isFalse();
assertThat(this.root.hasAnyRole("ROLE_A")).isTrue();
}
@Test
public void hasAuthorityDoesNotAddDefaultPrefix() {
assertThat(root.hasAuthority("A")).isFalse();
assertThat(root.hasAnyAuthority("NO", "A")).isFalse();
assertThat(root.hasAnyAuthority("ROLE_A", "NOT")).isTrue();
assertThat(this.root.hasAuthority("A")).isFalse();
assertThat(this.root.hasAnyAuthority("NO", "A")).isFalse();
assertThat(this.root.hasAnyAuthority("ROLE_A", "NOT")).isTrue();
}
}

View File

@@ -58,9 +58,9 @@ public class DefaultMethodSecurityExpressionHandlerTests {
@Before
public void setup() {
handler = new DefaultMethodSecurityExpressionHandler();
when(methodInvocation.getThis()).thenReturn(new Foo());
when(methodInvocation.getMethod()).thenReturn(Foo.class.getMethods()[0]);
this.handler = new DefaultMethodSecurityExpressionHandler();
when(this.methodInvocation.getThis()).thenReturn(new Foo());
when(this.methodInvocation.getMethod()).thenReturn(Foo.class.getMethods()[0]);
}
@After
@@ -70,18 +70,18 @@ public class DefaultMethodSecurityExpressionHandlerTests {
@Test(expected = IllegalArgumentException.class)
public void setTrustResolverNull() {
handler.setTrustResolver(null);
this.handler.setTrustResolver(null);
}
@Test
public void createEvaluationContextCustomTrustResolver() {
handler.setTrustResolver(trustResolver);
this.handler.setTrustResolver(this.trustResolver);
Expression expression = handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
Expression expression = this.handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
expression.getValue(context, Boolean.class);
verify(trustResolver).isAnonymous(authentication);
verify(this.trustResolver).isAnonymous(this.authentication);
}
@Test
@@ -92,11 +92,11 @@ public class DefaultMethodSecurityExpressionHandlerTests {
map.put("key2", "value2");
map.put("key3", "value3");
Expression expression = handler.getExpressionParser().parseExpression("filterObject.key eq 'key2'");
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject.key eq 'key2'");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
Object filtered = handler.filter(map, expression, context);
Object filtered = this.handler.filter(map, expression, context);
assertThat(filtered == map);
Map<String, String> result = ((Map<String, String>) filtered);
@@ -113,11 +113,11 @@ public class DefaultMethodSecurityExpressionHandlerTests {
map.put("key2", "value2");
map.put("key3", "value3");
Expression expression = handler.getExpressionParser().parseExpression("filterObject.value eq 'value3'");
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject.value eq 'value3'");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
Object filtered = handler.filter(map, expression, context);
Object filtered = this.handler.filter(map, expression, context);
assertThat(filtered == map);
Map<String, String> result = ((Map<String, String>) filtered);
@@ -134,12 +134,12 @@ public class DefaultMethodSecurityExpressionHandlerTests {
map.put("key2", "value2");
map.put("key3", "value3");
Expression expression = handler.getExpressionParser()
Expression expression = this.handler.getExpressionParser()
.parseExpression("(filterObject.key eq 'key1') or (filterObject.value eq 'value2')");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
Object filtered = handler.filter(map, expression, context);
Object filtered = this.handler.filter(map, expression, context);
assertThat(filtered == map);
Map<String, String> result = ((Map<String, String>) filtered);
@@ -153,11 +153,11 @@ public class DefaultMethodSecurityExpressionHandlerTests {
public void filterWhenUsingStreamThenFiltersStream() {
final Stream<String> stream = Stream.of("1", "2", "3");
Expression expression = handler.getExpressionParser().parseExpression("filterObject ne '2'");
Expression expression = this.handler.getExpressionParser().parseExpression("filterObject ne '2'");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
Object filtered = handler.filter(stream, expression, context);
Object filtered = this.handler.filter(stream, expression, context);
assertThat(filtered).isInstanceOf(Stream.class);
List<String> list = ((Stream<String>) filtered).collect(Collectors.toList());
@@ -169,11 +169,11 @@ public class DefaultMethodSecurityExpressionHandlerTests {
final Stream<?> upstream = mock(Stream.class);
doReturn(Stream.<String>empty()).when(upstream).filter(any());
Expression expression = handler.getExpressionParser().parseExpression("true");
Expression expression = this.handler.getExpressionParser().parseExpression("true");
EvaluationContext context = handler.createEvaluationContext(authentication, methodInvocation);
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.methodInvocation);
((Stream) handler.filter(upstream, expression, context)).close();
((Stream) this.handler.filter(upstream, expression, context)).close();
verify(upstream).close();
}

View File

@@ -46,7 +46,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
@Before
public void setUp() {
expressionBasedPreInvocationAdvice = new ExpressionBasedPreInvocationAdvice();
this.expressionBasedPreInvocationAdvice = new ExpressionBasedPreInvocationAdvice();
}
@Test(expected = IllegalArgumentException.class)
@@ -57,7 +57,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
}
@Test(expected = IllegalArgumentException.class)
@@ -67,7 +67,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
}
@Test
@@ -78,7 +78,8 @@ public class ExpressionBasedPreInvocationAdviceTests {
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
// when
boolean result = expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
boolean result = this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation,
attribute);
// then
assertThat(result).isTrue();
}
@@ -90,7 +91,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingArray", new Class[] { String[].class }, new Object[] { new String[0] });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
}
@Test
@@ -100,7 +101,8 @@ public class ExpressionBasedPreInvocationAdviceTests {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingCollection", new Class[] { List.class }, new Object[] { new ArrayList<>() });
// when
boolean result = expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
boolean result = this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation,
attribute);
// then
assertThat(result).isTrue();
}
@@ -112,7 +114,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
MockMethodInvocation methodInvocation = new MockMethodInvocation(new TestClass(), TestClass.class,
"doSomethingString", new Class[] { String.class }, new Object[] { "param" });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
}
@Test(expected = IllegalArgumentException.class)
@@ -123,7 +125,7 @@ public class ExpressionBasedPreInvocationAdviceTests {
"doSomethingTwoArgs", new Class[] { String.class, List.class },
new Object[] { "param", new ArrayList<>() });
// when - then
expressionBasedPreInvocationAdvice.before(authentication, methodInvocation, attribute);
this.expressionBasedPreInvocationAdvice.before(this.authentication, methodInvocation, attribute);
}
private class TestClass {

View File

@@ -43,8 +43,8 @@ public class MethodExpressionVoterTests {
@Test
public void hasRoleExpressionAllowsUserWithRole() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());
assertThat(
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null, "hasRole('blah')"))))
assertThat(this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null, "hasRole('blah')"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}
@@ -53,13 +53,13 @@ public class MethodExpressionVoterTests {
List<ConfigAttribute> cad = new ArrayList<>(1);
cad.add(new PreInvocationExpressionAttribute(null, null, "hasRole('joedoesnt')"));
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray());
assertThat(am.vote(joe, mi, cad)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
assertThat(this.am.vote(this.joe, mi, cad)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
@Test
public void matchingArgAgainstAuthenticationNameIsSuccessful() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAString(), "joe");
assertThat(am.vote(joe, mi,
assertThat(this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute(null, null,
"(#argument == principal) and (principal == 'joe')"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
@@ -69,7 +69,7 @@ public class MethodExpressionVoterTests {
public void accessIsGrantedIfNoPreAuthorizeAttributeIsUsed() throws Exception {
Collection arg = createCollectionArg("joe", "bob", "sam");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), arg);
assertThat(am.vote(joe, mi,
assertThat(this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "collection", null))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// All objects should have been removed, because the expression is always false
@@ -80,7 +80,7 @@ public class MethodExpressionVoterTests {
public void collectionPreFilteringIsSuccessful() throws Exception {
List arg = createCollectionArg("joe", "bob", "sam");
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(), arg);
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(
this.am.vote(this.joe, mi, createAttributes(new PreInvocationExpressionAttribute(
"(filterObject == 'joe' or filterObject == 'sam')", "collection", "permitAll")));
assertThat(arg).containsExactly("joe", "sam");
}
@@ -89,7 +89,7 @@ public class MethodExpressionVoterTests {
public void arraysCannotBePrefiltered() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAnArray(),
createArrayArg("sam", "joe"));
am.vote(joe, mi,
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'jim')", "someArray", null)));
}
@@ -97,7 +97,7 @@ public class MethodExpressionVoterTests {
public void incorrectFilterTargetNameIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
createCollectionArg("joe", "bob"));
am.vote(joe, mi,
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collcetion", null)));
}
@@ -105,7 +105,7 @@ public class MethodExpressionVoterTests {
public void nullNamedFilterTargetIsRejected() throws Exception {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingACollection(),
new Object[] { null });
am.vote(joe, mi,
this.am.vote(this.joe, mi,
createAttributes(new PreInvocationExpressionAttribute("(filterObject == 'joe')", "collection", null)));
}
@@ -114,7 +114,7 @@ public class MethodExpressionVoterTests {
MethodInvocation mi = new SimpleMethodInvocation(new TargetImpl(), methodTakingAString(), "joe");
assertThat(
am.vote(joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null,
this.am.vote(this.joe, mi, createAttributes(new PreInvocationExpressionAttribute(null, null,
"T(org.springframework.security.access.expression.method.SecurityRules).isJoe(#argument)"))))
.isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
}

View File

@@ -50,12 +50,12 @@ public class MethodSecurityEvaluationContextTests {
public void lookupVariableWhenParameterNameNullThenNotSet() {
Class<String> type = String.class;
Method method = ReflectionUtils.findMethod(String.class, "contains", CharSequence.class);
doReturn(new String[] { null }).when(paramNameDiscoverer).getParameterNames(method);
doReturn(new Object[] { null }).when(methodInvocation).getArguments();
doReturn(type).when(methodInvocation).getThis();
doReturn(method).when(methodInvocation).getMethod();
doReturn(new String[] { null }).when(this.paramNameDiscoverer).getParameterNames(method);
doReturn(new Object[] { null }).when(this.methodInvocation).getArguments();
doReturn(type).when(this.methodInvocation).getThis();
doReturn(method).when(this.methodInvocation).getMethod();
NotNullVariableMethodSecurityEvaluationContext context = new NotNullVariableMethodSecurityEvaluationContext(
authentication, methodInvocation, paramNameDiscoverer);
this.authentication, this.methodInvocation, this.paramNameDiscoverer);
context.lookupVariable("testVariable");
}

View File

@@ -51,43 +51,43 @@ public class MethodSecurityExpressionRootTests {
@Before
public void createContext() {
user = mock(Authentication.class);
root = new MethodSecurityExpressionRoot(user);
ctx = new StandardEvaluationContext();
ctx.setRootObject(root);
trustResolver = mock(AuthenticationTrustResolver.class);
root.setTrustResolver(trustResolver);
this.user = mock(Authentication.class);
this.root = new MethodSecurityExpressionRoot(this.user);
this.ctx = new StandardEvaluationContext();
this.ctx.setRootObject(this.root);
this.trustResolver = mock(AuthenticationTrustResolver.class);
this.root.setTrustResolver(this.trustResolver);
}
@Test
public void canCallMethodsOnVariables() {
ctx.setVariable("var", "somestring");
Expression e = parser.parseExpression("#var.length() == 10");
this.ctx.setVariable("var", "somestring");
Expression e = this.parser.parseExpression("#var.length() == 10");
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
}
@Test
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(true);
assertThat(root.isAnonymous()).isTrue();
when(this.trustResolver.isAnonymous(this.user)).thenReturn(true);
assertThat(this.root.isAnonymous()).isTrue();
}
@Test
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
when(trustResolver.isAnonymous(user)).thenReturn(false);
assertThat(root.isAnonymous()).isFalse();
when(this.trustResolver.isAnonymous(this.user)).thenReturn(false);
assertThat(this.root.isAnonymous()).isFalse();
}
@Test
public void hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes() {
final Object dummyDomainObject = new Object();
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
ctx.setVariable("domainObject", dummyDomainObject);
root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(false);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(false);
assertThat(root.hasPermission(dummyDomainObject, "ignored")).isFalse();
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
}
@@ -95,31 +95,31 @@ public class MethodSecurityExpressionRootTests {
public void hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes() {
final Object dummyDomainObject = new Object();
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
ctx.setVariable("domainObject", dummyDomainObject);
root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, dummyDomainObject, "ignored")).thenReturn(true);
assertThat(root.hasPermission(dummyDomainObject, "ignored")).isTrue();
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
@Test
public void hasPermissionOnDomainObjectWorksWithIntegerExpressions() {
final Object dummyDomainObject = new Object();
ctx.setVariable("domainObject", dummyDomainObject);
this.ctx.setVariable("domainObject", dummyDomainObject);
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
root.setPermissionEvaluator(pe);
when(pe.hasPermission(eq(user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true).thenReturn(true)
.thenReturn(false);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(eq(this.user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true)
.thenReturn(true).thenReturn(false);
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
Expression e = this.parser.parseExpression("hasPermission(#domainObject, 0xA)");
// evaluator returns true
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 10)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
e = this.parser.parseExpression("hasPermission(#domainObject, 10)");
// evaluator returns true
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(#domainObject, 0xFF)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
e = this.parser.parseExpression("hasPermission(#domainObject, 0xFF)");
// evaluator returns false, make sure return value matches
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isFalse();
}
@Test
@@ -129,20 +129,20 @@ public class MethodSecurityExpressionRootTests {
return "x";
}
};
root.setThis(targetObject);
this.root.setThis(targetObject);
Integer i = 2;
PermissionEvaluator pe = mock(PermissionEvaluator.class);
root.setPermissionEvaluator(pe);
when(pe.hasPermission(user, targetObject, i)).thenReturn(true).thenReturn(false);
when(pe.hasPermission(user, "x", i)).thenReturn(true);
this.root.setPermissionEvaluator(pe);
when(pe.hasPermission(this.user, targetObject, i)).thenReturn(true).thenReturn(false);
when(pe.hasPermission(this.user, "x", i)).thenReturn(true);
Expression e = parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isFalse();
Expression e = this.parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
e = this.parser.parseExpression("hasPermission(this, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isFalse();
e = parser.parseExpression("hasPermission(this.x, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, ctx)).isTrue();
e = this.parser.parseExpression("hasPermission(this.x, 2)");
assertThat(ExpressionUtils.evaluateAsBoolean(e, this.ctx)).isTrue();
}
}

View File

@@ -68,25 +68,25 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Before
public void setUpData() throws Exception {
voidImpl1 = new MockMethodInvocation(new ReturnVoidImpl1(), ReturnVoid.class, "doSomething", List.class);
voidImpl2 = new MockMethodInvocation(new ReturnVoidImpl2(), ReturnVoid.class, "doSomething", List.class);
voidImpl3 = new MockMethodInvocation(new ReturnVoidImpl3(), ReturnVoid.class, "doSomething", List.class);
listImpl1 = new MockMethodInvocation(new ReturnAListImpl1(), ReturnAList.class, "doSomething", List.class);
notherListImpl1 = new MockMethodInvocation(new ReturnAnotherListImpl1(), ReturnAnotherList.class, "doSomething",
List.class);
notherListImpl2 = new MockMethodInvocation(new ReturnAnotherListImpl2(), ReturnAnotherList.class, "doSomething",
List.class);
annotatedAtClassLevel = new MockMethodInvocation(new CustomAnnotationAtClassLevel(), ReturnVoid.class,
this.voidImpl1 = new MockMethodInvocation(new ReturnVoidImpl1(), ReturnVoid.class, "doSomething", List.class);
this.voidImpl2 = new MockMethodInvocation(new ReturnVoidImpl2(), ReturnVoid.class, "doSomething", List.class);
this.voidImpl3 = new MockMethodInvocation(new ReturnVoidImpl3(), ReturnVoid.class, "doSomething", List.class);
this.listImpl1 = new MockMethodInvocation(new ReturnAListImpl1(), ReturnAList.class, "doSomething", List.class);
this.notherListImpl1 = new MockMethodInvocation(new ReturnAnotherListImpl1(), ReturnAnotherList.class,
"doSomething", List.class);
annotatedAtInterfaceLevel = new MockMethodInvocation(new CustomAnnotationAtInterfaceLevel(), ReturnVoid2.class,
this.notherListImpl2 = new MockMethodInvocation(new ReturnAnotherListImpl2(), ReturnAnotherList.class,
"doSomething", List.class);
annotatedAtMethodLevel = new MockMethodInvocation(new CustomAnnotationAtMethodLevel(), ReturnVoid.class,
this.annotatedAtClassLevel = new MockMethodInvocation(new CustomAnnotationAtClassLevel(), ReturnVoid.class,
"doSomething", List.class);
this.annotatedAtInterfaceLevel = new MockMethodInvocation(new CustomAnnotationAtInterfaceLevel(),
ReturnVoid2.class, "doSomething", List.class);
this.annotatedAtMethodLevel = new MockMethodInvocation(new CustomAnnotationAtMethodLevel(), ReturnVoid.class,
"doSomething", List.class);
}
@Test
public void classLevelPreAnnotationIsPickedUpWhenNoMethodLevelExists() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl1).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -98,7 +98,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void mixedClassAndMethodPreAnnotationsAreBothIncluded() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl2).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl2).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -110,7 +110,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void methodWithPreFilterOnlyIsAllowed() {
ConfigAttribute[] attrs = mds.getAttributes(voidImpl3).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.voidImpl3).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -122,7 +122,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void methodWithPostFilterOnlyIsAllowed() {
ConfigAttribute[] attrs = mds.getAttributes(listImpl1).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.listImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(2);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -136,7 +136,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void interfaceAttributesAreIncluded() {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl1).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl1).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -149,7 +149,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void classAttributesTakesPrecedeceOverInterfaceAttributes() {
ConfigAttribute[] attrs = mds.getAttributes(notherListImpl2).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.notherListImpl2).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
assertThat(attrs[0] instanceof PreInvocationExpressionAttribute).isTrue();
@@ -162,21 +162,22 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void customAnnotationAtClassLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtClassLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@Test
public void customAnnotationAtInterfaceLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtInterfaceLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtInterfaceLevel)
.toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@Test
public void customAnnotationAtMethodLevelIsDetected() {
ConfigAttribute[] attrs = mds.getAttributes(annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
ConfigAttribute[] attrs = this.mds.getAttributes(this.annotatedAtMethodLevel).toArray(new ConfigAttribute[0]);
assertThat(attrs).hasSize(1);
}
@@ -184,7 +185,7 @@ public class PrePostAnnotationSecurityMetadataSourceTests {
@Test
public void proxyFactoryInterfaceAttributesFound() throws Exception {
MockMethodInvocation mi = MethodInvocationFactory.createSec2150MethodInvocation();
Collection<ConfigAttribute> attributes = mds.getAttributes(mi);
Collection<ConfigAttribute> attributes = this.mds.getAttributes(mi);
assertThat(attributes).hasSize(1);
Expression expression = (Expression) ReflectionTestUtils.getField(attributes.iterator().next(),
"authorizeExpression");

View File

@@ -65,7 +65,7 @@ public class AbstractSecurityInterceptorTests {
}
public SecurityMetadataSource obtainSecurityMetadataSource() {
return securityMetadataSource;
return this.securityMetadataSource;
}
public void setSecurityMetadataSource(SecurityMetadataSource securityMetadataSource) {
@@ -83,7 +83,7 @@ public class AbstractSecurityInterceptorTests {
}
public SecurityMetadataSource obtainSecurityMetadataSource() {
return securityMetadataSource;
return this.securityMetadataSource;
}
public void setSecurityMetadataSource(SecurityMetadataSource securityMetadataSource) {

View File

@@ -167,19 +167,19 @@ public class AfterInvocationProviderManagerTests {
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config,
Object returnedObject) throws AccessDeniedException {
if (config.contains(configAttribute)) {
return forceReturnObject;
if (config.contains(this.configAttribute)) {
return this.forceReturnObject;
}
return returnedObject;
}
public boolean supports(Class<?> clazz) {
return secureObject.isAssignableFrom(clazz);
return this.secureObject.isAssignableFrom(clazz);
}
public boolean supports(ConfigAttribute attribute) {
return attribute.equals(configAttribute);
return attribute.equals(this.configAttribute);
}
}

View File

@@ -86,16 +86,16 @@ public class MethodSecurityInterceptorTests {
@Before
public final void setUp() {
SecurityContextHolder.clearContext();
token = new TestingAuthenticationToken("Test", "Password");
interceptor = new MethodSecurityInterceptor();
adm = mock(AccessDecisionManager.class);
authman = mock(AuthenticationManager.class);
mds = mock(MethodSecurityMetadataSource.class);
eventPublisher = mock(ApplicationEventPublisher.class);
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
interceptor.setSecurityMetadataSource(mds);
interceptor.setApplicationEventPublisher(eventPublisher);
this.token = new TestingAuthenticationToken("Test", "Password");
this.interceptor = new MethodSecurityInterceptor();
this.adm = mock(AccessDecisionManager.class);
this.authman = mock(AuthenticationManager.class);
this.mds = mock(MethodSecurityMetadataSource.class);
this.eventPublisher = mock(ApplicationEventPublisher.class);
this.interceptor.setAccessDecisionManager(this.adm);
this.interceptor.setAuthenticationManager(this.authman);
this.interceptor.setSecurityMetadataSource(this.mds);
this.interceptor.setApplicationEventPublisher(this.eventPublisher);
createTarget(false);
}
@@ -105,119 +105,119 @@ public class MethodSecurityInterceptorTests {
}
private void createTarget(boolean useMock) {
realTarget = useMock ? mock(ITargetObject.class) : new TargetObject();
ProxyFactory pf = new ProxyFactory(realTarget);
pf.addAdvice(interceptor);
advisedTarget = (ITargetObject) pf.getProxy();
this.realTarget = useMock ? mock(ITargetObject.class) : new TargetObject();
ProxyFactory pf = new ProxyFactory(this.realTarget);
pf.addAdvice(this.interceptor);
this.advisedTarget = (ITargetObject) pf.getProxy();
}
@Test
public void gettersReturnExpectedData() {
RunAsManager runAs = mock(RunAsManager.class);
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setRunAsManager(runAs);
interceptor.setAfterInvocationManager(aim);
assertThat(interceptor.getAccessDecisionManager()).isEqualTo(adm);
assertThat(interceptor.getRunAsManager()).isEqualTo(runAs);
assertThat(interceptor.getAuthenticationManager()).isEqualTo(authman);
assertThat(interceptor.getSecurityMetadataSource()).isEqualTo(mds);
assertThat(interceptor.getAfterInvocationManager()).isEqualTo(aim);
this.interceptor.setRunAsManager(runAs);
this.interceptor.setAfterInvocationManager(aim);
assertThat(this.interceptor.getAccessDecisionManager()).isEqualTo(this.adm);
assertThat(this.interceptor.getRunAsManager()).isEqualTo(runAs);
assertThat(this.interceptor.getAuthenticationManager()).isEqualTo(this.authman);
assertThat(this.interceptor.getSecurityMetadataSource()).isEqualTo(this.mds);
assertThat(this.interceptor.getAfterInvocationManager()).isEqualTo(aim);
}
@Test(expected = IllegalArgumentException.class)
public void missingAccessDecisionManagerIsDetected() throws Exception {
interceptor.setAccessDecisionManager(null);
interceptor.afterPropertiesSet();
this.interceptor.setAccessDecisionManager(null);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void missingAuthenticationManagerIsDetected() throws Exception {
interceptor.setAuthenticationManager(null);
interceptor.afterPropertiesSet();
this.interceptor.setAuthenticationManager(null);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void missingMethodSecurityMetadataSourceIsRejected() throws Exception {
interceptor.setSecurityMetadataSource(null);
interceptor.afterPropertiesSet();
this.interceptor.setSecurityMetadataSource(null);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void missingRunAsManagerIsRejected() throws Exception {
interceptor.setRunAsManager(null);
interceptor.afterPropertiesSet();
this.interceptor.setRunAsManager(null);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
when(mds.supports(MethodInvocation.class)).thenReturn(false);
interceptor.afterPropertiesSet();
when(this.mds.supports(MethodInvocation.class)).thenReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
when(mds.supports(MethodInvocation.class)).thenReturn(true);
when(adm.supports(MethodInvocation.class)).thenReturn(false);
interceptor.afterPropertiesSet();
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.adm.supports(MethodInvocation.class)).thenReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
final RunAsManager ram = mock(RunAsManager.class);
when(ram.supports(MethodInvocation.class)).thenReturn(false);
interceptor.setRunAsManager(ram);
interceptor.afterPropertiesSet();
this.interceptor.setRunAsManager(ram);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
when(aim.supports(MethodInvocation.class)).thenReturn(false);
interceptor.setAfterInvocationManager(aim);
interceptor.afterPropertiesSet();
this.interceptor.setAfterInvocationManager(aim);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
when(adm.supports(any(ConfigAttribute.class))).thenReturn(false);
interceptor.afterPropertiesSet();
when(this.adm.supports(any(ConfigAttribute.class))).thenReturn(false);
this.interceptor.afterPropertiesSet();
}
@Test
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
when(adm.supports(MethodInvocation.class)).thenReturn(true);
when(mds.supports(MethodInvocation.class)).thenReturn(true);
interceptor.setValidateConfigAttributes(false);
interceptor.afterPropertiesSet();
verify(mds, never()).getAllConfigAttributes();
verify(adm, never()).supports(any(ConfigAttribute.class));
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
this.interceptor.setValidateConfigAttributes(false);
this.interceptor.afterPropertiesSet();
verify(this.mds, never()).getAllConfigAttributes();
verify(this.adm, never()).supports(any(ConfigAttribute.class));
}
@Test
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
when(adm.supports(MethodInvocation.class)).thenReturn(true);
when(mds.supports(MethodInvocation.class)).thenReturn(true);
when(mds.getAllConfigAttributes()).thenReturn(null);
when(this.adm.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.supports(MethodInvocation.class)).thenReturn(true);
when(this.mds.getAllConfigAttributes()).thenReturn(null);
interceptor.setValidateConfigAttributes(true);
interceptor.afterPropertiesSet();
verify(adm, never()).supports(any(ConfigAttribute.class));
this.interceptor.setValidateConfigAttributes(true);
this.interceptor.afterPropertiesSet();
verify(this.adm, never()).supports(any(ConfigAttribute.class));
}
@Test
public void callingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts() {
mdsReturnsNull();
String result = advisedTarget.publicMakeLowerCase("HELLO");
String result = this.advisedTarget.publicMakeLowerCase("HELLO");
assertThat(result).isEqualTo("hello Authentication empty");
}
@Test
public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
mdsReturnsNull();
SecurityContextHolder.getContext().setAuthentication(token);
assertThat(advisedTarget.publicMakeLowerCase("HELLO"))
SecurityContextHolder.getContext().setAuthentication(this.token);
assertThat(this.advisedTarget.publicMakeLowerCase("HELLO"))
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken false");
assertThat(!token.isAuthenticated()).isTrue();
assertThat(!this.token.isAuthenticated()).isTrue();
}
@Test(expected = AuthenticationException.class)
@@ -226,87 +226,87 @@ public class MethodSecurityInterceptorTests {
SecurityContextHolder.getContext().setAuthentication(token);
mdsReturnsUserRole();
when(authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
when(this.authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
advisedTarget.makeLowerCase("HELLO");
this.advisedTarget.makeLowerCase("HELLO");
}
@Test
public void callSucceedsIfAccessDecisionManagerGrantsAccess() {
token.setAuthenticated(true);
interceptor.setPublishAuthorizationSuccess(true);
SecurityContextHolder.getContext().setAuthentication(token);
this.token.setAuthenticated(true);
this.interceptor.setPublishAuthorizationSuccess(true);
SecurityContextHolder.getContext().setAuthentication(this.token);
mdsReturnsUserRole();
String result = advisedTarget.makeLowerCase("HELLO");
String result = this.advisedTarget.makeLowerCase("HELLO");
// Note we check the isAuthenticated remained true in following line
assertThat(result)
.isEqualTo("hello org.springframework.security.authentication.TestingAuthenticationToken true");
verify(eventPublisher).publishEvent(any(AuthorizedEvent.class));
verify(this.eventPublisher).publishEvent(any(AuthorizedEvent.class));
}
@Test
public void callIsntMadeWhenAccessDecisionManagerRejectsAccess() {
SecurityContextHolder.getContext().setAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(this.token);
// Use mocked target to make sure invocation doesn't happen (not in expectations
// so test would fail)
createTarget(true);
mdsReturnsUserRole();
when(authman.authenticate(token)).thenReturn(token);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(any(Authentication.class),
when(this.authman.authenticate(this.token)).thenReturn(this.token);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class));
try {
advisedTarget.makeUpperCase("HELLO");
this.advisedTarget.makeUpperCase("HELLO");
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
verify(eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullSecuredObjects() throws Throwable {
interceptor.invoke(null);
this.interceptor.invoke(null);
}
@Test
public void runAsReplacementIsCorrectlySet() {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(token);
token.setAuthenticated(true);
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
String result = advisedTarget.makeUpperCase("hello");
String result = this.advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
// SEC-1967
@Test
public void runAsReplacementCleansAfterException() {
createTarget(true);
when(realTarget.makeUpperCase(anyString())).thenThrow(new RuntimeException());
when(this.realTarget.makeUpperCase(anyString())).thenThrow(new RuntimeException());
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(token);
token.setAuthenticated(true);
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
try {
advisedTarget.makeUpperCase("hello");
this.advisedTarget.makeUpperCase("hello");
fail("Expected Exception");
}
catch (RuntimeException success) {
@@ -314,29 +314,29 @@ public class MethodSecurityInterceptorTests {
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void emptySecurityContextIsRejected() {
mdsReturnsUserRole();
advisedTarget.makeUpperCase("hello");
this.advisedTarget.makeUpperCase("hello");
}
@Test
public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() throws Throwable {
MethodInvocation mi = mock(MethodInvocation.class);
token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(token);
this.token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(this.token);
mdsReturnsUserRole();
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setAfterInvocationManager(aim);
this.interceptor.setAfterInvocationManager(aim);
when(mi.proceed()).thenThrow(new Throwable());
try {
interceptor.invoke(mi);
this.interceptor.invoke(mi);
fail("Expected exception");
}
catch (Throwable expected) {
@@ -346,11 +346,11 @@ public class MethodSecurityInterceptorTests {
}
void mdsReturnsNull() {
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
}
void mdsReturnsUserRole() {
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(this.mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
}
}

View File

@@ -82,26 +82,26 @@ public class AspectJMethodSecurityInterceptorTests {
public final void setUp() {
MockitoAnnotations.initMocks(this);
SecurityContextHolder.clearContext();
token = new TestingAuthenticationToken("Test", "Password");
interceptor = new AspectJMethodSecurityInterceptor();
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
interceptor.setSecurityMetadataSource(mds);
this.token = new TestingAuthenticationToken("Test", "Password");
this.interceptor = new AspectJMethodSecurityInterceptor();
this.interceptor.setAccessDecisionManager(this.adm);
this.interceptor.setAuthenticationManager(this.authman);
this.interceptor.setSecurityMetadataSource(this.mds);
// Set up joinpoint information for the countLength method on TargetObject
joinPoint = mock(ProceedingJoinPoint.class); // new MockJoinPoint(new
// TargetObject(), method);
this.joinPoint = mock(ProceedingJoinPoint.class); // new MockJoinPoint(new
// TargetObject(), method);
Signature sig = mock(Signature.class);
when(sig.getDeclaringType()).thenReturn(TargetObject.class);
JoinPoint.StaticPart staticPart = mock(JoinPoint.StaticPart.class);
when(joinPoint.getSignature()).thenReturn(sig);
when(joinPoint.getStaticPart()).thenReturn(staticPart);
when(this.joinPoint.getSignature()).thenReturn(sig);
when(this.joinPoint.getStaticPart()).thenReturn(staticPart);
CodeSignature codeSig = mock(CodeSignature.class);
when(codeSig.getName()).thenReturn("countLength");
when(codeSig.getDeclaringType()).thenReturn(TargetObject.class);
when(codeSig.getParameterTypes()).thenReturn(new Class[] { String.class });
when(staticPart.getSignature()).thenReturn(codeSig);
when(mds.getAttributes(any())).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(authman.authenticate(token)).thenReturn(token);
when(this.mds.getAttributes(any())).thenReturn(SecurityConfig.createList("ROLE_USER"));
when(this.authman.authenticate(this.token)).thenReturn(this.token);
}
@After
@@ -111,27 +111,27 @@ public class AspectJMethodSecurityInterceptorTests {
@Test
public void callbackIsInvokedWhenPermissionGranted() throws Throwable {
SecurityContextHolder.getContext().setAuthentication(token);
interceptor.invoke(joinPoint, aspectJCallback);
verify(aspectJCallback).proceedWithObject();
SecurityContextHolder.getContext().setAuthentication(this.token);
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
verify(this.aspectJCallback).proceedWithObject();
// Just try the other method too
interceptor.invoke(joinPoint);
this.interceptor.invoke(this.joinPoint);
}
@SuppressWarnings("unchecked")
@Test
public void callbackIsNotInvokedWhenPermissionDenied() {
doThrow(new AccessDeniedException("denied")).when(adm).decide(any(), any(), any());
doThrow(new AccessDeniedException("denied")).when(this.adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(this.token);
try {
interceptor.invoke(joinPoint, aspectJCallback);
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
verify(aspectJCallback, never()).proceedWithObject();
verify(this.aspectJCallback, never()).proceedWithObject();
}
@Test
@@ -139,9 +139,9 @@ public class AspectJMethodSecurityInterceptorTests {
TargetObject to = new TargetObject();
Method m = ClassUtils.getMethodIfAvailable(TargetObject.class, "countLength", new Class[] { String.class });
when(joinPoint.getTarget()).thenReturn(to);
when(joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(joinPoint);
when(this.joinPoint.getTarget()).thenReturn(to);
when(this.joinPoint.getArgs()).thenReturn(new Object[] { "Hi" });
MethodInvocationAdapter mia = new MethodInvocationAdapter(this.joinPoint);
assertThat(mia.getArguments()[0]).isEqualTo("Hi");
assertThat(mia.getStaticPart()).isEqualTo(m);
assertThat(mia.getMethod()).isEqualTo(m);
@@ -150,16 +150,16 @@ public class AspectJMethodSecurityInterceptorTests {
@Test
public void afterInvocationManagerIsNotInvokedIfExceptionIsRaised() {
token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(token);
this.token.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(this.token);
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setAfterInvocationManager(aim);
this.interceptor.setAfterInvocationManager(aim);
when(aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
try {
interceptor.invoke(joinPoint, aspectJCallback);
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected exception");
}
catch (RuntimeException expected) {
@@ -173,17 +173,17 @@ public class AspectJMethodSecurityInterceptorTests {
@SuppressWarnings("unchecked")
public void invokeWithAspectJCallbackRunAsReplacementCleansAfterException() {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(token);
token.setAuthenticated(true);
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.aspectJCallback.proceedWithObject()).thenThrow(new RuntimeException());
try {
interceptor.invoke(joinPoint, aspectJCallback);
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected Exception");
}
catch (RuntimeException success) {
@@ -191,7 +191,7 @@ public class AspectJMethodSecurityInterceptorTests {
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
// SEC-1967
@@ -199,17 +199,17 @@ public class AspectJMethodSecurityInterceptorTests {
@SuppressWarnings("unchecked")
public void invokeRunAsReplacementCleansAfterException() throws Throwable {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(token);
token.setAuthenticated(true);
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(),
TestingAuthenticationToken.class);
interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(joinPoint.proceed()).thenThrow(new RuntimeException());
this.interceptor.setRunAsManager(runAs);
when(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
when(this.joinPoint.proceed()).thenThrow(new RuntimeException());
try {
interceptor.invoke(joinPoint);
this.interceptor.invoke(this.joinPoint);
fail("Expected Exception");
}
catch (RuntimeException success) {
@@ -217,7 +217,7 @@ public class AspectJMethodSecurityInterceptorTests {
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
}

View File

@@ -47,25 +47,25 @@ public class MapBasedMethodSecurityMetadataSourceTests {
@Before
public void initialize() throws Exception {
mds = new MapBasedMethodSecurityMetadataSource();
someMethodString = MockService.class.getMethod("someMethod", String.class);
someMethodInteger = MockService.class.getMethod("someMethod", Integer.class);
this.mds = new MapBasedMethodSecurityMetadataSource();
this.someMethodString = MockService.class.getMethod("someMethod", String.class);
this.someMethodInteger = MockService.class.getMethod("someMethod", Integer.class);
}
@Test
public void wildcardedMatchIsOverwrittenByMoreSpecificMatch() {
mds.addSecureMethod(MockService.class, "some*", ROLE_A);
mds.addSecureMethod(MockService.class, "someMethod*", ROLE_B);
assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_B);
this.mds.addSecureMethod(MockService.class, "some*", this.ROLE_A);
this.mds.addSecureMethod(MockService.class, "someMethod*", this.ROLE_B);
assertThat(this.mds.getAttributes(this.someMethodInteger, MockService.class)).isEqualTo(this.ROLE_B);
}
@Test
public void methodsWithDifferentArgumentsAreMatchedCorrectly() {
mds.addSecureMethod(MockService.class, someMethodInteger, ROLE_A);
mds.addSecureMethod(MockService.class, someMethodString, ROLE_B);
this.mds.addSecureMethod(MockService.class, this.someMethodInteger, this.ROLE_A);
this.mds.addSecureMethod(MockService.class, this.someMethodString, this.ROLE_B);
assertThat(mds.getAttributes(someMethodInteger, MockService.class)).isEqualTo(ROLE_A);
assertThat(mds.getAttributes(someMethodString, MockService.class)).isEqualTo(ROLE_B);
assertThat(this.mds.getAttributes(this.someMethodInteger, MockService.class)).isEqualTo(this.ROLE_A);
assertThat(this.mds.getAttributes(this.someMethodString, MockService.class)).isEqualTo(this.ROLE_B);
}
@SuppressWarnings("unused")

View File

@@ -64,14 +64,14 @@ public class MethodInvocationPrivilegeEvaluatorTests {
@Before
public final void setUp() {
SecurityContextHolder.clearContext();
interceptor = new MethodSecurityInterceptor();
token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING");
adm = mock(AccessDecisionManager.class);
this.interceptor = new MethodSecurityInterceptor();
this.token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING");
this.adm = mock(AccessDecisionManager.class);
AuthenticationManager authman = mock(AuthenticationManager.class);
mds = mock(MethodSecurityMetadataSource.class);
interceptor.setAccessDecisionManager(adm);
interceptor.setAuthenticationManager(authman);
interceptor.setSecurityMetadataSource(mds);
this.mds = mock(MethodSecurityMetadataSource.class);
this.interceptor.setAccessDecisionManager(this.adm);
this.interceptor.setAuthenticationManager(authman);
this.interceptor.setSecurityMetadataSource(this.mds);
}
@Test
@@ -80,12 +80,12 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
when(mds.getAttributes(mi)).thenReturn(role);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
mipe.setSecurityInterceptor(interceptor);
mipe.setSecurityInterceptor(this.interceptor);
mipe.afterPropertiesSet();
assertThat(mipe.isAllowed(mi, token)).isTrue();
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
}
@Test
@@ -93,10 +93,10 @@ public class MethodInvocationPrivilegeEvaluatorTests {
final MethodInvocation mi = MethodInvocationUtils.createFromClass(new OtherTargetObject(), ITargetObject.class,
"makeLowerCase", new Class[] { String.class }, new Object[] { "Hello world" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
assertThat(mipe.isAllowed(mi, token)).isTrue();
assertThat(mipe.isAllowed(mi, this.token)).isTrue();
}
@Test
@@ -104,11 +104,11 @@ public class MethodInvocationPrivilegeEvaluatorTests {
Object object = new TargetObject();
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, token)).isFalse();
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}
@Test
@@ -117,11 +117,11 @@ public class MethodInvocationPrivilegeEvaluatorTests {
"makeLowerCase", new Class[] { String.class }, new Object[] { "helloWorld" });
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
mipe.setSecurityInterceptor(interceptor);
when(mds.getAttributes(mi)).thenReturn(role);
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
mipe.setSecurityInterceptor(this.interceptor);
when(this.mds.getAttributes(mi)).thenReturn(this.role);
doThrow(new AccessDeniedException("rejected")).when(this.adm).decide(this.token, mi, this.role);
assertThat(mipe.isAllowed(mi, token)).isFalse();
assertThat(mipe.isAllowed(mi, this.token)).isFalse();
}
}

View File

@@ -42,11 +42,11 @@ public class MockMethodInvocation implements MethodInvocation {
}
public Object[] getArguments() {
return arguments;
return this.arguments;
}
public Method getMethod() {
return method;
return this.method;
}
public AccessibleObject getStaticPart() {
@@ -54,7 +54,7 @@ public class MockMethodInvocation implements MethodInvocation {
}
public Object getThis() {
return targetObject;
return this.targetObject;
}
public Object proceed() {

View File

@@ -47,13 +47,13 @@ public class DelegatingMethodSecurityMetadataSourceTests {
when(delegate.getAttributes(ArgumentMatchers.<Method>any(), ArgumentMatchers.any(Class.class)))
.thenReturn(null);
sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation(null, String.class.getMethod("toString"));
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
assertThat(this.mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case
assertThat(mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
assertThat(this.mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
}
@Test
@@ -65,14 +65,15 @@ public class DelegatingMethodSecurityMetadataSourceTests {
Method toString = String.class.getMethod("toString");
when(delegate.getAttributes(toString, String.class)).thenReturn(attributes);
sources.add(delegate);
mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(mds.getAllConfigAttributes().isEmpty()).isTrue();
this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue();
MethodInvocation mi = new SimpleMethodInvocation("", toString);
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
assertThat(this.mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case
assertThat(mds.getAttributes(mi)).isSameAs(attributes);
assertThat(mds.getAttributes(new SimpleMethodInvocation(null, String.class.getMethod("length")))).isEmpty();
assertThat(this.mds.getAttributes(mi)).isSameAs(attributes);
assertThat(this.mds.getAttributes(new SimpleMethodInvocation(null, String.class.getMethod("length"))))
.isEmpty();
}
}

View File

@@ -37,23 +37,23 @@ public class PreInvocationAuthorizationAdviceVoterTests {
@Before
public void setUp() {
voter = new PreInvocationAuthorizationAdviceVoter(authorizationAdvice);
this.voter = new PreInvocationAuthorizationAdviceVoter(this.authorizationAdvice);
}
@Test
public void supportsMethodInvocation() {
assertThat(voter.supports(MethodInvocation.class)).isTrue();
assertThat(this.voter.supports(MethodInvocation.class)).isTrue();
}
// SEC-2031
@Test
public void supportsProxyMethodInvocation() {
assertThat(voter.supports(ProxyMethodInvocation.class)).isTrue();
assertThat(this.voter.supports(ProxyMethodInvocation.class)).isTrue();
}
@Test
public void supportsMethodInvocationAdapter() {
assertThat(voter.supports(MethodInvocationAdapter.class)).isTrue();
assertThat(this.voter.supports(MethodInvocationAdapter.class)).isTrue();
}
}

View File

@@ -45,23 +45,23 @@ public class AbstractAclVoterTests {
@Test
public void supportsMethodInvocations() {
assertThat(voter.supports(MethodInvocation.class)).isTrue();
assertThat(voter.supports(String.class)).isFalse();
assertThat(this.voter.supports(MethodInvocation.class)).isTrue();
assertThat(this.voter.supports(String.class)).isFalse();
}
@Test
public void expectedDomainObjectArgumentIsReturnedFromMethodInvocation() {
voter.setProcessDomainObjectClass(String.class);
this.voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(), "methodTakingAString", "The Argument");
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
assertThat(this.voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@Test
public void correctArgumentIsSelectedFromMultipleArgs() {
voter.setProcessDomainObjectClass(String.class);
this.voter.setProcessDomainObjectClass(String.class);
MethodInvocation mi = MethodInvocationUtils.create(new TestClass(), "methodTakingAListAndAString",
new ArrayList<>(), "The Argument");
assertThat(voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
assertThat(this.voter.getDomainObjectInstance(mi)).isEqualTo("The Argument");
}
@SuppressWarnings("unused")

View File

@@ -57,59 +57,65 @@ public class AffirmativeBasedTests {
@SuppressWarnings("unchecked")
public void setup() {
grant = mock(AccessDecisionVoter.class);
abstain = mock(AccessDecisionVoter.class);
deny = mock(AccessDecisionVoter.class);
this.grant = mock(AccessDecisionVoter.class);
this.abstain = mock(AccessDecisionVoter.class);
this.deny = mock(AccessDecisionVoter.class);
when(grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
when(this.grant.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_GRANTED);
when(abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
when(this.abstain.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_ABSTAIN);
when(deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
when(this.deny.vote(any(Authentication.class), any(Object.class), any(List.class)))
.thenReturn(AccessDecisionVoter.ACCESS_DENIED);
}
@Test
public void oneAffirmativeVoteOneDenyVoteOneAbstainVoteGrantsAccess() throws Exception {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, deny, abstain));
mgr.afterPropertiesSet();
mgr.decide(user, new Object(), attrs);
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.grant, this.deny, this.abstain));
this.mgr.afterPropertiesSet();
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test
public void oneDenyVoteOneAbstainVoteOneAffirmativeVoteGrantsAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, grant));
mgr.decide(user, new Object(), attrs);
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.grant));
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test
public void oneAffirmativeVoteTwoAbstainVotesGrantsAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(grant, abstain, abstain));
mgr.decide(user, new Object(), attrs);
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.grant, this.abstain, this.abstain));
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test(expected = AccessDeniedException.class)
public void oneDenyVoteTwoAbstainVotesDeniesAccess() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(deny, abstain, abstain));
mgr.decide(user, new Object(), attrs);
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.deny, this.abstain, this.abstain));
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test(expected = AccessDeniedException.class)
public void onlyAbstainVotesDeniesAccessWithDefault() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
assertThat(!this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
mgr.decide(user, new Object(), attrs);
this.mgr.decide(this.user, new Object(), this.attrs);
}
@Test
public void testThreeAbstainVotesGrantsAccessIfAllowIfAllAbstainDecisionsIsSet() {
mgr = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(abstain, abstain, abstain));
mgr.setAllowIfAllAbstainDecisions(true);
assertThat(mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
this.mgr = new AffirmativeBased(
Arrays.<AccessDecisionVoter<? extends Object>>asList(this.abstain, this.abstain, this.abstain));
this.mgr.setAllowIfAllAbstainDecisions(true);
assertThat(this.mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check changed
mgr.decide(user, new Object(), attrs);
this.mgr.decide(this.user, new Object(), this.attrs);
}
}

View File

@@ -30,7 +30,7 @@ public class SomeDomainObject {
}
public String getParent() {
return "parentOf" + identity;
return "parentOf" + this.identity;
}
}

View File

@@ -43,21 +43,21 @@ public class AbstractAuthenticationTokenTests {
@Before
public final void setUp() {
authorities = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
this.authorities = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
}
@Test(expected = UnsupportedOperationException.class)
public void testAuthoritiesAreImmutable() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
List<GrantedAuthority> gotAuthorities = (List<GrantedAuthority>) token.getAuthorities();
assertThat(gotAuthorities).isNotSameAs(authorities);
assertThat(gotAuthorities).isNotSameAs(this.authorities);
gotAuthorities.set(0, new SimpleGrantedAuthority("ROLE_SUPER_USER"));
}
@Test
public void testGetters() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
assertThat(token.getPrincipal()).isEqualTo("Test");
assertThat(token.getCredentials()).isEqualTo("Password");
assertThat(token.getName()).isEqualTo("Test");
@@ -65,8 +65,8 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testHashCode() {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", this.authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", this.authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl(null, null, AuthorityUtils.NO_AUTHORITIES);
assertThat(token2.hashCode()).isEqualTo(token1.hashCode());
assertThat(token1.hashCode() != token3.hashCode()).isTrue();
@@ -78,14 +78,14 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testObjectsEquals() {
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token1 = new MockAuthenticationImpl("Test", "Password", this.authorities);
MockAuthenticationImpl token2 = new MockAuthenticationImpl("Test", "Password", this.authorities);
assertThat(token2).isEqualTo(token1);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test", "Password_Changed", authorities);
MockAuthenticationImpl token3 = new MockAuthenticationImpl("Test", "Password_Changed", this.authorities);
assertThat(!token1.equals(token3)).isTrue();
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", authorities);
MockAuthenticationImpl token4 = new MockAuthenticationImpl("Test_Changed", "Password", this.authorities);
assertThat(!token1.equals(token4)).isTrue();
MockAuthenticationImpl token5 = new MockAuthenticationImpl("Test", "Password",
@@ -105,7 +105,7 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testSetAuthenticated() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
assertThat(!token.isAuthenticated()).isTrue();
token.setAuthenticated(true);
assertThat(token.isAuthenticated()).isTrue();
@@ -113,7 +113,7 @@ public class AbstractAuthenticationTokenTests {
@Test
public void testToStringWithAuthorities() {
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl("Test", "Password", this.authorities);
assertThat(token.toString().lastIndexOf("ROLE_TWO") != -1).isTrue();
}
@@ -130,7 +130,7 @@ public class AbstractAuthenticationTokenTests {
AuthenticatedPrincipal principal = mock(AuthenticatedPrincipal.class);
when(principal.getName()).thenReturn(principalName);
MockAuthenticationImpl token = new MockAuthenticationImpl(principal, "Password", authorities);
MockAuthenticationImpl token = new MockAuthenticationImpl(principal, "Password", this.authorities);
assertThat(token.getName()).isEqualTo(principalName);
verify(principal, times(1)).getName();
}

View File

@@ -52,30 +52,30 @@ public class DefaultAuthenticationEventPublisherTests {
@Test
public void expectedDefaultMappingsAreSatisfied() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
this.publisher.setApplicationEventPublisher(appPublisher);
Authentication a = mock(Authentication.class);
Exception cause = new Exception();
Object extraInfo = new Object();
publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
publisher.publishAuthenticationFailure(new DisabledException(""), a);
publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
publisher.publishAuthenticationFailure(new LockedException(""), a);
publisher.publishAuthenticationFailure(new LockedException("", cause), a);
publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
this.publisher.publishAuthenticationFailure(new LockedException(""), a);
this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
@@ -88,48 +88,49 @@ public class DefaultAuthenticationEventPublisherTests {
@Test
public void authenticationSuccessIsPublished() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationSuccess(mock(Authentication.class));
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
publisher.setApplicationEventPublisher(null);
this.publisher.setApplicationEventPublisher(null);
// Should be ignored with null app publisher
publisher.publishAuthenticationSuccess(mock(Authentication.class));
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
}
@Test
public void additionalExceptionMappingsAreSupported() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
publisher.setAdditionalExceptionMappings(p);
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test(expected = RuntimeException.class)
public void missingEventClassExceptionCausesException() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), "NoSuchClass");
publisher.setAdditionalExceptionMappings(p);
this.publisher.setAdditionalExceptionMappings(p);
}
@Test
public void unknownFailureExceptionIsIgnored() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
publisher.setAdditionalExceptionMappings(p);
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new AuthenticationException("") {
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verifyZeroInteractions(appPublisher);
}
@@ -137,61 +138,63 @@ public class DefaultAuthenticationEventPublisherTests {
@Test(expected = IllegalArgumentException.class)
public void emptyMapCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
}
@Test(expected = IllegalArgumentException.class)
public void missingExceptionClassCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(null, AuthenticationFailureLockedEvent.class);
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
}
@Test(expected = IllegalArgumentException.class)
public void missingEventClassAsMapValueCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(LockedException.class, null);
publisher = new DefaultAuthenticationEventPublisher();
publisher.setAdditionalExceptionMappings(mappings);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setAdditionalExceptionMappings(mappings);
}
@Test
public void additionalExceptionMappingsUsingMapAreSupported() {
publisher = new DefaultAuthenticationEventPublisher();
this.publisher = new DefaultAuthenticationEventPublisher();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(MockAuthenticationException.class, AuthenticationFailureDisabledEvent.class);
publisher.setAdditionalExceptionMappings(mappings);
this.publisher.setAdditionalExceptionMappings(mappings);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test(expected = IllegalArgumentException.class)
public void defaultAuthenticationFailureEventClassSetNullThen() {
publisher = new DefaultAuthenticationEventPublisher();
publisher.setDefaultAuthenticationFailureEvent(null);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(null);
}
@Test
public void defaultAuthenticationFailureEventIsPublished() {
publisher = new DefaultAuthenticationEventPublisher();
publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
publisher.setApplicationEventPublisher(appPublisher);
publisher.publishAuthenticationFailure(new AuthenticationException("") {
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
@Test(expected = RuntimeException.class)
public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() {
publisher = new DefaultAuthenticationEventPublisher();
publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class);
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class);
}
private static final class AuthenticationFailureEventWithoutAppropriateConstructor

View File

@@ -47,7 +47,7 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Before
public void setup() {
manager = new ReactiveAuthenticationManagerAdapter(delegate);
this.manager = new ReactiveAuthenticationManagerAdapter(this.delegate);
}
@Test(expected = IllegalArgumentException.class)
@@ -62,28 +62,28 @@ public class ReactiveAuthenticationManagerAdapterTests {
@Test
public void authenticateWhenSuccessThenSuccess() {
when(delegate.authenticate(any())).thenReturn(authentication);
when(authentication.isAuthenticated()).thenReturn(true);
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
when(this.authentication.isAuthenticated()).thenReturn(true);
Authentication result = manager.authenticate(authentication).block();
Authentication result = this.manager.authenticate(this.authentication).block();
assertThat(result).isEqualTo(authentication);
assertThat(result).isEqualTo(this.authentication);
}
@Test
public void authenticateWhenReturnNotAuthenticatedThenError() {
when(delegate.authenticate(any())).thenReturn(authentication);
when(this.delegate.authenticate(any())).thenReturn(this.authentication);
Authentication result = manager.authenticate(authentication).block();
Authentication result = this.manager.authenticate(this.authentication).block();
assertThat(result).isNull();
}
@Test
public void authenticateWhenBadCredentialsThenError() {
when(delegate.authenticate(any())).thenThrow(new BadCredentialsException("Failed"));
when(this.delegate.authenticate(any())).thenThrow(new BadCredentialsException("Failed"));
Mono<Authentication> result = manager.authenticate(authentication);
Mono<Authentication> result = this.manager.authenticate(this.authentication);
StepVerifier.create(result).expectError(BadCredentialsException.class).verify();
}

View File

@@ -56,9 +56,9 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Before
public void setup() {
manager = new UserDetailsRepositoryReactiveAuthenticationManager(repository);
username = "user";
password = "pass";
this.manager = new UserDetailsRepositoryReactiveAuthenticationManager(this.repository);
this.username = "user";
this.password = "pass";
}
@Test(expected = IllegalArgumentException.class)
@@ -69,10 +69,11 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
@Test
public void authenticateWhenUserNotFoundThenBadCredentials() {
when(repository.findByUsername(username)).thenReturn(Mono.empty());
when(this.repository.findByUsername(this.username)).thenReturn(Mono.empty());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Mono<Authentication> authentication = manager.authenticate(token);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
Mono<Authentication> authentication = this.manager.authenticate(token);
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
@@ -85,11 +86,11 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password + "INVALID");
Mono<Authentication> authentication = manager.authenticate(token);
Mono<Authentication> authentication = this.manager.authenticate(token);
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
@@ -102,10 +103,11 @@ public class ReactiveUserDetailsServiceAuthenticationManagerTests {
.roles("USER")
.build();
// @formatter:on
when(repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
when(this.repository.findByUsername(user.getUsername())).thenReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = manager.authenticate(token).block();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.username,
this.password);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
}

View File

@@ -705,7 +705,7 @@ public class DaoAuthenticationProviderTests {
public UserDetails loadUserByUsername(String username) {
if ("rod".equals(username)) {
return new User("rod", password, true, true, true, true, ROLES_12);
return new User("rod", this.password, true, true, true, true, ROLES_12);
}
throw new UsernameNotFoundException("Could not find: " + username);
}

View File

@@ -29,15 +29,15 @@ public class MockUserCache implements UserCache {
private Map<String, UserDetails> cache = new HashMap<>();
public UserDetails getUserFromCache(String username) {
return cache.get(username);
return this.cache.get(username);
}
public void putUserInCache(UserDetails user) {
cache.put(user.getUsername(), user);
this.cache.put(user.getUsername(), user);
}
public void removeUserFromCache(String username) {
cache.remove(username);
this.cache.remove(username);
}
}

View File

@@ -66,54 +66,54 @@ public class DefaultJaasAuthenticationProviderTests {
@Before
public void setUp() throws Exception {
Configuration configuration = mock(Configuration.class);
publisher = mock(ApplicationEventPublisher.class);
log = mock(Log.class);
provider = new DefaultJaasAuthenticationProvider();
provider.setConfiguration(configuration);
provider.setApplicationEventPublisher(publisher);
provider.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
provider.afterPropertiesSet();
this.publisher = mock(ApplicationEventPublisher.class);
this.log = mock(Log.class);
this.provider = new DefaultJaasAuthenticationProvider();
this.provider.setConfiguration(configuration);
this.provider.setApplicationEventPublisher(this.publisher);
this.provider.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
this.provider.afterPropertiesSet();
AppConfigurationEntry[] aces = new AppConfigurationEntry[] {
new AppConfigurationEntry(TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
Collections.<String, Object>emptyMap()) };
when(configuration.getAppConfigurationEntry(provider.getLoginContextName())).thenReturn(aces);
token = new UsernamePasswordAuthenticationToken("user", "password");
ReflectionTestUtils.setField(provider, "log", log);
when(configuration.getAppConfigurationEntry(this.provider.getLoginContextName())).thenReturn(aces);
this.token = new UsernamePasswordAuthenticationToken("user", "password");
ReflectionTestUtils.setField(this.provider, "log", this.log);
}
@Test(expected = IllegalArgumentException.class)
public void afterPropertiesSetNullConfiguration() throws Exception {
provider.setConfiguration(null);
provider.afterPropertiesSet();
this.provider.setConfiguration(null);
this.provider.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void afterPropertiesSetNullAuthorityGranters() throws Exception {
provider.setAuthorityGranters(null);
provider.afterPropertiesSet();
this.provider.setAuthorityGranters(null);
this.provider.afterPropertiesSet();
}
@Test
public void authenticateUnsupportedAuthentication() {
assertThat(provider.authenticate(new TestingAuthenticationToken("user", "password"))).isNull();
assertThat(this.provider.authenticate(new TestingAuthenticationToken("user", "password"))).isNull();
}
@Test
public void authenticateSuccess() {
Authentication auth = provider.authenticate(token);
assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
assertThat(auth.getCredentials()).isEqualTo(token.getCredentials());
Authentication auth = this.provider.authenticate(this.token);
assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal());
assertThat(auth.getCredentials()).isEqualTo(this.token.getCredentials());
assertThat(auth.isAuthenticated()).isEqualTo(true);
assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false);
verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class));
verifyNoMoreInteractions(publisher);
verify(this.publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class));
verifyNoMoreInteractions(this.publisher);
}
@Test
public void authenticateBadPassword() {
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException success) {
@@ -125,7 +125,7 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void authenticateBadUser() {
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException success) {
@@ -145,7 +145,7 @@ public class DefaultJaasAuthenticationProviderTests {
when(securityContext.getAuthentication()).thenReturn(token);
when(token.getLoginContext()).thenReturn(context);
provider.onApplicationEvent(event);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
@@ -158,10 +158,10 @@ public class DefaultJaasAuthenticationProviderTests {
public void logoutNullSession() {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
provider.handleLogout(event);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(log).debug(anyString());
verify(this.log).debug(anyString());
verifyNoMoreInteractions(event);
}
@@ -172,7 +172,7 @@ public class DefaultJaasAuthenticationProviderTests {
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
provider.handleLogout(event);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
@@ -186,9 +186,9 @@ public class DefaultJaasAuthenticationProviderTests {
SecurityContext securityContext = mock(SecurityContext.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
when(securityContext.getAuthentication()).thenReturn(this.token);
provider.handleLogout(event);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
@@ -205,7 +205,7 @@ public class DefaultJaasAuthenticationProviderTests {
when(event.getSecurityContexts()).thenReturn(Arrays.asList(securityContext));
when(securityContext.getAuthentication()).thenReturn(token);
provider.onApplicationEvent(event);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
@@ -226,23 +226,23 @@ public class DefaultJaasAuthenticationProviderTests {
when(token.getLoginContext()).thenReturn(context);
doThrow(loginException).when(context).logout();
provider.onApplicationEvent(event);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(log).warn(anyString(), eq(loginException));
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
}
@Test
public void publishNullPublisher() {
provider.setApplicationEventPublisher(null);
this.provider.setApplicationEventPublisher(null);
AuthenticationException ae = new BadCredentialsException("Failed to login");
provider.publishFailureEvent(token, ae);
provider.publishSuccessEvent(token);
this.provider.publishFailureEvent(this.token, ae);
this.provider.publishSuccessEvent(this.token);
}
@Test
@@ -251,10 +251,10 @@ public class DefaultJaasAuthenticationProviderTests {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(resName);
context.registerShutdownHook();
try {
provider = context.getBean(DefaultJaasAuthenticationProvider.class);
Authentication auth = provider.authenticate(token);
this.provider = context.getBean(DefaultJaasAuthenticationProvider.class);
Authentication auth = this.provider.authenticate(this.token);
assertThat(auth.isAuthenticated()).isEqualTo(true);
assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
assertThat(auth.getPrincipal()).isEqualTo(this.token.getPrincipal());
}
finally {
context.close();
@@ -264,10 +264,10 @@ public class DefaultJaasAuthenticationProviderTests {
private void verifyFailedLogin() {
ArgumentCaptor<JaasAuthenticationFailedEvent> event = ArgumentCaptor
.forClass(JaasAuthenticationFailedEvent.class);
verify(publisher).publishEvent(event.capture());
verify(this.publisher).publishEvent(event.capture());
assertThat(event.getValue()).isInstanceOf(JaasAuthenticationFailedEvent.class);
assertThat(event.getValue().getException()).isNotNull();
verifyNoMoreInteractions(publisher);
verifyNoMoreInteractions(this.publisher);
}
}

View File

@@ -66,39 +66,39 @@ public class JaasAuthenticationProviderTests {
@Before
public void setUp() {
String resName = "/" + getClass().getName().replace('.', '/') + ".xml";
context = new ClassPathXmlApplicationContext(resName);
eventCheck = (JaasEventCheck) context.getBean("eventCheck");
jaasProvider = (JaasAuthenticationProvider) context.getBean("jaasAuthenticationProvider");
this.context = new ClassPathXmlApplicationContext(resName);
this.eventCheck = (JaasEventCheck) this.context.getBean("eventCheck");
this.jaasProvider = (JaasAuthenticationProvider) this.context.getBean("jaasAuthenticationProvider");
}
@Test
public void testBadPassword() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException e) {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull();
}
@Test
public void testBadUser() {
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException e) {
}
assertThat(eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
assertThat(eventCheck.successEvent).as("Success event was fired").isNull();
assertThat(this.eventCheck.successEvent).as("Success event was fired").isNull();
}
@Test
@@ -115,10 +115,10 @@ public class JaasAuthenticationProviderTests {
@Test
public void detectsMissingLoginConfig() throws Exception {
JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
myJaasProvider.setApplicationEventPublisher(context);
myJaasProvider.setAuthorityGranters(jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(jaasProvider.getLoginContextName());
myJaasProvider.setApplicationEventPublisher(this.context);
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
try {
myJaasProvider.afterPropertiesSet();
@@ -151,11 +151,11 @@ public class JaasAuthenticationProviderTests {
pw.close();
JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
myJaasProvider.setApplicationEventPublisher(context);
myJaasProvider.setApplicationEventPublisher(this.context);
myJaasProvider.setLoginConfig(new FileSystemResource(configFile));
myJaasProvider.setAuthorityGranters(jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(jaasProvider.getLoginContextName());
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
myJaasProvider.afterPropertiesSet();
}
@@ -163,10 +163,10 @@ public class JaasAuthenticationProviderTests {
@Test
public void detectsMissingLoginContextName() throws Exception {
JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
myJaasProvider.setApplicationEventPublisher(context);
myJaasProvider.setAuthorityGranters(jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginConfig(jaasProvider.getLoginConfig());
myJaasProvider.setApplicationEventPublisher(this.context);
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig());
myJaasProvider.setLoginContextName(null);
try {
@@ -193,14 +193,14 @@ public class JaasAuthenticationProviderTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_ONE"));
assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = jaasProvider.authenticate(token);
Authentication auth = this.jaasProvider.authenticate(token);
assertThat(jaasProvider.getAuthorityGranters()).isNotNull();
assertThat(jaasProvider.getCallbackHandlers()).isNotNull();
assertThat(jaasProvider.getLoginConfig()).isNotNull();
assertThat(jaasProvider.getLoginContextName()).isNotNull();
assertThat(this.jaasProvider.getAuthorityGranters()).isNotNull();
assertThat(this.jaasProvider.getCallbackHandlers()).isNotNull();
assertThat(this.jaasProvider.getLoginConfig()).isNotNull();
assertThat(this.jaasProvider.getLoginContextName()).isNotNull();
Collection<? extends GrantedAuthority> list = auth.getAuthorities();
Set<String> set = AuthorityUtils.authorityListToSet(list);
@@ -222,24 +222,24 @@ public class JaasAuthenticationProviderTests {
assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull();
assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal")
assertThat(this.eventCheck.successEvent).as("Success event should be fired").isNotNull();
assertThat(this.eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal")
.isEqualTo(auth);
assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull();
assertThat(this.eventCheck.failedEvent).as("Failure event should not be fired").isNull();
}
@Test
public void testGetApplicationEventPublisher() {
assertThat(jaasProvider.getApplicationEventPublisher()).isNotNull();
assertThat(this.jaasProvider.getApplicationEventPublisher()).isNotNull();
}
@Test
public void testLoginExceptionResolver() {
assertThat(jaasProvider.getLoginExceptionResolver()).isNotNull();
jaasProvider.setLoginExceptionResolver(e -> new LockedException("This is just a test!"));
assertThat(this.jaasProvider.getLoginExceptionResolver()).isNotNull();
this.jaasProvider.setLoginExceptionResolver(e -> new LockedException("This is just a test!"));
try {
jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (LockedException e) {
}
@@ -250,7 +250,7 @@ public class JaasAuthenticationProviderTests {
@Test
public void testLogout() throws Exception {
MockLoginContext loginContext = new MockLoginContext(jaasProvider.getLoginContextName());
MockLoginContext loginContext = new MockLoginContext(this.jaasProvider.getLoginContextName());
JaasAuthenticationToken token = new JaasAuthenticationToken(null, null, loginContext);
@@ -260,7 +260,7 @@ public class JaasAuthenticationProviderTests {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
when(event.getSecurityContexts()).thenReturn(Arrays.asList(context));
jaasProvider.handleLogout(event);
this.jaasProvider.handleLogout(event);
assertThat(loginContext.loggedOut).isTrue();
}
@@ -269,18 +269,17 @@ public class JaasAuthenticationProviderTests {
public void testNullDefaultAuthorities() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
assertThat(this.jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
Authentication auth = jaasProvider.authenticate(token);
Authentication auth = this.jaasProvider.authenticate(token);
assertThat(auth.getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned")
.hasSize(2);
}
@Test
public void testUnsupportedAuthenticationObjectReturnsNull() {
assertThat(
jaasProvider.authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES)))
.isNull();
assertThat(this.jaasProvider
.authenticate(new TestingAuthenticationToken("foo", "bar", AuthorityUtils.NO_AUTHORITIES))).isNull();
}
private static class MockLoginContext extends LoginContext {

View File

@@ -32,11 +32,11 @@ public class JaasEventCheck implements ApplicationListener<JaasAuthenticationEve
public void onApplicationEvent(JaasAuthenticationEvent event) {
if (event instanceof JaasAuthenticationFailedEvent) {
failedEvent = (JaasAuthenticationFailedEvent) event;
this.failedEvent = (JaasAuthenticationFailedEvent) event;
}
if (event instanceof JaasAuthenticationSuccessEvent) {
successEvent = (JaasAuthenticationSuccessEvent) event;
this.successEvent = (JaasAuthenticationSuccessEvent) event;
}
}

View File

@@ -57,8 +57,8 @@ public class TestLoginModule implements LoginModule {
callbackHandler.handle(new Callback[] { textCallback, nameCallback, passwordCallback });
password = new String(passwordCallback.getPassword());
user = nameCallback.getName();
this.password = new String(passwordCallback.getPassword());
this.user = nameCallback.getName();
}
catch (Exception e) {
throw new RuntimeException(e);
@@ -66,17 +66,17 @@ public class TestLoginModule implements LoginModule {
}
public boolean login() throws LoginException {
if (!user.equals("user")) {
if (!this.user.equals("user")) {
throw new LoginException("Bad User");
}
if (!password.equals("password")) {
if (!this.password.equals("password")) {
throw new LoginException("Bad Password");
}
subject.getPrincipals().add(() -> "TEST_PRINCIPAL");
this.subject.getPrincipals().add(() -> "TEST_PRINCIPAL");
subject.getPrincipals().add(() -> "NULL_PRINCIPAL");
this.subject.getPrincipals().add(() -> "NULL_PRINCIPAL");
return true;
}

View File

@@ -45,23 +45,23 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
when(authentication.isAuthenticated()).thenReturn(true);
when(this.authentication.isAuthenticated()).thenReturn(true);
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
@Test
public void checkWhenNotAuthenticatedThenReturnFalse() {
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenEmptyThenReturnFalse() {
boolean granted = manager.check(Mono.empty(), null).block().isGranted();
boolean granted = this.manager.check(Mono.empty(), null).block().isGranted();
assertThat(granted).isFalse();
}
@@ -70,14 +70,14 @@ public class AuthenticatedReactiveAuthorizationManagerTests {
public void checkWhenAnonymousAuthenticatedThenReturnFalse() {
AnonymousAuthenticationToken anonymousAuthenticationToken = mock(AnonymousAuthenticationToken.class);
boolean granted = manager.check(Mono.just(anonymousAuthenticationToken), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(anonymousAuthenticationToken), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenErrorThenError() {
Mono<AuthorizationDecision> result = manager.check(Mono.error(new RuntimeException("ooops")), null);
Mono<AuthorizationDecision> result = this.manager.check(Mono.error(new RuntimeException("ooops")), null);
StepVerifier.create(result).expectError().verify();
}

View File

@@ -45,89 +45,90 @@ public class AuthorityReactiveAuthorizationManagerTests {
@Test
public void checkWhenHasAuthorityAndNotAuthenticatedThenReturnFalse() {
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenHasAuthorityAndEmptyThenReturnFalse() {
boolean granted = manager.check(Mono.empty(), null).block().isGranted();
boolean granted = this.manager.check(Mono.empty(), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenHasAuthorityAndErrorThenError() {
Mono<AuthorizationDecision> result = manager.check(Mono.error(new RuntimeException("ooops")), null);
Mono<AuthorizationDecision> result = this.manager.check(Mono.error(new RuntimeException("ooops")), null);
StepVerifier.create(result).expectError().verify();
}
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
when(authentication.isAuthenticated()).thenReturn(true);
when(authentication.getAuthorities()).thenReturn(Collections.emptyList());
when(this.authentication.isAuthenticated()).thenReturn(true);
when(this.authentication.getAuthorities()).thenReturn(Collections.emptyList());
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndWrongAuthoritiesThenReturnFalse() {
authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenHasAuthorityAndAuthorizedThenReturnTrue() {
authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
this.authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
@Test
public void checkWhenHasRoleAndAuthorizedThenReturnTrue() {
manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
this.manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
@Test
public void checkWhenHasRoleAndNotAuthorizedThenReturnFalse() {
manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
this.manager = AuthorityReactiveAuthorizationManager.hasRole("ADMIN");
this.authentication = new TestingAuthenticationToken("rob", "secret", "ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
@Test
public void checkWhenHasAnyRoleAndAuthorizedThenReturnTrue() {
manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_USER", "ROLE_AUDITING", "ROLE_ADMIN");
this.manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
this.authentication = new TestingAuthenticationToken("rob", "secret", "ROLE_USER", "ROLE_AUDITING",
"ROLE_ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
@Test
public void checkWhenHasAnyRoleAndNotAuthorizedThenReturnFalse() {
manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
authentication = new TestingAuthenticationToken("rob", "secret", "USER", "AUDITING", "ADMIN");
this.manager = AuthorityReactiveAuthorizationManager.hasAnyRole("GENERAL", "USER", "TEST");
this.authentication = new TestingAuthenticationToken("rob", "secret", "USER", "AUDITING", "ADMIN");
boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}

View File

@@ -52,7 +52,7 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Before
public final void setUpExecutorService() {
executor = create();
this.executor = create();
}
@Test(expected = IllegalArgumentException.class)
@@ -62,104 +62,104 @@ public abstract class AbstractDelegatingSecurityContextExecutorServiceTests
@Test
public void shutdown() {
executor.shutdown();
verify(delegate).shutdown();
this.executor.shutdown();
verify(this.delegate).shutdown();
}
@Test
public void shutdownNow() {
List<Runnable> result = executor.shutdownNow();
verify(delegate).shutdownNow();
assertThat(result).isEqualTo(delegate.shutdownNow()).isNotNull();
List<Runnable> result = this.executor.shutdownNow();
verify(this.delegate).shutdownNow();
assertThat(result).isEqualTo(this.delegate.shutdownNow()).isNotNull();
}
@Test
public void isShutdown() {
boolean result = executor.isShutdown();
verify(delegate).isShutdown();
assertThat(result).isEqualTo(delegate.isShutdown()).isNotNull();
boolean result = this.executor.isShutdown();
verify(this.delegate).isShutdown();
assertThat(result).isEqualTo(this.delegate.isShutdown()).isNotNull();
}
@Test
public void isTerminated() {
boolean result = executor.isTerminated();
verify(delegate).isTerminated();
assertThat(result).isEqualTo(delegate.isTerminated()).isNotNull();
boolean result = this.executor.isTerminated();
verify(this.delegate).isTerminated();
assertThat(result).isEqualTo(this.delegate.isTerminated()).isNotNull();
}
@Test
public void awaitTermination() throws InterruptedException {
boolean result = executor.awaitTermination(1, TimeUnit.SECONDS);
verify(delegate).awaitTermination(1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(delegate.awaitTermination(1, TimeUnit.SECONDS)).isNotNull();
boolean result = this.executor.awaitTermination(1, TimeUnit.SECONDS);
verify(this.delegate).awaitTermination(1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.delegate.awaitTermination(1, TimeUnit.SECONDS)).isNotNull();
}
@Test
public void submitCallable() {
when(delegate.submit(wrappedCallable)).thenReturn(expectedFutureObject);
Future<Object> result = executor.submit(callable);
verify(delegate).submit(wrappedCallable);
assertThat(result).isEqualTo(expectedFutureObject);
when(this.delegate.submit(this.wrappedCallable)).thenReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.callable);
verify(this.delegate).submit(this.wrappedCallable);
assertThat(result).isEqualTo(this.expectedFutureObject);
}
@Test
public void submitRunnableWithResult() {
when(delegate.submit(wrappedRunnable, resultArg)).thenReturn(expectedFutureObject);
Future<Object> result = executor.submit(runnable, resultArg);
verify(delegate).submit(wrappedRunnable, resultArg);
assertThat(result).isEqualTo(expectedFutureObject);
when(this.delegate.submit(this.wrappedRunnable, this.resultArg)).thenReturn(this.expectedFutureObject);
Future<Object> result = this.executor.submit(this.runnable, this.resultArg);
verify(this.delegate).submit(this.wrappedRunnable, this.resultArg);
assertThat(result).isEqualTo(this.expectedFutureObject);
}
@Test
@SuppressWarnings("unchecked")
public void submitRunnable() {
when((Future<Object>) delegate.submit(wrappedRunnable)).thenReturn(expectedFutureObject);
Future<?> result = executor.submit(runnable);
verify(delegate).submit(wrappedRunnable);
assertThat(result).isEqualTo(expectedFutureObject);
when((Future<Object>) this.delegate.submit(this.wrappedRunnable)).thenReturn(this.expectedFutureObject);
Future<?> result = this.executor.submit(this.runnable);
verify(this.delegate).submit(this.wrappedRunnable);
assertThat(result).isEqualTo(this.expectedFutureObject);
}
@Test
@SuppressWarnings("unchecked")
public void invokeAll() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult);
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable));
verify(delegate).invokeAll(wrappedCallables);
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables)).thenReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable));
verify(this.delegate).invokeAll(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
}
@Test
@SuppressWarnings("unchecked")
public void invokeAllTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
List<Future<Object>> result = executor.invokeAll(Arrays.asList(callable), 1, TimeUnit.SECONDS);
verify(delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAll(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
List<Future<Object>> result = this.executor.invokeAll(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAll(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
}
@Test
@SuppressWarnings("unchecked")
public void invokeAny() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAny(wrappedCallables)).thenReturn(exectedResult);
Object result = executor.invokeAny(Arrays.asList(callable));
verify(delegate).invokeAny(wrappedCallables);
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables)).thenReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable));
verify(this.delegate).invokeAny(wrappedCallables);
assertThat(result).isEqualTo(exectedResult);
}
@Test
@SuppressWarnings("unchecked")
public void invokeAnyTimeout() throws Exception {
List<Future<Object>> exectedResult = Arrays.asList(expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(wrappedCallable);
when(delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
Object result = executor.invokeAny(Arrays.asList(callable), 1, TimeUnit.SECONDS);
verify(delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
List<Future<Object>> exectedResult = Arrays.asList(this.expectedFutureObject);
List<Callable<Object>> wrappedCallables = Arrays.asList(this.wrappedCallable);
when(this.delegate.invokeAny(wrappedCallables, 1, TimeUnit.SECONDS)).thenReturn(exectedResult);
Object result = this.executor.invokeAny(Arrays.asList(this.callable), 1, TimeUnit.SECONDS);
verify(this.delegate).invokeAny(wrappedCallables, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(exectedResult);
}

View File

@@ -52,13 +52,13 @@ public abstract class AbstractDelegatingSecurityContextExecutorTests
@Test
public void execute() {
executor = create();
executor.execute(runnable);
verify(getExecutor()).execute(wrappedRunnable);
this.executor = create();
this.executor.execute(this.runnable);
verify(getExecutor()).execute(this.wrappedRunnable);
}
protected Executor getExecutor() {
return delegate;
return this.delegate;
}
protected abstract DelegatingSecurityContextExecutor create();

View File

@@ -46,45 +46,45 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT
@Before
public final void setUpExecutor() {
executor = create();
this.executor = create();
}
@Test
@SuppressWarnings("unchecked")
public void scheduleRunnable() {
when((ScheduledFuture<Object>) delegate.schedule(wrappedRunnable, 1, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.schedule(runnable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).schedule(wrappedRunnable, 1, TimeUnit.SECONDS);
when((ScheduledFuture<Object>) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.schedule(this.runnable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS);
}
@Test
public void scheduleCallable() {
when(delegate.schedule(wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(expectedResult);
ScheduledFuture<Object> result = executor.schedule(callable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).schedule(wrappedCallable, 1, TimeUnit.SECONDS);
when(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).thenReturn(this.expectedResult);
ScheduledFuture<Object> result = this.executor.schedule(this.callable, 1, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).schedule(this.wrappedCallable, 1, TimeUnit.SECONDS);
}
@Test
@SuppressWarnings("unchecked")
public void scheduleAtFixedRate() {
when((ScheduledFuture<Object>) delegate.scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.scheduleAtFixedRate(runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).scheduleAtFixedRate(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
when((ScheduledFuture<Object>) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleAtFixedRate(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);
}
@Test
@SuppressWarnings("unchecked")
public void scheduleWithFixedDelay() {
when((ScheduledFuture<Object>) delegate.scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS))
.thenReturn(expectedResult);
ScheduledFuture<?> result = executor.scheduleWithFixedDelay(runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(expectedResult);
verify(delegate).scheduleWithFixedDelay(wrappedRunnable, 1, 2, TimeUnit.SECONDS);
when((ScheduledFuture<Object>) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2,
TimeUnit.SECONDS)).thenReturn(this.expectedResult);
ScheduledFuture<?> result = this.executor.scheduleWithFixedDelay(this.runnable, 1, 2, TimeUnit.SECONDS);
assertThat(result).isEqualTo(this.expectedResult);
verify(this.delegate).scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS);
}
@Override

View File

@@ -68,23 +68,23 @@ public abstract class AbstractDelegatingSecurityContextTestSupport {
public final void explicitSecurityContextPowermockSetup() throws Exception {
spy(DelegatingSecurityContextCallable.class);
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", eq(callable),
securityContextCaptor.capture());
doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", eq(this.callable),
this.securityContextCaptor.capture());
spy(DelegatingSecurityContextRunnable.class);
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", eq(runnable),
securityContextCaptor.capture());
doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", eq(this.runnable),
this.securityContextCaptor.capture());
}
public final void currentSecurityContextPowermockSetup() throws Exception {
spy(DelegatingSecurityContextCallable.class);
doReturn(wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", callable, null);
doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", this.callable, null);
spy(DelegatingSecurityContextRunnable.class);
doReturn(wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", runnable, null);
doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", this.runnable, null);
}
@Before
public final void setContext() {
SecurityContextHolder.setContext(currentSecurityContext);
SecurityContextHolder.setContext(this.currentSecurityContext);
}
@After

View File

@@ -37,7 +37,7 @@ public class CurrentDelegatingSecurityContextExecutorServiceTests
@Override
protected DelegatingSecurityContextExecutorService create() {
return new DelegatingSecurityContextExecutorService(delegate);
return new DelegatingSecurityContextExecutorService(this.delegate);
}
}

View File

@@ -37,7 +37,7 @@ public class CurrentDelegatingSecurityContextScheduledExecutorServiceTests
@Override
protected DelegatingSecurityContextScheduledExecutorService create() {
return new DelegatingSecurityContextScheduledExecutorService(delegate);
return new DelegatingSecurityContextScheduledExecutorService(this.delegate);
}
}

View File

@@ -61,15 +61,16 @@ public class DelegatingSecurityContextCallableTests {
@Before
@SuppressWarnings("serial")
public void setUp() throws Exception {
originalSecurityContext = SecurityContextHolder.createEmptyContext();
when(delegate.call()).thenAnswer(new Returns(callableResult) {
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
when(this.delegate.call()).thenAnswer(new Returns(this.callableResult) {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
assertThat(SecurityContextHolder.getContext())
.isEqualTo(DelegatingSecurityContextCallableTests.this.securityContext);
return super.answer(invocation);
}
});
executor = Executors.newFixedThreadPool(1);
this.executor = Executors.newFixedThreadPool(1);
}
@After
@@ -86,7 +87,7 @@ public class DelegatingSecurityContextCallableTests {
@Test(expected = IllegalArgumentException.class)
public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextCallable<>(null, securityContext);
new DelegatingSecurityContextCallable<>(null, this.securityContext);
}
@Test(expected = IllegalArgumentException.class)
@@ -96,40 +97,40 @@ public class DelegatingSecurityContextCallableTests {
@Test(expected = IllegalArgumentException.class)
public void constructorNullSecurityContext() {
new DelegatingSecurityContextCallable<>(delegate, null);
new DelegatingSecurityContextCallable<>(this.delegate, null);
}
// --- call ---
@Test
public void call() throws Exception {
callable = new DelegatingSecurityContextCallable<>(delegate, securityContext);
assertWrapped(callable);
this.callable = new DelegatingSecurityContextCallable<>(this.delegate, this.securityContext);
assertWrapped(this.callable);
}
@Test
public void callDefaultSecurityContext() throws Exception {
SecurityContextHolder.setContext(securityContext);
callable = new DelegatingSecurityContextCallable<>(delegate);
SecurityContextHolder.setContext(this.securityContext);
this.callable = new DelegatingSecurityContextCallable<>(this.delegate);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the
// SecurityContextHolder
assertWrapped(callable);
assertWrapped(this.callable);
}
// SEC-3031
@Test
public void callOnSameThread() throws Exception {
originalSecurityContext = securityContext;
SecurityContextHolder.setContext(originalSecurityContext);
callable = new DelegatingSecurityContextCallable<>(delegate, securityContext);
assertWrapped(callable.call());
this.originalSecurityContext = this.securityContext;
SecurityContextHolder.setContext(this.originalSecurityContext);
this.callable = new DelegatingSecurityContextCallable<>(this.delegate, this.securityContext);
assertWrapped(this.callable.call());
}
// --- create ---
@Test(expected = IllegalArgumentException.class)
public void createNullDelegate() {
DelegatingSecurityContextCallable.create(null, securityContext);
DelegatingSecurityContextCallable.create(null, this.securityContext);
}
@Test(expected = IllegalArgumentException.class)
@@ -139,17 +140,17 @@ public class DelegatingSecurityContextCallableTests {
@Test
public void createNullSecurityContext() throws Exception {
SecurityContextHolder.setContext(securityContext);
callable = DelegatingSecurityContextCallable.create(delegate, null);
SecurityContextHolder.setContext(this.securityContext);
this.callable = DelegatingSecurityContextCallable.create(this.delegate, null);
SecurityContextHolder.clearContext(); // ensure callable is what sets up the
// SecurityContextHolder
assertWrapped(callable);
assertWrapped(this.callable);
}
@Test
public void create() throws Exception {
callable = DelegatingSecurityContextCallable.create(delegate, securityContext);
assertWrapped(callable);
this.callable = DelegatingSecurityContextCallable.create(this.delegate, this.securityContext);
assertWrapped(this.callable);
}
// --- toString
@@ -157,18 +158,18 @@ public class DelegatingSecurityContextCallableTests {
// SEC-2682
@Test
public void toStringDelegates() {
callable = new DelegatingSecurityContextCallable<>(delegate, securityContext);
assertThat(callable.toString()).isEqualTo(delegate.toString());
this.callable = new DelegatingSecurityContextCallable<>(this.delegate, this.securityContext);
assertThat(this.callable.toString()).isEqualTo(this.delegate.toString());
}
private void assertWrapped(Callable<Object> callable) throws Exception {
Future<Object> submit = executor.submit(callable);
Future<Object> submit = this.executor.submit(callable);
assertWrapped(submit.get());
}
private void assertWrapped(Object callableResult) throws Exception {
verify(delegate).call();
assertThat(SecurityContextHolder.getContext()).isEqualTo(originalSecurityContext);
verify(this.delegate).call();
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.originalSecurityContext);
}
}

View File

@@ -60,13 +60,13 @@ public class DelegatingSecurityContextRunnableTests {
@Before
public void setUp() {
originalSecurityContext = SecurityContextHolder.createEmptyContext();
this.originalSecurityContext = SecurityContextHolder.createEmptyContext();
doAnswer((Answer<Object>) invocation -> {
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.securityContext);
return null;
}).when(delegate).run();
}).when(this.delegate).run();
executor = Executors.newFixedThreadPool(1);
this.executor = Executors.newFixedThreadPool(1);
}
@After
@@ -83,7 +83,7 @@ public class DelegatingSecurityContextRunnableTests {
@Test(expected = IllegalArgumentException.class)
public void constructorNullDelegateNonNullSecurityContext() {
new DelegatingSecurityContextRunnable(null, securityContext);
new DelegatingSecurityContextRunnable(null, this.securityContext);
}
@Test(expected = IllegalArgumentException.class)
@@ -93,41 +93,41 @@ public class DelegatingSecurityContextRunnableTests {
@Test(expected = IllegalArgumentException.class)
public void constructorNullSecurityContext() {
new DelegatingSecurityContextRunnable(delegate, null);
new DelegatingSecurityContextRunnable(this.delegate, null);
}
// --- run ---
@Test
public void call() throws Exception {
runnable = new DelegatingSecurityContextRunnable(delegate, securityContext);
assertWrapped(runnable);
this.runnable = new DelegatingSecurityContextRunnable(this.delegate, this.securityContext);
assertWrapped(this.runnable);
}
@Test
public void callDefaultSecurityContext() throws Exception {
SecurityContextHolder.setContext(securityContext);
runnable = new DelegatingSecurityContextRunnable(delegate);
SecurityContextHolder.setContext(this.securityContext);
this.runnable = new DelegatingSecurityContextRunnable(this.delegate);
SecurityContextHolder.clearContext(); // ensure runnable is what sets up the
// SecurityContextHolder
assertWrapped(runnable);
assertWrapped(this.runnable);
}
// SEC-3031
@Test
public void callOnSameThread() throws Exception {
originalSecurityContext = securityContext;
SecurityContextHolder.setContext(originalSecurityContext);
executor = synchronousExecutor();
runnable = new DelegatingSecurityContextRunnable(delegate, securityContext);
assertWrapped(runnable);
this.originalSecurityContext = this.securityContext;
SecurityContextHolder.setContext(this.originalSecurityContext);
this.executor = synchronousExecutor();
this.runnable = new DelegatingSecurityContextRunnable(this.delegate, this.securityContext);
assertWrapped(this.runnable);
}
// --- create ---
@Test(expected = IllegalArgumentException.class)
public void createNullDelegate() {
DelegatingSecurityContextRunnable.create(null, securityContext);
DelegatingSecurityContextRunnable.create(null, this.securityContext);
}
@Test(expected = IllegalArgumentException.class)
@@ -137,17 +137,17 @@ public class DelegatingSecurityContextRunnableTests {
@Test
public void createNullSecurityContext() throws Exception {
SecurityContextHolder.setContext(securityContext);
runnable = DelegatingSecurityContextRunnable.create(delegate, null);
SecurityContextHolder.setContext(this.securityContext);
this.runnable = DelegatingSecurityContextRunnable.create(this.delegate, null);
SecurityContextHolder.clearContext(); // ensure runnable is what sets up the
// SecurityContextHolder
assertWrapped(runnable);
assertWrapped(this.runnable);
}
@Test
public void create() throws Exception {
runnable = DelegatingSecurityContextRunnable.create(delegate, securityContext);
assertWrapped(runnable);
this.runnable = DelegatingSecurityContextRunnable.create(this.delegate, this.securityContext);
assertWrapped(this.runnable);
}
// --- toString
@@ -155,15 +155,15 @@ public class DelegatingSecurityContextRunnableTests {
// SEC-2682
@Test
public void toStringDelegates() {
runnable = new DelegatingSecurityContextRunnable(delegate, securityContext);
assertThat(runnable.toString()).isEqualTo(delegate.toString());
this.runnable = new DelegatingSecurityContextRunnable(this.delegate, this.securityContext);
assertThat(this.runnable.toString()).isEqualTo(this.delegate.toString());
}
private void assertWrapped(Runnable runnable) throws Exception {
Future<?> submit = executor.submit(runnable);
Future<?> submit = this.executor.submit(runnable);
submit.get();
verify(delegate).run();
assertThat(SecurityContextHolder.getContext()).isEqualTo(originalSecurityContext);
verify(this.delegate).run();
assertThat(SecurityContextHolder.getContext()).isEqualTo(this.originalSecurityContext);
}
private static ExecutorService synchronousExecutor() {

View File

@@ -33,31 +33,31 @@ public class DelegatingSecurityContextSupportTests extends AbstractDelegatingSec
@Test
public void wrapCallable() throws Exception {
explicitSecurityContextPowermockSetup();
support = new ConcreteDelegatingSecurityContextSupport(securityContext);
assertThat(support.wrap(callable)).isSameAs(wrappedCallable);
assertThat(securityContextCaptor.getValue()).isSameAs(securityContext);
this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext);
assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable);
assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext);
}
@Test
public void wrapCallableNullSecurityContext() throws Exception {
currentSecurityContextPowermockSetup();
support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(support.wrap(callable)).isSameAs(wrappedCallable);
this.support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(this.support.wrap(this.callable)).isSameAs(this.wrappedCallable);
}
@Test
public void wrapRunnable() throws Exception {
explicitSecurityContextPowermockSetup();
support = new ConcreteDelegatingSecurityContextSupport(securityContext);
assertThat(support.wrap(runnable)).isSameAs(wrappedRunnable);
assertThat(securityContextCaptor.getValue()).isSameAs(securityContext);
this.support = new ConcreteDelegatingSecurityContextSupport(this.securityContext);
assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable);
assertThat(this.securityContextCaptor.getValue()).isSameAs(this.securityContext);
}
@Test
public void wrapRunnableNullSecurityContext() throws Exception {
currentSecurityContextPowermockSetup();
support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(support.wrap(runnable)).isSameAs(wrappedRunnable);
this.support = new ConcreteDelegatingSecurityContextSupport(null);
assertThat(this.support.wrap(this.runnable)).isSameAs(this.wrappedRunnable);
}
private static class ConcreteDelegatingSecurityContextSupport extends AbstractDelegatingSecurityContextSupport {

View File

@@ -37,7 +37,7 @@ public class ExplicitDelegatingSecurityContextExecutorServiceTests
@Override
protected DelegatingSecurityContextExecutorService create() {
return new DelegatingSecurityContextExecutorService(delegate, securityContext);
return new DelegatingSecurityContextExecutorService(this.delegate, this.securityContext);
}
}

View File

@@ -36,7 +36,7 @@ public class ExplicitDelegatingSecurityContextExecutorTests extends AbstractDele
@Override
protected DelegatingSecurityContextExecutor create() {
return new DelegatingSecurityContextExecutor(getExecutor(), securityContext);
return new DelegatingSecurityContextExecutor(getExecutor(), this.securityContext);
}
}

View File

@@ -37,7 +37,7 @@ public class ExplicitDelegatingSecurityContextScheduledExecutorServiceTests
@Override
protected DelegatingSecurityContextScheduledExecutorService create() {
return new DelegatingSecurityContextScheduledExecutorService(delegate, securityContext);
return new DelegatingSecurityContextScheduledExecutorService(this.delegate, this.securityContext);
}
}

View File

@@ -41,46 +41,46 @@ public class DelegatingApplicationListenerTests {
@Before
public void setup() {
event = new ApplicationEvent(this) {
this.event = new ApplicationEvent(this) {
};
listener = new DelegatingApplicationListener();
listener.addListener(delegate);
this.listener = new DelegatingApplicationListener();
this.listener.addListener(this.delegate);
}
@Test
public void processEventNull() {
listener.onApplicationEvent(null);
this.listener.onApplicationEvent(null);
verify(delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
}
@Test
public void processEventSuccess() {
when(delegate.supportsEventType(event.getClass())).thenReturn(true);
when(delegate.supportsSourceType(event.getSource().getClass())).thenReturn(true);
listener.onApplicationEvent(event);
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
when(this.delegate.supportsSourceType(this.event.getSource().getClass())).thenReturn(true);
this.listener.onApplicationEvent(this.event);
verify(delegate).onApplicationEvent(event);
verify(this.delegate).onApplicationEvent(this.event);
}
@Test
public void processEventEventTypeNotSupported() {
listener.onApplicationEvent(event);
this.listener.onApplicationEvent(this.event);
verify(delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
}
@Test
public void processEventSourceTypeNotSupported() {
when(delegate.supportsEventType(event.getClass())).thenReturn(true);
listener.onApplicationEvent(event);
when(this.delegate.supportsEventType(this.event.getClass())).thenReturn(true);
this.listener.onApplicationEvent(this.event);
verify(delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
verify(this.delegate, never()).onApplicationEvent(any(ApplicationEvent.class));
}
@Test(expected = IllegalArgumentException.class)
public void addNull() {
listener.addListener(null);
this.listener.addListener(null);
}
}

View File

@@ -51,7 +51,7 @@ public class SpringSecurityCoreVersionTests {
@Before
public void setup() {
Whitebox.setInternalState(SpringSecurityCoreVersion.class, logger);
Whitebox.setInternalState(SpringSecurityCoreVersion.class, this.logger);
}
@After
@@ -90,7 +90,7 @@ public class SpringSecurityCoreVersionTests {
performChecks();
verifyZeroInteractions(logger);
verifyZeroInteractions(this.logger);
}
@Test
@@ -102,7 +102,7 @@ public class SpringSecurityCoreVersionTests {
performChecks();
verifyZeroInteractions(logger);
verifyZeroInteractions(this.logger);
}
@Test
@@ -114,7 +114,7 @@ public class SpringSecurityCoreVersionTests {
performChecks();
verify(logger, times(1)).warn(any());
verify(this.logger, times(1)).warn(any());
}
@Test
@@ -126,7 +126,7 @@ public class SpringSecurityCoreVersionTests {
performChecks();
verify(logger, never()).warn(any());
verify(this.logger, never()).warn(any());
}
// SEC-2697
@@ -140,7 +140,7 @@ public class SpringSecurityCoreVersionTests {
performChecks(minSpringVersion);
verify(logger, never()).warn(any());
verify(this.logger, never()).warn(any());
}
@Test
@@ -153,7 +153,7 @@ public class SpringSecurityCoreVersionTests {
performChecks();
verifyZeroInteractions(logger);
verifyZeroInteractions(this.logger);
}
private String getDisableChecksProperty() {

View File

@@ -29,85 +29,88 @@ public class AnnotationParameterNameDiscovererTests {
@Before
public void setup() {
discoverer = new AnnotationParameterNameDiscoverer(P.class.getName());
this.discoverer = new AnnotationParameterNameDiscoverer(P.class.getName());
}
@Test
public void getParameterNamesInterfaceSingleParam() {
assertThat(discoverer.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
}
@Test
public void getParameterNamesInterfaceSingleParamAnnotatedWithMultiParams() {
assertThat(discoverer.getParameterNames(
assertThat(this.discoverer.getParameterNames(
ReflectionUtils.findMethod(Dao.class, "findMessageByToAndFrom", String.class, String.class)))
.isEqualTo(new String[] { "to", null });
}
@Test
public void getParameterNamesInterfaceNoAnnotation() {
assertThat(discoverer
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByIdNoAnnotation", String.class)))
.isNull();
}
@Test
public void getParameterNamesClassSingleParam() {
assertThat(discoverer.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
}
@Test
public void getParameterNamesClassSingleParamAnnotatedWithMultiParams() {
assertThat(discoverer.getParameterNames(
assertThat(this.discoverer.getParameterNames(
ReflectionUtils.findMethod(Dao.class, "findMessageByToAndFrom", String.class, String.class)))
.isEqualTo(new String[] { "to", null });
}
@Test
public void getParameterNamesClassNoAnnotation() {
assertThat(discoverer
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByIdNoAnnotation", String.class)))
.isNull();
}
@Test
public void getParameterNamesConstructor() throws Exception {
assertThat(discoverer.getParameterNames(Impl.class.getDeclaredConstructor(String.class)))
assertThat(this.discoverer.getParameterNames(Impl.class.getDeclaredConstructor(String.class)))
.isEqualTo(new String[] { "id" });
}
@Test
public void getParameterNamesConstructorNoAnnotation() throws Exception {
assertThat(discoverer.getParameterNames(Impl.class.getDeclaredConstructor(Long.class))).isNull();
assertThat(this.discoverer.getParameterNames(Impl.class.getDeclaredConstructor(Long.class))).isNull();
}
@Test
public void getParameterNamesClassAnnotationOnInterface() {
assertThat(discoverer
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(DaoImpl.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
assertThat(discoverer.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByTo", String.class)))
.isEqualTo(new String[] { "to" });
}
@Test
public void getParameterNamesClassAnnotationOnImpl() {
assertThat(discoverer.getParameterNames(
assertThat(this.discoverer.getParameterNames(
ReflectionUtils.findMethod(Dao.class, "findMessageByToAndFrom", String.class, String.class)))
.isEqualTo(new String[] { "to", null });
assertThat(discoverer.getParameterNames(
assertThat(this.discoverer.getParameterNames(
ReflectionUtils.findMethod(DaoImpl.class, "findMessageByToAndFrom", String.class, String.class)))
.isEqualTo(new String[] { "to", "from" });
}
@Test
public void getParameterNamesClassAnnotationOnBaseClass() {
assertThat(discoverer
assertThat(this.discoverer
.getParameterNames(ReflectionUtils.findMethod(Dao.class, "findMessageByIdNoAnnotation", String.class)))
.isNull();
assertThat(discoverer.getParameterNames(
assertThat(this.discoverer.getParameterNames(
ReflectionUtils.findMethod(DaoImpl.class, "findMessageByIdNoAnnotation", String.class)))
.isEqualTo(new String[] { "id" });
}

View File

@@ -40,13 +40,13 @@ public class DefaultSecurityParameterNameDiscovererTests {
@Before
public void setup() {
discoverer = new DefaultSecurityParameterNameDiscoverer();
this.discoverer = new DefaultSecurityParameterNameDiscoverer();
}
@Test
public void constructorDefault() {
List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils
.getField(discoverer, "parameterNameDiscoverers");
.getField(this.discoverer, "parameterNameDiscoverers");
assertThat(discoverers).hasSize(2);
@@ -61,11 +61,11 @@ public class DefaultSecurityParameterNameDiscovererTests {
@Test
public void constructorDiscoverers() {
discoverer = new DefaultSecurityParameterNameDiscoverer(
this.discoverer = new DefaultSecurityParameterNameDiscoverer(
Arrays.asList(new LocalVariableTableParameterNameDiscoverer()));
List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils
.getField(discoverer, "parameterNameDiscoverers");
.getField(this.discoverer, "parameterNameDiscoverers");
assertThat(discoverers).hasSize(3);
assertThat(discoverers.get(0)).isInstanceOf(LocalVariableTableParameterNameDiscoverer.class);

View File

@@ -37,7 +37,7 @@ public class SessionRegistryImplTests {
@Before
public void setUp() {
sessionRegistry = new SessionRegistryImpl();
this.sessionRegistry = new SessionRegistryImpl();
}
@Test
@@ -46,10 +46,10 @@ public class SessionRegistryImplTests {
final String sessionId = "zzzz";
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
this.sessionRegistry.registerNewSession(sessionId, principal);
// De-register session via an ApplicationEvent
sessionRegistry.onApplicationEvent(new SessionDestroyedEvent("") {
this.sessionRegistry.onApplicationEvent(new SessionDestroyedEvent("") {
@Override
public String getId() {
return sessionId;
@@ -62,7 +62,7 @@ public class SessionRegistryImplTests {
});
// Check attempts to retrieve cleared session return null
assertThat(sessionRegistry.getSessionInformation(sessionId)).isNull();
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
}
@Test
@@ -72,10 +72,10 @@ public class SessionRegistryImplTests {
final String newSessionId = "123";
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
this.sessionRegistry.registerNewSession(sessionId, principal);
// De-register session via an ApplicationEvent
sessionRegistry.onApplicationEvent(new SessionIdChangedEvent("") {
this.sessionRegistry.onApplicationEvent(new SessionIdChangedEvent("") {
@Override
public String getOldSessionId() {
return sessionId;
@@ -87,9 +87,9 @@ public class SessionRegistryImplTests {
}
});
assertThat(sessionRegistry.getSessionInformation(sessionId)).isNull();
assertThat(sessionRegistry.getSessionInformation(newSessionId)).isNotNull();
assertThat(sessionRegistry.getSessionInformation(newSessionId).getPrincipal()).isEqualTo(principal);
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
assertThat(this.sessionRegistry.getSessionInformation(newSessionId)).isNotNull();
assertThat(this.sessionRegistry.getSessionInformation(newSessionId).getPrincipal()).isEqualTo(principal);
}
@Test
@@ -100,13 +100,13 @@ public class SessionRegistryImplTests {
String sessionId2 = "9876543210";
String sessionId3 = "5432109876";
sessionRegistry.registerNewSession(sessionId1, principal1);
sessionRegistry.registerNewSession(sessionId2, principal1);
sessionRegistry.registerNewSession(sessionId3, principal2);
this.sessionRegistry.registerNewSession(sessionId1, principal1);
this.sessionRegistry.registerNewSession(sessionId2, principal1);
this.sessionRegistry.registerNewSession(sessionId3, principal2);
assertThat(sessionRegistry.getAllPrincipals()).hasSize(2);
assertThat(sessionRegistry.getAllPrincipals().contains(principal1)).isTrue();
assertThat(sessionRegistry.getAllPrincipals().contains(principal2)).isTrue();
assertThat(this.sessionRegistry.getAllPrincipals()).hasSize(2);
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal1)).isTrue();
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal2)).isTrue();
}
@Test
@@ -114,36 +114,36 @@ public class SessionRegistryImplTests {
Object principal = "Some principal object";
String sessionId = "1234567890";
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
this.sessionRegistry.registerNewSession(sessionId, principal);
// Retrieve existing session by session ID
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertThat(sessionRegistry.getSessionInformation(sessionId).getPrincipal()).isEqualTo(principal);
assertThat(sessionRegistry.getSessionInformation(sessionId).getSessionId()).isEqualTo(sessionId);
assertThat(sessionRegistry.getSessionInformation(sessionId).getLastRequest()).isNotNull();
Date currentDateTime = this.sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getPrincipal()).isEqualTo(principal);
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getSessionId()).isEqualTo(sessionId);
assertThat(this.sessionRegistry.getSessionInformation(sessionId).getLastRequest()).isNotNull();
// Retrieve existing session by principal
assertThat(sessionRegistry.getAllSessions(principal, false)).hasSize(1);
assertThat(this.sessionRegistry.getAllSessions(principal, false)).hasSize(1);
// Sleep to ensure SessionRegistryImpl will update time
Thread.sleep(1000);
// Update request date/time
sessionRegistry.refreshLastRequest(sessionId);
this.sessionRegistry.refreshLastRequest(sessionId);
Date retrieved = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
Date retrieved = this.sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertThat(retrieved.after(currentDateTime)).isTrue();
// Check it retrieves correctly when looked up via principal
assertThat(sessionRegistry.getAllSessions(principal, false).get(0).getLastRequest()).isCloseTo(retrieved,
assertThat(this.sessionRegistry.getAllSessions(principal, false).get(0).getLastRequest()).isCloseTo(retrieved,
2000L);
// Clear session information
sessionRegistry.removeSessionInformation(sessionId);
this.sessionRegistry.removeSessionInformation(sessionId);
// Check attempts to retrieve cleared session return null
assertThat(sessionRegistry.getSessionInformation(sessionId)).isNull();
assertThat(sessionRegistry.getAllSessions(principal, false)).isEmpty();
assertThat(this.sessionRegistry.getSessionInformation(sessionId)).isNull();
assertThat(this.sessionRegistry.getAllSessions(principal, false)).isEmpty();
}
@Test
@@ -152,23 +152,23 @@ public class SessionRegistryImplTests {
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
sessionRegistry.registerNewSession(sessionId1, principal);
List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal, false);
this.sessionRegistry.registerNewSession(sessionId1, principal);
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal, false);
assertThat(sessions).hasSize(1);
assertThat(contains(sessionId1, principal)).isTrue();
sessionRegistry.registerNewSession(sessionId2, principal);
sessions = sessionRegistry.getAllSessions(principal, false);
this.sessionRegistry.registerNewSession(sessionId2, principal);
sessions = this.sessionRegistry.getAllSessions(principal, false);
assertThat(sessions).hasSize(2);
assertThat(contains(sessionId2, principal)).isTrue();
// Expire one session
SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
SessionInformation session = this.sessionRegistry.getSessionInformation(sessionId2);
session.expireNow();
// Check retrieval still correct
assertThat(sessionRegistry.getSessionInformation(sessionId2).isExpired()).isTrue();
assertThat(sessionRegistry.getSessionInformation(sessionId1).isExpired()).isFalse();
assertThat(this.sessionRegistry.getSessionInformation(sessionId2).isExpired()).isTrue();
assertThat(this.sessionRegistry.getSessionInformation(sessionId1).isExpired()).isFalse();
}
@Test
@@ -177,28 +177,28 @@ public class SessionRegistryImplTests {
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
sessionRegistry.registerNewSession(sessionId1, principal);
List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal, false);
this.sessionRegistry.registerNewSession(sessionId1, principal);
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal, false);
assertThat(sessions).hasSize(1);
assertThat(contains(sessionId1, principal)).isTrue();
sessionRegistry.registerNewSession(sessionId2, principal);
sessions = sessionRegistry.getAllSessions(principal, false);
this.sessionRegistry.registerNewSession(sessionId2, principal);
sessions = this.sessionRegistry.getAllSessions(principal, false);
assertThat(sessions).hasSize(2);
assertThat(contains(sessionId2, principal)).isTrue();
sessionRegistry.removeSessionInformation(sessionId1);
sessions = sessionRegistry.getAllSessions(principal, false);
this.sessionRegistry.removeSessionInformation(sessionId1);
sessions = this.sessionRegistry.getAllSessions(principal, false);
assertThat(sessions).hasSize(1);
assertThat(contains(sessionId2, principal)).isTrue();
sessionRegistry.removeSessionInformation(sessionId2);
assertThat(sessionRegistry.getSessionInformation(sessionId2)).isNull();
assertThat(sessionRegistry.getAllSessions(principal, false)).isEmpty();
this.sessionRegistry.removeSessionInformation(sessionId2);
assertThat(this.sessionRegistry.getSessionInformation(sessionId2)).isNull();
assertThat(this.sessionRegistry.getAllSessions(principal, false)).isEmpty();
}
private boolean contains(String sessionId, Object principal) {
List<SessionInformation> info = sessionRegistry.getAllSessions(principal, false);
List<SessionInformation> info = this.sessionRegistry.getAllSessions(principal, false);
for (SessionInformation sessionInformation : info) {
if (sessionId.equals(sessionInformation.getSessionId())) {

View File

@@ -56,34 +56,34 @@ public class MapReactiveUserDetailsServiceTests {
@Test
public void findByUsernameWhenFoundThenReturns() {
assertThat((users.findByUsername(USER_DETAILS.getUsername()).block())).isEqualTo(USER_DETAILS);
assertThat((this.users.findByUsername(USER_DETAILS.getUsername()).block())).isEqualTo(USER_DETAILS);
}
@Test
public void findByUsernameWhenDifferentCaseThenReturns() {
assertThat((users.findByUsername("uSeR").block())).isEqualTo(USER_DETAILS);
assertThat((this.users.findByUsername("uSeR").block())).isEqualTo(USER_DETAILS);
}
@Test
public void findByUsernameWhenClearCredentialsThenFindByUsernameStillHasCredentials() {
User foundUser = users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block();
User foundUser = this.users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block();
assertThat(foundUser.getPassword()).isNotEmpty();
foundUser.eraseCredentials();
assertThat(foundUser.getPassword()).isNull();
foundUser = users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block();
foundUser = this.users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block();
assertThat(foundUser.getPassword()).isNotEmpty();
}
@Test
public void findByUsernameWhenNotFoundThenEmpty() {
assertThat((users.findByUsername("notfound"))).isEqualTo(Mono.empty());
assertThat((this.users.findByUsername("notfound"))).isEqualTo(Mono.empty());
}
@Test
public void updatePassword() {
users.updatePassword(USER_DETAILS, "new").block();
assertThat(users.findByUsername(USER_DETAILS.getUsername()).block().getPassword()).isEqualTo("new");
this.users.updatePassword(USER_DETAILS, "new").block();
assertThat(this.users.findByUsername(USER_DETAILS.getUsername()).block().getPassword()).isEqualTo("new");
}
}

View File

@@ -36,19 +36,19 @@ public class MockUserDetailsService implements UserDetailsService {
private List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_USER");
public MockUserDetailsService() {
users.put("valid", new User("valid", "", true, true, true, true, auths));
users.put("locked", new User("locked", "", true, true, true, false, auths));
users.put("disabled", new User("disabled", "", false, true, true, true, auths));
users.put("credentialsExpired", new User("credentialsExpired", "", true, true, false, true, auths));
users.put("expired", new User("expired", "", true, false, true, true, auths));
this.users.put("valid", new User("valid", "", true, true, true, true, this.auths));
this.users.put("locked", new User("locked", "", true, true, true, false, this.auths));
this.users.put("disabled", new User("disabled", "", false, true, true, true, this.auths));
this.users.put("credentialsExpired", new User("credentialsExpired", "", true, true, false, true, this.auths));
this.users.put("expired", new User("expired", "", true, false, true, true, this.auths));
}
public UserDetails loadUserByUsername(String username) {
if (users.get(username) == null) {
if (this.users.get(username) == null) {
throw new UsernameNotFoundException("User not found: " + username);
}
return users.get(username);
return this.users.get(username);
}
}

View File

@@ -32,9 +32,9 @@ public abstract class AbstractMixinTests {
@Before
public void setup() {
mapper = new ObjectMapper();
this.mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJackson2Modules.getModules(loader));
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
}
User createDefaultUser() {

View File

@@ -53,13 +53,13 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
public void serializeAnonymousAuthenticationTokenTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(HASH_KEY, user, user.getAuthorities());
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON, actualJson, true);
}
@Test
public void deserializeAnonymousAuthenticationTokenTest() throws IOException {
AnonymousAuthenticationToken token = mapper.readValue(ANONYMOUS_JSON, AnonymousAuthenticationToken.class);
AnonymousAuthenticationToken token = this.mapper.readValue(ANONYMOUS_JSON, AnonymousAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getKeyHash()).isEqualTo(HASH_KEY.hashCode());
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
@@ -70,7 +70,7 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null,"
+ "\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + ","
+ "\"authorities\": [\"java.util.ArrayList\", []]}";
mapper.readValue(jsonString, AnonymousAuthenticationToken.class);
this.mapper.readValue(jsonString, AnonymousAuthenticationToken.class);
}
@Test
@@ -79,7 +79,7 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
User user = createDefaultUser();
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(HASH_KEY, user, user.getAuthorities());
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
}

View File

@@ -44,13 +44,13 @@ public class BadCredentialsExceptionMixinTests extends AbstractMixinTests {
@Test
public void serializeBadCredentialsExceptionMixinTest() throws JsonProcessingException, JSONException {
BadCredentialsException exception = new BadCredentialsException("message");
String serializedJson = mapper.writeValueAsString(exception);
String serializedJson = this.mapper.writeValueAsString(exception);
JSONAssert.assertEquals(EXCEPTION_JSON, serializedJson, true);
}
@Test
public void deserializeBadCredentialsExceptionMixinTest() throws IOException {
BadCredentialsException exception = mapper.readValue(EXCEPTION_JSON, BadCredentialsException.class);
BadCredentialsException exception = this.mapper.readValue(EXCEPTION_JSON, BadCredentialsException.class);
assertThat(exception).isNotNull();
assertThat(exception.getCause()).isNull();
assertThat(exception.getMessage()).isEqualTo("message");

View File

@@ -74,7 +74,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, "admin",
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, actualJson, true);
}
@@ -83,7 +83,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user,
user.getAuthorities());
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(String.format(REMEMBERME_AUTH_JSON, "\"password\""), actualJson, true);
}
@@ -94,14 +94,14 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user,
user.getAuthorities());
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson,
true);
}
@Test
public void deserializeRememberMeAuthenticationToken() throws IOException {
RememberMeAuthenticationToken token = mapper.readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON,
RememberMeAuthenticationToken token = this.mapper.readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON,
RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isEqualTo("admin").isEqualTo(token.getName());
@@ -110,7 +110,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
@Test
public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException {
RememberMeAuthenticationToken token = mapper.readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""),
RememberMeAuthenticationToken token = this.mapper.readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""),
RememberMeAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);

View File

@@ -50,13 +50,13 @@ public class SecurityContextMixinTests extends AbstractMixinTests {
SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234",
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
String actualJson = mapper.writeValueAsString(context);
String actualJson = this.mapper.writeValueAsString(context);
JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true);
}
@Test
public void securityContextDeserializeTest() throws IOException {
SecurityContext context = mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class);
SecurityContext context = this.mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class);
assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin");

View File

@@ -44,57 +44,57 @@ public class SecurityJackson2ModulesTests {
@Before
public void setup() {
mapper = new ObjectMapper();
SecurityJackson2Modules.enableDefaultTyping(mapper);
this.mapper = new ObjectMapper();
SecurityJackson2Modules.enableDefaultTyping(this.mapper);
}
@Test
public void readValueWhenNotAllowedOrMappedThenThrowsException() {
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
assertThatThrownBy(() -> {
mapper.readValue(content, Object.class);
this.mapper.readValue(content, Object.class);
}).hasStackTraceContaining("allowlist");
}
@Test
public void readValueWhenExplicitDefaultTypingAfterSecuritySetupThenReadsAsSpecificType() throws Exception {
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
this.mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
assertThat(mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
}
@Test
public void readValueWhenExplicitDefaultTypingBeforeSecuritySetupThenReadsAsSpecificType() throws Exception {
mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
SecurityJackson2Modules.enableDefaultTyping(mapper);
this.mapper = new ObjectMapper();
this.mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
SecurityJackson2Modules.enableDefaultTyping(this.mapper);
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
assertThat(mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
}
@Test
public void readValueWhenAnnotatedThenReadsAsSpecificType() throws Exception {
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlistedButAnnotated\",\"property\":\"bar\"}";
assertThat(mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlistedButAnnotated.class);
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlistedButAnnotated.class);
}
@Test
public void readValueWhenMixinProvidedThenReadsAsSpecificType() throws Exception {
mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
this.mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
assertThat(mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(NotAllowlisted.class);
}
@Test
public void readValueWhenHashMapThenReadsAsSpecificType() throws Exception {
mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
this.mapper.addMixIn(NotAllowlisted.class, NotAllowlistedMixin.class);
String content = "{\"@class\":\"java.util.HashMap\"}";
assertThat(mapper.readValue(content, Object.class)).isInstanceOf(HashMap.class);
assertThat(this.mapper.readValue(content, Object.class)).isInstanceOf(HashMap.class);
}
@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE })
@@ -110,7 +110,7 @@ public class SecurityJackson2ModulesTests {
private String property = "bar";
public String getProperty() {
return property;
return this.property;
}
public void setProperty(String property) {
@@ -124,7 +124,7 @@ public class SecurityJackson2ModulesTests {
private String property = "bar";
public String getProperty() {
return property;
return this.property;
}
public void setProperty(String property) {

View File

@@ -51,13 +51,13 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
@Test
public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
String serializeJson = mapper.writeValueAsString(authority);
String serializeJson = this.mapper.writeValueAsString(authority);
JSONAssert.assertEquals(AUTHORITY_JSON, serializeJson, true);
}
@Test
public void deserializeGrantedAuthorityTest() throws IOException {
SimpleGrantedAuthority authority = mapper.readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class);
SimpleGrantedAuthority authority = this.mapper.readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class);
assertThat(authority).isNotNull();
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
}
@@ -65,7 +65,7 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
@Test(expected = JsonMappingException.class)
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
mapper.readValue(json, SimpleGrantedAuthority.class);
this.mapper.readValue(json, SimpleGrantedAuthority.class);
}
}

View File

@@ -57,14 +57,14 @@ public class UserDeserializerTests extends AbstractMixinTests {
@Test
public void serializeUserTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser();
String userJson = mapper.writeValueAsString(user);
String userJson = this.mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithPasswordJson(user.getPassword()), userJson, true);
}
@Test
public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException {
User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList());
String userJson = mapper.writeValueAsString(user);
String userJson = this.mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true);
}
@@ -73,14 +73,14 @@ public class UserDeserializerTests extends AbstractMixinTests {
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[]");
mapper.readValue(userJsonWithoutPasswordString, User.class);
this.mapper.readValue(userJsonWithoutPasswordString, User.class);
}
@Test
public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception {
String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), mapper, "password");
String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), this.mapper, "password");
User user = mapper.readValue(userJsonWithoutPasswordString, User.class);
User user = this.mapper.readValue(userJsonWithoutPasswordString, User.class);
assertThat(user).isNotNull();
assertThat(user.getUsername()).isEqualTo("admin");
assertThat(user.getPassword()).isNull();
@@ -92,12 +92,12 @@ public class UserDeserializerTests extends AbstractMixinTests {
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception {
String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON,
"[{\"authority\": \"ROLE_USER\"}]");
mapper.readValue(userJson, User.class);
this.mapper.readValue(userJson, User.class);
}
@Test
public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException {
User user = mapper.readValue(userJson(), User.class);
User user = this.mapper.readValue(userJson(), User.class);
assertThat(user).isNotNull();
assertThat(user.getUsername()).isEqualTo("admin");
assertThat(user.getPassword()).isEqualTo("1234");

View File

@@ -86,7 +86,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest()
throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234");
String serializedJson = mapper.writeValueAsString(token);
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@@ -96,13 +96,13 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),
user.getPassword(), user.getAuthorities());
String serializedJson = mapper.writeValueAsString(token);
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
}
@Test
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
UsernamePasswordAuthenticationToken token = mapper.readValue(UNAUTHENTICATED_STRINGPRINCIPAL_JSON,
UsernamePasswordAuthenticationToken token = this.mapper.readValue(UNAUTHENTICATED_STRINGPRINCIPAL_JSON,
UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isEqualTo(false);
@@ -112,7 +112,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
UsernamePasswordAuthenticationToken expectedToken = createToken();
UsernamePasswordAuthenticationToken token = mapper.readValue(AUTHENTICATED_STRINGPRINCIPAL_JSON,
UsernamePasswordAuthenticationToken token = this.mapper.readValue(AUTHENTICATED_STRINGPRINCIPAL_JSON,
UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isTrue();
@@ -123,13 +123,13 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest()
throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken();
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON, actualJson, true);
}
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
UsernamePasswordAuthenticationToken token = mapper.readValue(AUTHENTICATED_JSON,
UsernamePasswordAuthenticationToken token = this.mapper.readValue(AUTHENTICATED_JSON,
UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
@@ -144,7 +144,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken();
token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON.replaceAll(UserDeserializerTests.USER_PASSWORD, "null"), actualJson,
true);
}
@@ -156,14 +156,14 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
principal.setUsername("admin");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null,
new ArrayList<>());
String actualJson = mapper.writeValueAsString(token);
String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_NON_USER_PRINCIPAL_JSON, actualJson, true);
}
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithNonUserPrincipalTest()
throws IOException {
UsernamePasswordAuthenticationToken token = mapper.readValue(AUTHENTICATED_NON_USER_PRINCIPAL_JSON,
UsernamePasswordAuthenticationToken token = this.mapper.readValue(AUTHENTICATED_NON_USER_PRINCIPAL_JSON,
UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(NonUserPrincipal.class);
@@ -171,7 +171,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithDetailsTest() throws IOException {
UsernamePasswordAuthenticationToken token = mapper.readValue(AUTHENTICATED_STRINGDETAILS_JSON,
UsernamePasswordAuthenticationToken token = this.mapper.readValue(AUTHENTICATED_STRINGDETAILS_JSON,
UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
@@ -224,7 +224,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
private String username;
public String getUsername() {
return username;
return this.username;
}
public void setUsername(String username) {

View File

@@ -83,56 +83,57 @@ public class JdbcUserDetailsManagerTests {
@Before
public void initializeManagerAndCreateTables() {
manager = new JdbcUserDetailsManager();
cache = new MockUserCache();
manager.setUserCache(cache);
manager.setDataSource(dataSource);
manager.setCreateUserSql(JdbcUserDetailsManager.DEF_CREATE_USER_SQL);
manager.setUpdateUserSql(JdbcUserDetailsManager.DEF_UPDATE_USER_SQL);
manager.setUserExistsSql(JdbcUserDetailsManager.DEF_USER_EXISTS_SQL);
manager.setCreateAuthoritySql(JdbcUserDetailsManager.DEF_INSERT_AUTHORITY_SQL);
manager.setDeleteUserAuthoritiesSql(JdbcUserDetailsManager.DEF_DELETE_USER_AUTHORITIES_SQL);
manager.setDeleteUserSql(JdbcUserDetailsManager.DEF_DELETE_USER_SQL);
manager.setChangePasswordSql(JdbcUserDetailsManager.DEF_CHANGE_PASSWORD_SQL);
manager.initDao();
template = manager.getJdbcTemplate();
this.manager = new JdbcUserDetailsManager();
this.cache = new MockUserCache();
this.manager.setUserCache(this.cache);
this.manager.setDataSource(dataSource);
this.manager.setCreateUserSql(JdbcUserDetailsManager.DEF_CREATE_USER_SQL);
this.manager.setUpdateUserSql(JdbcUserDetailsManager.DEF_UPDATE_USER_SQL);
this.manager.setUserExistsSql(JdbcUserDetailsManager.DEF_USER_EXISTS_SQL);
this.manager.setCreateAuthoritySql(JdbcUserDetailsManager.DEF_INSERT_AUTHORITY_SQL);
this.manager.setDeleteUserAuthoritiesSql(JdbcUserDetailsManager.DEF_DELETE_USER_AUTHORITIES_SQL);
this.manager.setDeleteUserSql(JdbcUserDetailsManager.DEF_DELETE_USER_SQL);
this.manager.setChangePasswordSql(JdbcUserDetailsManager.DEF_CHANGE_PASSWORD_SQL);
this.manager.initDao();
this.template = this.manager.getJdbcTemplate();
template.execute("create table users(username varchar(20) not null primary key,"
this.template.execute("create table users(username varchar(20) not null primary key,"
+ "password varchar(20) not null, enabled boolean not null)");
template.execute("create table authorities (username varchar(20) not null, authority varchar(20) not null, "
+ "constraint fk_authorities_users foreign key(username) references users(username))");
PopulatedDatabase.createGroupTables(template);
PopulatedDatabase.insertGroupData(template);
this.template
.execute("create table authorities (username varchar(20) not null, authority varchar(20) not null, "
+ "constraint fk_authorities_users foreign key(username) references users(username))");
PopulatedDatabase.createGroupTables(this.template);
PopulatedDatabase.insertGroupData(this.template);
}
@After
public void dropTablesAndClearContext() {
template.execute("drop table authorities");
template.execute("drop table users");
template.execute("drop table group_authorities");
template.execute("drop table group_members");
template.execute("drop table groups");
this.template.execute("drop table authorities");
this.template.execute("drop table users");
this.template.execute("drop table group_authorities");
this.template.execute("drop table group_members");
this.template.execute("drop table groups");
SecurityContextHolder.clearContext();
}
private void setUpAccLockingColumns() {
template.execute("alter table users add column acc_locked boolean default false not null");
template.execute("alter table users add column acc_expired boolean default false not null");
template.execute("alter table users add column creds_expired boolean default false not null");
this.template.execute("alter table users add column acc_locked boolean default false not null");
this.template.execute("alter table users add column acc_expired boolean default false not null");
this.template.execute("alter table users add column creds_expired boolean default false not null");
manager.setUsersByUsernameQuery(
this.manager.setUsersByUsernameQuery(
"select username,password,enabled, acc_locked, acc_expired, creds_expired from users where username = ?");
manager.setCreateUserSql(
this.manager.setCreateUserSql(
"insert into users (username, password, enabled, acc_locked, acc_expired, creds_expired) values (?,?,?,?,?,?)");
manager.setUpdateUserSql(
this.manager.setUpdateUserSql(
"update users set password = ?, enabled = ?, acc_locked=?, acc_expired=?, creds_expired=? where username = ?");
}
@Test
public void createUserInsertsCorrectData() {
manager.createUser(joe);
this.manager.createUser(joe);
UserDetails joe2 = manager.loadUserByUsername("joe");
UserDetails joe2 = this.manager.loadUserByUsername("joe");
assertThat(joe2).isEqualTo(joe);
}
@@ -143,9 +144,9 @@ public class JdbcUserDetailsManagerTests {
UserDetails user = new User("joe", "pass", true, false, true, false,
AuthorityUtils.createAuthorityList("A", "B"));
manager.createUser(user);
this.manager.createUser(user);
UserDetails user2 = manager.loadUserByUsername(user.getUsername());
UserDetails user2 = this.manager.loadUserByUsername(user.getUsername());
assertThat(user2).isEqualToComparingFieldByField(user);
}
@@ -153,11 +154,11 @@ public class JdbcUserDetailsManagerTests {
@Test
public void deleteUserRemovesUserDataAndAuthoritiesAndClearsCache() {
insertJoe();
manager.deleteUser("joe");
this.manager.deleteUser("joe");
assertThat(template.queryForList(SELECT_JOE_SQL)).isEmpty();
assertThat(template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
assertThat(cache.getUserMap().containsKey("joe")).isFalse();
assertThat(this.template.queryForList(SELECT_JOE_SQL)).isEmpty();
assertThat(this.template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
}
@Test
@@ -166,12 +167,12 @@ public class JdbcUserDetailsManagerTests {
User newJoe = new User("joe", "newpassword", false, true, true, true,
AuthorityUtils.createAuthorityList(new String[] { "D", "F", "E" }));
manager.updateUser(newJoe);
this.manager.updateUser(newJoe);
UserDetails joe = manager.loadUserByUsername("joe");
UserDetails joe = this.manager.loadUserByUsername("joe");
assertThat(joe).isEqualTo(newJoe);
assertThat(cache.getUserMap().containsKey("joe")).isFalse();
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
}
@Test
@@ -183,40 +184,40 @@ public class JdbcUserDetailsManagerTests {
User newJoe = new User("joe", "newpassword", false, false, false, true,
AuthorityUtils.createAuthorityList("D", "F", "E"));
manager.updateUser(newJoe);
this.manager.updateUser(newJoe);
UserDetails joe = manager.loadUserByUsername(newJoe.getUsername());
UserDetails joe = this.manager.loadUserByUsername(newJoe.getUsername());
assertThat(joe).isEqualToComparingFieldByField(newJoe);
assertThat(cache.getUserMap().containsKey(newJoe.getUsername())).isFalse();
assertThat(this.cache.getUserMap().containsKey(newJoe.getUsername())).isFalse();
}
@Test
public void userExistsReturnsFalseForNonExistentUsername() {
assertThat(manager.userExists("joe")).isFalse();
assertThat(this.manager.userExists("joe")).isFalse();
}
@Test
public void userExistsReturnsTrueForExistingUsername() {
insertJoe();
assertThat(manager.userExists("joe")).isTrue();
assertThat(cache.getUserMap().containsKey("joe")).isTrue();
assertThat(this.manager.userExists("joe")).isTrue();
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
}
@Test(expected = AccessDeniedException.class)
public void changePasswordFailsForUnauthenticatedUser() {
manager.changePassword("password", "newPassword");
this.manager.changePassword("password", "newPassword");
}
@Test
public void changePasswordSucceedsWithAuthenticatedUserAndNoAuthenticationManagerSet() {
insertJoe();
authenticateJoe();
manager.changePassword("wrongpassword", "newPassword");
UserDetails newJoe = manager.loadUserByUsername("joe");
this.manager.changePassword("wrongpassword", "newPassword");
UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("newPassword");
assertThat(cache.getUserMap().containsKey("joe")).isFalse();
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
}
@Test
@@ -226,9 +227,9 @@ public class JdbcUserDetailsManagerTests {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(currentAuth)).thenReturn(currentAuth);
manager.setAuthenticationManager(am);
manager.changePassword("password", "newPassword");
UserDetails newJoe = manager.loadUserByUsername("joe");
this.manager.setAuthenticationManager(am);
this.manager.changePassword("password", "newPassword");
UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("newPassword");
// The password in the context should also be altered
@@ -236,7 +237,7 @@ public class JdbcUserDetailsManagerTests {
assertThat(newAuth.getName()).isEqualTo("joe");
assertThat(newAuth.getDetails()).isEqualTo(currentAuth.getDetails());
assertThat(newAuth.getCredentials()).isNull();
assertThat(cache.getUserMap().containsKey("joe")).isFalse();
assertThat(this.cache.getUserMap().containsKey("joe")).isFalse();
}
@Test
@@ -246,25 +247,25 @@ public class JdbcUserDetailsManagerTests {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
manager.setAuthenticationManager(am);
this.manager.setAuthenticationManager(am);
try {
manager.changePassword("password", "newPassword");
this.manager.changePassword("password", "newPassword");
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
// Check password hasn't changed.
UserDetails newJoe = manager.loadUserByUsername("joe");
UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password");
assertThat(cache.getUserMap().containsKey("joe")).isTrue();
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue();
}
@Test
public void findAllGroupsReturnsExpectedGroupNames() {
List<String> groups = manager.findAllGroups();
List<String> groups = this.manager.findAllGroups();
assertThat(groups).hasSize(4);
Collections.sort(groups);
@@ -276,19 +277,19 @@ public class JdbcUserDetailsManagerTests {
@Test
public void findGroupMembersReturnsCorrectData() {
List<String> groupMembers = manager.findUsersInGroup("GROUP_0");
List<String> groupMembers = this.manager.findUsersInGroup("GROUP_0");
assertThat(groupMembers).hasSize(1);
assertThat(groupMembers.get(0)).isEqualTo("jerry");
groupMembers = manager.findUsersInGroup("GROUP_1");
groupMembers = this.manager.findUsersInGroup("GROUP_1");
assertThat(groupMembers).hasSize(2);
}
@Test
@SuppressWarnings("unchecked")
public void createGroupInsertsCorrectData() {
manager.createGroup("TEST_GROUP", AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y"));
this.manager.createGroup("TEST_GROUP", AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y"));
List roles = template.queryForList("select ga.authority from groups g, group_authorities ga "
List roles = this.template.queryForList("select ga.authority from groups g, group_authorities ga "
+ "where ga.group_id = g.id " + "and g.group_name = 'TEST_GROUP'");
assertThat(roles).hasSize(2);
@@ -296,78 +297,80 @@ public class JdbcUserDetailsManagerTests {
@Test
public void deleteGroupRemovesData() {
manager.deleteGroup("GROUP_0");
manager.deleteGroup("GROUP_1");
manager.deleteGroup("GROUP_2");
manager.deleteGroup("GROUP_3");
this.manager.deleteGroup("GROUP_0");
this.manager.deleteGroup("GROUP_1");
this.manager.deleteGroup("GROUP_2");
this.manager.deleteGroup("GROUP_3");
assertThat(template.queryForList("select * from group_authorities")).isEmpty();
assertThat(template.queryForList("select * from group_members")).isEmpty();
assertThat(template.queryForList("select id from groups")).isEmpty();
assertThat(this.template.queryForList("select * from group_authorities")).isEmpty();
assertThat(this.template.queryForList("select * from group_members")).isEmpty();
assertThat(this.template.queryForList("select id from groups")).isEmpty();
}
@Test
public void renameGroupIsSuccessful() {
manager.renameGroup("GROUP_0", "GROUP_X");
this.manager.renameGroup("GROUP_0", "GROUP_X");
assertThat(template.queryForObject("select id from groups where group_name = 'GROUP_X'", Integer.class))
assertThat(this.template.queryForObject("select id from groups where group_name = 'GROUP_X'", Integer.class))
.isZero();
}
@Test
public void addingGroupUserSetsCorrectData() {
manager.addUserToGroup("tom", "GROUP_0");
this.manager.addUserToGroup("tom", "GROUP_0");
assertThat(template.queryForList("select username from group_members where group_id = 0")).hasSize(2);
assertThat(this.template.queryForList("select username from group_members where group_id = 0")).hasSize(2);
}
@Test
public void removeUserFromGroupDeletesGroupMemberRow() {
manager.removeUserFromGroup("jerry", "GROUP_1");
this.manager.removeUserFromGroup("jerry", "GROUP_1");
assertThat(template.queryForList("select group_id from group_members where username = 'jerry'")).hasSize(1);
assertThat(this.template.queryForList("select group_id from group_members where username = 'jerry'"))
.hasSize(1);
}
@Test
public void findGroupAuthoritiesReturnsCorrectAuthorities() {
assertThat(AuthorityUtils.createAuthorityList("ROLE_A")).isEqualTo(manager.findGroupAuthorities("GROUP_0"));
assertThat(AuthorityUtils.createAuthorityList("ROLE_A"))
.isEqualTo(this.manager.findGroupAuthorities("GROUP_0"));
}
@Test
public void addGroupAuthorityInsertsCorrectGroupAuthorityRow() {
GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_X");
manager.addGroupAuthority("GROUP_0", auth);
this.manager.addGroupAuthority("GROUP_0", auth);
template.queryForObject("select authority from group_authorities where authority = 'ROLE_X' and group_id = 0",
String.class);
this.template.queryForObject(
"select authority from group_authorities where authority = 'ROLE_X' and group_id = 0", String.class);
}
@Test
public void deleteGroupAuthorityRemovesCorrectRows() {
GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_A");
manager.removeGroupAuthority("GROUP_0", auth);
assertThat(template.queryForList("select authority from group_authorities where group_id = 0")).isEmpty();
this.manager.removeGroupAuthority("GROUP_0", auth);
assertThat(this.template.queryForList("select authority from group_authorities where group_id = 0")).isEmpty();
manager.removeGroupAuthority("GROUP_2", auth);
assertThat(template.queryForList("select authority from group_authorities where group_id = 2")).hasSize(2);
this.manager.removeGroupAuthority("GROUP_2", auth);
assertThat(this.template.queryForList("select authority from group_authorities where group_id = 2")).hasSize(2);
}
// SEC-1156
@Test
public void createUserDoesNotSaveAuthoritiesIfEnableAuthoritiesIsFalse() {
manager.setEnableAuthorities(false);
manager.createUser(joe);
assertThat(template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
this.manager.setEnableAuthorities(false);
this.manager.createUser(joe);
assertThat(this.template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
}
// SEC-1156
@Test
public void updateUserDoesNotSaveAuthoritiesIfEnableAuthoritiesIsFalse() {
manager.setEnableAuthorities(false);
this.manager.setEnableAuthorities(false);
insertJoe();
template.execute("delete from authorities where username='joe'");
manager.updateUser(joe);
assertThat(template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
this.template.execute("delete from authorities where username='joe'");
this.manager.updateUser(joe);
assertThat(this.template.queryForList(SELECT_JOE_AUTHORITIES_SQL)).isEmpty();
}
// SEC-2166
@@ -376,7 +379,7 @@ public class JdbcUserDetailsManagerTests {
insertJoe();
UsernamePasswordAuthenticationToken currentAuth = new UsernamePasswordAuthenticationToken("joe", null,
AuthorityUtils.createAuthorityList("ROLE_USER"));
Authentication updatedAuth = manager.createNewAuthentication(currentAuth, "new");
Authentication updatedAuth = this.manager.createNewAuthentication(currentAuth, "new");
assertThat(updatedAuth.getCredentials()).isNull();
}
@@ -389,11 +392,11 @@ public class JdbcUserDetailsManagerTests {
}
private void insertJoe() {
template.execute("insert into users (username, password, enabled) values ('joe','password','true')");
template.execute("insert into authorities (username, authority) values ('joe','A')");
template.execute("insert into authorities (username, authority) values ('joe','B')");
template.execute("insert into authorities (username, authority) values ('joe','C')");
cache.putUserInCache(joe);
this.template.execute("insert into users (username, password, enabled) values ('joe','password','true')");
this.template.execute("insert into authorities (username, authority) values ('joe','A')");
this.template.execute("insert into authorities (username, authority) values ('joe','B')");
this.template.execute("insert into authorities (username, authority) values ('joe','C')");
this.cache.putUserInCache(joe);
}
private class MockUserCache implements UserCache {
@@ -401,19 +404,19 @@ public class JdbcUserDetailsManagerTests {
private Map<String, UserDetails> cache = new HashMap<>();
public UserDetails getUserFromCache(String username) {
return cache.get(username);
return this.cache.get(username);
}
public void putUserInCache(UserDetails user) {
cache.put(user.getUsername(), user);
this.cache.put(user.getUsername(), user);
}
public void removeUserFromCache(String username) {
cache.remove(username);
this.cache.remove(username);
}
Map<String, UserDetails> getUserMap() {
return cache;
return this.cache;
}
}

View File

@@ -43,13 +43,13 @@ public abstract class AbstractSecurityContextSchedulingTaskExecutorTests
@Test
public void prefersShortLivedTasks() {
executor = create();
executor.prefersShortLivedTasks();
verify(taskExecutorDelegate).prefersShortLivedTasks();
this.executor = create();
this.executor.prefersShortLivedTasks();
verify(this.taskExecutorDelegate).prefersShortLivedTasks();
}
protected SchedulingTaskExecutor getExecutor() {
return taskExecutorDelegate;
return this.taskExecutorDelegate;
}
protected abstract DelegatingSecurityContextSchedulingTaskExecutor create();

View File

@@ -36,7 +36,7 @@ public class CurrentSecurityContextSchedulingTaskExecutorTests
}
protected DelegatingSecurityContextSchedulingTaskExecutor create() {
return new DelegatingSecurityContextSchedulingTaskExecutor(taskExecutorDelegate);
return new DelegatingSecurityContextSchedulingTaskExecutor(this.taskExecutorDelegate);
}
}

View File

@@ -56,44 +56,44 @@ public class DelegatingSecurityContextTaskSchedulerTests {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(scheduler);
this.delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(this.scheduler);
}
@After
public void cleanup() {
delegatingSecurityContextTaskScheduler = null;
this.delegatingSecurityContextTaskScheduler = null;
}
@Test(expected = IllegalArgumentException.class)
public void testSchedulerIsNotNull() {
delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(null);
this.delegatingSecurityContextTaskScheduler = new DelegatingSecurityContextTaskScheduler(null);
}
@Test
public void testSchedulerWithRunnableAndTrigger() {
delegatingSecurityContextTaskScheduler.schedule(runnable, trigger);
verify(scheduler).schedule(any(Runnable.class), any(Trigger.class));
this.delegatingSecurityContextTaskScheduler.schedule(this.runnable, this.trigger);
verify(this.scheduler).schedule(any(Runnable.class), any(Trigger.class));
}
@Test
public void testSchedulerWithRunnableAndInstant() {
Instant date = Instant.now();
delegatingSecurityContextTaskScheduler.schedule(runnable, date);
verify(scheduler).schedule(any(Runnable.class), any(Date.class));
this.delegatingSecurityContextTaskScheduler.schedule(this.runnable, date);
verify(this.scheduler).schedule(any(Runnable.class), any(Date.class));
}
@Test
public void testScheduleAtFixedRateWithRunnableAndDate() {
Date date = new Date(1544751374L);
Duration duration = Duration.ofSeconds(4L);
delegatingSecurityContextTaskScheduler.scheduleAtFixedRate(runnable, date, 1000L);
verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), isA(Date.class), eq(1000L));
this.delegatingSecurityContextTaskScheduler.scheduleAtFixedRate(this.runnable, date, 1000L);
verify(this.scheduler).scheduleAtFixedRate(isA(Runnable.class), isA(Date.class), eq(1000L));
}
@Test
public void testScheduleAtFixedRateWithRunnableAndLong() {
delegatingSecurityContextTaskScheduler.scheduleAtFixedRate(runnable, 1000L);
verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(1000L));
this.delegatingSecurityContextTaskScheduler.scheduleAtFixedRate(this.runnable, 1000L);
verify(this.scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(1000L));
}
}

View File

@@ -36,7 +36,7 @@ public class ExplicitSecurityContextSchedulingTaskExecutorTests
}
protected DelegatingSecurityContextSchedulingTaskExecutor create() {
return new DelegatingSecurityContextSchedulingTaskExecutor(taskExecutorDelegate, securityContext);
return new DelegatingSecurityContextSchedulingTaskExecutor(this.taskExecutorDelegate, this.securityContext);
}
}

View File

@@ -44,29 +44,29 @@ public abstract class AbstractDelegatingSecurityContextAsyncTaskExecutorTests
@Before
public final void setUpExecutor() {
executor = create();
this.executor = create();
}
@Test
public void executeStartTimeout() {
executor.execute(runnable, 1);
verify(getExecutor()).execute(wrappedRunnable, 1);
this.executor.execute(this.runnable, 1);
verify(getExecutor()).execute(this.wrappedRunnable, 1);
}
@Test
public void submit() {
executor.submit(runnable);
verify(getExecutor()).submit(wrappedRunnable);
this.executor.submit(this.runnable);
verify(getExecutor()).submit(this.wrappedRunnable);
}
@Test
public void submitCallable() {
executor.submit(callable);
verify(getExecutor()).submit(wrappedCallable);
this.executor.submit(this.callable);
verify(getExecutor()).submit(this.wrappedCallable);
}
protected AsyncTaskExecutor getExecutor() {
return taskExecutorDelegate;
return this.taskExecutorDelegate;
}
protected abstract DelegatingSecurityContextAsyncTaskExecutor create();

View File

@@ -37,7 +37,7 @@ public class CurrentDelegatingSecurityContextAsyncTaskExecutorTests
@Override
protected DelegatingSecurityContextAsyncTaskExecutor create() {
return new DelegatingSecurityContextAsyncTaskExecutor(taskExecutorDelegate);
return new DelegatingSecurityContextAsyncTaskExecutor(this.taskExecutorDelegate);
}
}

View File

@@ -44,11 +44,11 @@ public class CurrentDelegatingSecurityContextTaskExecutorTests extends AbstractD
}
protected Executor getExecutor() {
return taskExecutorDelegate;
return this.taskExecutorDelegate;
}
protected DelegatingSecurityContextExecutor create() {
return new DelegatingSecurityContextTaskExecutor(taskExecutorDelegate);
return new DelegatingSecurityContextTaskExecutor(this.taskExecutorDelegate);
}
}

View File

@@ -37,7 +37,7 @@ public class ExplicitDelegatingSecurityContextAsyncTaskExecutorTests
@Override
protected DelegatingSecurityContextAsyncTaskExecutor create() {
return new DelegatingSecurityContextAsyncTaskExecutor(taskExecutorDelegate, securityContext);
return new DelegatingSecurityContextAsyncTaskExecutor(this.taskExecutorDelegate, this.securityContext);
}
}

View File

@@ -44,11 +44,11 @@ public class ExplicitDelegatingSecurityContextTaskExecutorTests extends Abstract
}
protected Executor getExecutor() {
return taskExecutorDelegate;
return this.taskExecutorDelegate;
}
protected DelegatingSecurityContextExecutor create() {
return new DelegatingSecurityContextTaskExecutor(taskExecutorDelegate, securityContext);
return new DelegatingSecurityContextTaskExecutor(this.taskExecutorDelegate, this.securityContext);
}
}