Removal of jmock test dependency and upgrading of mockito version to 1.8.5. Minor adjustments to other build deps and configurations (e.g. prevent groovy from being used as a transitive dep, since we only use it for tests).
This commit is contained in:
parent
aafc5f9038
commit
3c02989d67
|
@ -1,10 +1,8 @@
|
|||
package org.springframework.security.acls.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.acls.model.AccessControlEntry;
|
||||
import org.springframework.security.acls.model.Acl;
|
||||
|
@ -18,7 +16,6 @@ import org.springframework.security.acls.model.Sid;
|
|||
* @author Andrei Stefan
|
||||
*/
|
||||
public class AccessControlImplEntryTests {
|
||||
Mockery jmock = new JUnit4Mockery();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
@ -35,7 +32,7 @@ public class AccessControlImplEntryTests {
|
|||
|
||||
// Check Sid field is present
|
||||
try {
|
||||
new AccessControlEntryImpl(null, jmock.mock(Acl.class), null,
|
||||
new AccessControlEntryImpl(null, mock(Acl.class), null,
|
||||
BasePermission.ADMINISTRATION, true, true, true);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
|
@ -44,7 +41,7 @@ public class AccessControlImplEntryTests {
|
|||
|
||||
// Check Permission field is present
|
||||
try {
|
||||
new AccessControlEntryImpl(null, jmock.mock(Acl.class), new PrincipalSid("johndoe"), null,
|
||||
new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null,
|
||||
true, true, true);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
|
@ -54,11 +51,11 @@ public class AccessControlImplEntryTests {
|
|||
|
||||
@Test
|
||||
public void testAccessControlEntryImplGetters() {
|
||||
Acl mockAcl = jmock.mock(Acl.class);
|
||||
Acl mockAcl = mock(Acl.class);
|
||||
Sid sid = new PrincipalSid("johndoe");
|
||||
|
||||
// Create a sample entry
|
||||
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
|
||||
AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.ADMINISTRATION,
|
||||
true, true, true);
|
||||
|
||||
// and check every get() method
|
||||
|
@ -73,32 +70,31 @@ public class AccessControlImplEntryTests {
|
|||
|
||||
@Test
|
||||
public void testEquals() {
|
||||
final Acl mockAcl = jmock.mock(Acl.class);
|
||||
final ObjectIdentity oid = jmock.mock(ObjectIdentity.class);
|
||||
jmock.checking(new Expectations() {{
|
||||
allowing(mockAcl).getObjectIdentity(); will(returnValue(oid));
|
||||
}});
|
||||
final Acl mockAcl = mock(Acl.class);
|
||||
final ObjectIdentity oid = mock(ObjectIdentity.class);
|
||||
|
||||
when(mockAcl.getObjectIdentity()).thenReturn(oid);
|
||||
Sid sid = new PrincipalSid("johndoe");
|
||||
|
||||
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
|
||||
AccessControlEntry ace = new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.ADMINISTRATION,
|
||||
true, true, true);
|
||||
|
||||
assertFalse(ace.equals(null));
|
||||
assertFalse(ace.equals(new Long(100)));
|
||||
assertFalse(ace.equals(Long.valueOf(100)));
|
||||
assertTrue(ace.equals(ace));
|
||||
assertTrue(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
|
||||
assertTrue(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
|
||||
BasePermission.ADMINISTRATION, true, true, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(2), mockAcl, sid,
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(2), mockAcl, sid,
|
||||
BasePermission.ADMINISTRATION, true, true, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, new PrincipalSid("scott"),
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, new PrincipalSid("scott"),
|
||||
BasePermission.ADMINISTRATION, true, true, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.WRITE, true,
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid, BasePermission.WRITE, true,
|
||||
true, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
|
||||
BasePermission.ADMINISTRATION, false, true, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
|
||||
BasePermission.ADMINISTRATION, true, false, true)));
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
|
||||
assertFalse(ace.equals(new AccessControlEntryImpl(Long.valueOf(1), mockAcl, sid,
|
||||
BasePermission.ADMINISTRATION, true, true, false)));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,11 @@
|
|||
package org.springframework.security.acls.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
|
||||
import org.jmock.Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -50,7 +46,6 @@ public class AclImplTests {
|
|||
private static final List<Sid> BEN = Arrays.asList((Sid)new PrincipalSid("ben"));
|
||||
|
||||
Authentication auth = new TestingAuthenticationToken("joe", "ignored", "ROLE_ADMINISTRATOR");
|
||||
Mockery jmockCtx = new Mockery();
|
||||
AclAuthorizationStrategy authzStrategy;
|
||||
PermissionGrantingStrategy pgs;
|
||||
AuditLogger mockAuditLogger;
|
||||
|
|
|
@ -1,13 +1,11 @@
|
|||
package org.springframework.security.acls.domain;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -21,29 +19,17 @@ import org.springframework.security.acls.model.AuditableAccessControlEntry;
|
|||
*/
|
||||
public class AuditLoggerTests {
|
||||
//~ Instance fields ================================================================================================
|
||||
private Mockery jmock = new JUnit4Mockery();
|
||||
private PrintStream console;
|
||||
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
private ConsoleAuditLogger logger;
|
||||
private AuditableAccessControlEntry ace;
|
||||
private Expectations aceRequiresAudit;
|
||||
private Expectations aceDoesntRequireAudit;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger = new ConsoleAuditLogger();
|
||||
ace = jmock.mock(AuditableAccessControlEntry.class);
|
||||
aceRequiresAudit = new Expectations() {{
|
||||
allowing(ace).isAuditSuccess(); will(returnValue(true));
|
||||
allowing(ace).isAuditFailure(); will(returnValue(true));
|
||||
}};
|
||||
aceDoesntRequireAudit = new Expectations() {{
|
||||
allowing(ace).isAuditSuccess(); will(returnValue(false));
|
||||
allowing(ace).isAuditFailure(); will(returnValue(false));
|
||||
}};
|
||||
|
||||
ace = mock(AuditableAccessControlEntry.class);
|
||||
console = System.out;
|
||||
System.setOut(new PrintStream(bytes));
|
||||
}
|
||||
|
@ -56,35 +42,36 @@ public class AuditLoggerTests {
|
|||
|
||||
@Test
|
||||
public void nonAuditableAceIsIgnored() {
|
||||
AccessControlEntry ace = jmock.mock(AccessControlEntry.class);
|
||||
AccessControlEntry ace = mock(AccessControlEntry.class);
|
||||
logger.logIfNeeded(true, ace);
|
||||
assertEquals(0, bytes.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
|
||||
jmock.checking(aceDoesntRequireAudit);
|
||||
when(ace.isAuditSuccess()).thenReturn(false);
|
||||
logger.logIfNeeded(true, ace);
|
||||
assertEquals(0, bytes.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successIsLoggedIfAceRequiresSuccessAudit() throws Exception {
|
||||
jmock.checking(aceRequiresAudit);
|
||||
when(ace.isAuditSuccess()).thenReturn(true);
|
||||
|
||||
logger.logIfNeeded(true, ace);
|
||||
assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
|
||||
jmock.checking(aceDoesntRequireAudit);
|
||||
when(ace.isAuditFailure()).thenReturn(false);
|
||||
logger.logIfNeeded(false, ace);
|
||||
assertEquals(0, bytes.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
|
||||
jmock.checking(aceRequiresAudit);
|
||||
when(ace.isAuditFailure()).thenReturn(true);
|
||||
logger.logIfNeeded(false, ace);
|
||||
assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
|
||||
}
|
||||
|
|
|
@ -14,7 +14,7 @@ allprojects {
|
|||
mavenRepo name: 'SpringSource Maven Snapshot Repo', urls: 'http://maven.springframework.org/snapshot/'
|
||||
mavenRepo name: 'SpringSource Enterprise Release', urls: 'http://repository.springsource.com/maven/bundles/release'
|
||||
mavenRepo name: 'SpringSource Enterprise External', urls: 'http://repository.springsource.com/maven/bundles/external'
|
||||
mavenRepo(name: 'Spock Snapshots', urls: 'http://m2repo.spockframework.org/snapshots')
|
||||
// mavenRepo(name: 'Spock Snapshots', urls: 'http://m2repo.spockframework.org/snapshots')
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,7 +32,7 @@ configure(javaProjects) {
|
|||
|
||||
configure(coreModuleProjects) {
|
||||
apply from: "$rootDir/gradle/bundlor.gradle"
|
||||
apply from: "$rootDir/gradle/maven.gradle"
|
||||
apply from: "$rootDir/gradle/maven-deployment.gradle"
|
||||
// Gives better names in structure101 jar diagram
|
||||
sourceSets.main.classesDir = new File(buildDir, "classes/" + project.name.substring("spring-security".length() + 1))
|
||||
}
|
||||
|
|
|
@ -4,6 +4,12 @@ apply plugin: 'groovy'
|
|||
|
||||
compileTestJava.dependsOn(':spring-security-core:compileTestJava')
|
||||
|
||||
configurations {
|
||||
// GRADLE-1124
|
||||
compile.extendsFrom = [provided]
|
||||
testCompile.extendsFrom groovy
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile project(':spring-security-core'),
|
||||
project(':spring-security-web'),
|
||||
|
|
|
@ -11,7 +11,6 @@ dependencies {
|
|||
"org.springframework:spring-tx:$springVersion",
|
||||
"org.springframework:spring-web:$springVersion",
|
||||
"org.aspectj:aspectjrt:$aspectjVersion",
|
||||
"org.aspectj:aspectjweaver:$aspectjVersion",
|
||||
'javax.annotation:jsr250-api:1.0'
|
||||
|
||||
testCompile 'commons-collections:commons-collections:3.2',
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
package org.springframework.security.access.expression.method;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.expression.Expression;
|
||||
|
@ -23,18 +24,17 @@ public class MethodSecurityExpressionRootTests {
|
|||
SpelExpressionParser parser = new SpelExpressionParser();
|
||||
MethodSecurityExpressionRoot root;
|
||||
StandardEvaluationContext ctx;
|
||||
Mockery jmock = new Mockery();
|
||||
private AuthenticationTrustResolver trustResolver;
|
||||
private Authentication user;
|
||||
|
||||
|
||||
@Before
|
||||
public void createContext() {
|
||||
user = jmock.mock(Authentication.class);
|
||||
user = mock(Authentication.class);
|
||||
root = new MethodSecurityExpressionRoot(user);
|
||||
ctx = new StandardEvaluationContext();
|
||||
ctx.setRootObject(root);
|
||||
trustResolver = jmock.mock(AuthenticationTrustResolver.class);
|
||||
trustResolver = mock(AuthenticationTrustResolver.class);
|
||||
root.setTrustResolver(trustResolver);
|
||||
}
|
||||
|
||||
|
@ -48,42 +48,35 @@ public class MethodSecurityExpressionRootTests {
|
|||
|
||||
@Test
|
||||
public void isAnonymousReturnsTrueIfTrustResolverReportsAnonymous() {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(trustResolver).isAnonymous(user); will(returnValue(true));
|
||||
}});
|
||||
when(trustResolver.isAnonymous(user)).thenReturn(true);
|
||||
assertTrue(root.isAnonymous());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isAnonymousReturnsFalseIfTrustResolverReportsNonAnonymous() {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(trustResolver).isAnonymous(user); will(returnValue(false));
|
||||
}});
|
||||
when(trustResolver.isAnonymous(user)).thenReturn(false);
|
||||
assertFalse(root.isAnonymous());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes() throws Exception {
|
||||
final Object dummyDomainObject = new Object();
|
||||
final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
|
||||
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
|
||||
ctx.setVariable("domainObject", dummyDomainObject);
|
||||
root.setPermissionEvaluator(pe);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(pe).hasPermission(user, dummyDomainObject, "ignored"); will(returnValue(false));
|
||||
}});
|
||||
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(false);
|
||||
|
||||
assertFalse(root.hasPermission(dummyDomainObject, "ignored"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes() throws Exception {
|
||||
final Object dummyDomainObject = new Object();
|
||||
final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
|
||||
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
|
||||
ctx.setVariable("domainObject", dummyDomainObject);
|
||||
root.setPermissionEvaluator(pe);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(pe).hasPermission(user, dummyDomainObject, "ignored"); will(returnValue(true));
|
||||
}});
|
||||
when(pe.hasPermission(user, dummyDomainObject, "ignored")).thenReturn(true);
|
||||
|
||||
assertTrue(root.hasPermission(dummyDomainObject, "ignored"));
|
||||
}
|
||||
|
@ -93,13 +86,11 @@ public class MethodSecurityExpressionRootTests {
|
|||
public void hasPermissionOnDomainObjectWorksWithIntegerExpressions() throws Exception {
|
||||
final Object dummyDomainObject = new Object();
|
||||
ctx.setVariable("domainObject", dummyDomainObject);
|
||||
final PermissionEvaluator pe = jmock.mock(PermissionEvaluator.class);
|
||||
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
|
||||
root.setPermissionEvaluator(pe);
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
exactly(3).of(pe).hasPermission(with(user), with(dummyDomainObject), with(any(Integer.class)));
|
||||
will(onConsecutiveCalls(returnValue(true), returnValue(true), returnValue(false)));
|
||||
}});
|
||||
when(pe.hasPermission(eq(user), eq(dummyDomainObject), any(Integer.class))).thenReturn(true)
|
||||
.thenReturn(true)
|
||||
.thenReturn(false);
|
||||
|
||||
Expression e = parser.parseExpression("hasPermission(#domainObject, 0xA)");
|
||||
// evaluator returns true
|
||||
|
|
|
@ -1,27 +1,21 @@
|
|||
package org.springframework.security.access.hierarchicalroles;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JMock;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
|
||||
@RunWith(JMock.class)
|
||||
@SuppressWarnings("deprecation")
|
||||
public class UserDetailsServiceWrapperTests {
|
||||
|
||||
private UserDetailsService wrappedUserDetailsService = null;
|
||||
private UserDetailsServiceWrapper userDetailsServiceWrapper = null;
|
||||
private Mockery jmockContext = new JUnit4Mockery();
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
@ -29,12 +23,10 @@ public class UserDetailsServiceWrapperTests {
|
|||
roleHierarchy.setHierarchy("ROLE_A > ROLE_B");
|
||||
final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
final UserDetailsService wrappedUserDetailsService = jmockContext.mock(UserDetailsService.class);
|
||||
final UserDetailsService wrappedUserDetailsService = mock(UserDetailsService.class);
|
||||
when(wrappedUserDetailsService.loadUserByUsername("EXISTING_USER")).thenReturn(user);
|
||||
when(wrappedUserDetailsService.loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION")).thenThrow(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION"));
|
||||
|
||||
jmockContext.checking( new Expectations() {{
|
||||
allowing(wrappedUserDetailsService).loadUserByUsername("EXISTING_USER"); will(returnValue(user));
|
||||
allowing(wrappedUserDetailsService).loadUserByUsername("USERNAME_NOT_FOUND_EXCEPTION"); will(throwException(new UsernameNotFoundException("USERNAME_NOT_FOUND_EXCEPTION")));
|
||||
}});
|
||||
this.wrappedUserDetailsService = wrappedUserDetailsService;
|
||||
userDetailsServiceWrapper = new UserDetailsServiceWrapper();
|
||||
userDetailsServiceWrapper.setRoleHierarchy(roleHierarchy);
|
||||
|
|
|
@ -15,15 +15,13 @@
|
|||
|
||||
package org.springframework.security.access.intercept.aopalliance;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -37,12 +35,12 @@ import org.springframework.security.access.SecurityConfig;
|
|||
import org.springframework.security.access.intercept.AfterInvocationManager;
|
||||
import org.springframework.security.access.intercept.RunAsManager;
|
||||
import org.springframework.security.access.intercept.RunAsUserToken;
|
||||
import org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor;
|
||||
import org.springframework.security.access.method.MethodSecurityMetadataSource;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
|
@ -53,7 +51,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
|||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class MethodSecurityInterceptorTests {
|
||||
private Mockery jmock = new JUnit4Mockery();
|
||||
private TestingAuthenticationToken token;
|
||||
private MethodSecurityInterceptor interceptor;
|
||||
private ITargetObject realTarget;
|
||||
|
@ -62,9 +59,6 @@ public class MethodSecurityInterceptorTests {
|
|||
private MethodSecurityMetadataSource mds;
|
||||
private AuthenticationManager authman;
|
||||
|
||||
private Expectations mdsWillReturnNullFromGetAttributes;
|
||||
private Expectations mdsWillReturnROLE_USERFromGetAttributes;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Before
|
||||
|
@ -72,20 +66,13 @@ public class MethodSecurityInterceptorTests {
|
|||
SecurityContextHolder.clearContext();
|
||||
token = new TestingAuthenticationToken("Test", "Password");
|
||||
interceptor = new MethodSecurityInterceptor();
|
||||
adm = jmock.mock(AccessDecisionManager.class);
|
||||
authman = jmock.mock(AuthenticationManager.class);
|
||||
mds = jmock.mock(MethodSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
authman = mock(AuthenticationManager.class);
|
||||
mds = mock(MethodSecurityMetadataSource.class);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setAuthenticationManager(authman);
|
||||
interceptor.setSecurityMetadataSource(mds);
|
||||
createTarget(false);
|
||||
|
||||
mdsWillReturnNullFromGetAttributes = new Expectations() {{
|
||||
oneOf(mds).getAttributes(with(any(MethodInvocation.class))); will (returnValue(null));
|
||||
}};
|
||||
mdsWillReturnROLE_USERFromGetAttributes = new Expectations() {{
|
||||
oneOf(mds).getAttributes(with(any(MethodInvocation.class))); will (returnValue(SecurityConfig.createList("ROLE_USER")));
|
||||
}};
|
||||
}
|
||||
|
||||
@After
|
||||
|
@ -94,7 +81,7 @@ public class MethodSecurityInterceptorTests {
|
|||
}
|
||||
|
||||
private void createTarget(boolean useMock) {
|
||||
realTarget = useMock ? jmock.mock(ITargetObject.class) : new TargetObject();
|
||||
realTarget = useMock ? mock(ITargetObject.class) : new TargetObject();
|
||||
ProxyFactory pf = new ProxyFactory(realTarget);
|
||||
pf.addAdvice(interceptor);
|
||||
advisedTarget = (ITargetObject) pf.getProxy();
|
||||
|
@ -102,8 +89,8 @@ public class MethodSecurityInterceptorTests {
|
|||
|
||||
@Test
|
||||
public void gettersReturnExpectedData() {
|
||||
RunAsManager runAs = jmock.mock(RunAsManager.class);
|
||||
AfterInvocationManager aim = jmock.mock(AfterInvocationManager.class);
|
||||
RunAsManager runAs = mock(RunAsManager.class);
|
||||
AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
interceptor.setRunAsManager(runAs);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
assertEquals(adm, interceptor.getAccessDecisionManager());
|
||||
|
@ -139,87 +126,70 @@ public class MethodSecurityInterceptorTests {
|
|||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void initializationRejectsSecurityMetadataSourceThatDoesNotSupportMethodInvocation() throws Throwable {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).supports(MethodInvocation.class); will(returnValue(false));
|
||||
}});
|
||||
when(mds.supports(MethodInvocation.class)).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void initializationRejectsAccessDecisionManagerThatDoesNotSupportMethodInvocation() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
|
||||
oneOf(adm).supports(MethodInvocation.class); will(returnValue(false));
|
||||
}});
|
||||
interceptor.afterPropertiesSet();
|
||||
when(mds.supports(MethodInvocation.class)).thenReturn(true);
|
||||
when(adm.supports(MethodInvocation.class)).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void intitalizationRejectsRunAsManagerThatDoesNotSupportMethodInvocation() throws Exception {
|
||||
final RunAsManager ram = jmock.mock(RunAsManager.class);
|
||||
jmock.checking(new Expectations() {{
|
||||
ignoring(mds);
|
||||
oneOf(ram).supports(MethodInvocation.class); will(returnValue(false));
|
||||
}});
|
||||
final RunAsManager ram = mock(RunAsManager.class);
|
||||
when(ram.supports(MethodInvocation.class)).thenReturn(false);
|
||||
interceptor.setRunAsManager(ram);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void intitalizationRejectsAfterInvocationManagerThatDoesNotSupportMethodInvocation() throws Exception {
|
||||
final AfterInvocationManager aim = jmock.mock(AfterInvocationManager.class);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(aim).supports(MethodInvocation.class); will(returnValue(false));
|
||||
ignoring(anything());
|
||||
}});
|
||||
final AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
when(aim.supports(MethodInvocation.class)).thenReturn(false);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void initializationFailsIfAccessDecisionManagerRejectsConfigAttributes() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(adm).supports(with(aNonNull(ConfigAttribute.class))); will(returnValue(false));
|
||||
ignoring(anything());
|
||||
}});
|
||||
when(adm.supports(any(ConfigAttribute.class))).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validationNotAttemptedIfIsValidateConfigAttributesSetToFalse() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
|
||||
oneOf(adm).supports(MethodInvocation.class); will(returnValue(true));
|
||||
never(mds).getAllConfigAttributes();
|
||||
never(adm).supports(with(any(ConfigAttribute.class)));
|
||||
}});
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validationNotAttemptedIfMethodSecurityMetadataSourceReturnsNullForAttributes() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).supports(MethodInvocation.class); will(returnValue(true));
|
||||
oneOf(adm).supports(MethodInvocation.class); will(returnValue(true));
|
||||
oneOf(mds).getAllConfigAttributes(); will(returnValue(null));
|
||||
never(adm).supports(with(any(ConfigAttribute.class)));
|
||||
}});
|
||||
when(adm.supports(MethodInvocation.class)).thenReturn(true);
|
||||
when(mds.supports(MethodInvocation.class)).thenReturn(true);
|
||||
when(mds.getAllConfigAttributes()).thenReturn(null);
|
||||
|
||||
interceptor.setValidateConfigAttributes(true);
|
||||
interceptor.afterPropertiesSet();
|
||||
verify(adm, never()).supports(any(ConfigAttribute.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingAPublicMethodFacadeWillNotRepeatSecurityChecksWhenPassedToTheSecuredMethodItFronts() {
|
||||
jmock.checking(mdsWillReturnNullFromGetAttributes);
|
||||
mdsReturnsNull();
|
||||
String result = advisedTarget.publicMakeLowerCase("HELLO");
|
||||
assertEquals("hello Authentication empty", result);
|
||||
jmock.assertIsSatisfied();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingAPublicMethodWhenPresentingAnAuthenticationObjectDoesntChangeItsAuthenticatedProperty() {
|
||||
jmock.checking(mdsWillReturnNullFromGetAttributes);
|
||||
mdsReturnsNull();
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertEquals("hello org.springframework.security.authentication.TestingAuthenticationToken false",
|
||||
advisedTarget.publicMakeLowerCase("HELLO"));
|
||||
|
@ -227,14 +197,12 @@ public class MethodSecurityInterceptorTests {
|
|||
}
|
||||
|
||||
@Test(expected=AuthenticationException.class)
|
||||
public void callIsWhenAuthenticationManagerRejectsAuthentication() throws Exception {
|
||||
public void callIsntMadeWhenAuthenticationManagerRejectsAuthentication() throws Exception {
|
||||
final TestingAuthenticationToken token = new TestingAuthenticationToken("Test", "Password");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
|
||||
jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(authman).authenticate(token); will(throwException(new BadCredentialsException("rejected")));
|
||||
}});
|
||||
mdsReturnsUserRole();
|
||||
when(authman.authenticate(token)).thenThrow(new BadCredentialsException("rejected"));
|
||||
|
||||
advisedTarget.makeLowerCase("HELLO");
|
||||
}
|
||||
|
@ -243,10 +211,7 @@ public class MethodSecurityInterceptorTests {
|
|||
public void callSucceedsIfAccessDecisionManagerGrantsAccess() throws Exception {
|
||||
token.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(adm).decide(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
|
||||
}});
|
||||
mdsReturnsUserRole();
|
||||
|
||||
String result = advisedTarget.makeLowerCase("HELLO");
|
||||
|
||||
|
@ -259,12 +224,9 @@ public class MethodSecurityInterceptorTests {
|
|||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
// Use mocked target to make sure invocation doesn't happen (not in expectations so test would fail)
|
||||
createTarget(true);
|
||||
jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(authman).authenticate(token); will(returnValue(token));
|
||||
oneOf(adm).decide(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
|
||||
will(throwException(new AccessDeniedException("rejected")));
|
||||
}});
|
||||
mdsReturnsUserRole();
|
||||
when(authman.authenticate(token)).thenReturn(token);
|
||||
doThrow(new AccessDeniedException("rejected")).when(adm).decide(any(Authentication.class), any(MethodInvocation.class), any(List.class));
|
||||
|
||||
advisedTarget.makeUpperCase("HELLO");
|
||||
}
|
||||
|
@ -278,16 +240,12 @@ public class MethodSecurityInterceptorTests {
|
|||
public void runAsReplacementIsCorrectlySet() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
token.setAuthenticated(true);
|
||||
final RunAsManager runAs = jmock.mock(RunAsManager.class);
|
||||
final RunAsManager runAs = mock(RunAsManager.class);
|
||||
final RunAsUserToken runAsToken =
|
||||
new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), TestingAuthenticationToken.class);
|
||||
interceptor.setRunAsManager(runAs);
|
||||
jmock.checking(mdsWillReturnROLE_USERFromGetAttributes);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(runAs).buildRunAs(with(token), with(aNonNull(MethodInvocation.class)), with(aNonNull(List.class)));
|
||||
will(returnValue(runAsToken));
|
||||
ignoring(anything());
|
||||
}});
|
||||
mdsReturnsUserRole();
|
||||
when(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).thenReturn(runAsToken);
|
||||
|
||||
String result = advisedTarget.makeUpperCase("hello");
|
||||
assertEquals("HELLO org.springframework.security.access.intercept.RunAsUserToken true", result);
|
||||
|
@ -297,9 +255,15 @@ public class MethodSecurityInterceptorTests {
|
|||
|
||||
@Test(expected=AuthenticationCredentialsNotFoundException.class)
|
||||
public void emptySecurityContextIsRejected() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
ignoring(anything());
|
||||
}});
|
||||
mdsReturnsUserRole();
|
||||
advisedTarget.makeUpperCase("hello");
|
||||
}
|
||||
|
||||
void mdsReturnsNull() {
|
||||
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(null);
|
||||
}
|
||||
|
||||
void mdsReturnsUserRole() {
|
||||
when(mds.getAttributes(any(MethodInvocation.class))).thenReturn(SecurityConfig.createList("ROLE_USER"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,13 +16,11 @@
|
|||
package org.springframework.security.access.intercept.method;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.ITargetObject;
|
||||
|
@ -47,7 +45,6 @@ import org.springframework.security.util.MethodInvocationUtils;
|
|||
* @author Ben Alex
|
||||
*/
|
||||
public class MethodInvocationPrivilegeEvaluatorTests {
|
||||
private Mockery jmock = new JUnit4Mockery();
|
||||
private TestingAuthenticationToken token;
|
||||
private MethodSecurityInterceptor interceptor;
|
||||
private AccessDecisionManager adm;
|
||||
|
@ -61,9 +58,9 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
|||
SecurityContextHolder.clearContext();
|
||||
interceptor = new MethodSecurityInterceptor();
|
||||
token = new TestingAuthenticationToken("Test", "Password", "ROLE_SOMETHING");
|
||||
adm = jmock.mock(AccessDecisionManager.class);
|
||||
AuthenticationManager authman = jmock.mock(AuthenticationManager.class);
|
||||
mds = jmock.mock(MethodSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
AuthenticationManager authman = mock(AuthenticationManager.class);
|
||||
mds = mock(MethodSecurityMetadataSource.class);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setAuthenticationManager(authman);
|
||||
interceptor.setSecurityMetadataSource(mds);
|
||||
|
@ -75,10 +72,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
|||
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
|
||||
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).getAttributes(mi); will(returnValue(role));
|
||||
oneOf(adm).decide(token, mi, role);
|
||||
}});
|
||||
when(mds.getAttributes(mi)).thenReturn(role);
|
||||
|
||||
mipe.setSecurityInterceptor(interceptor);
|
||||
mipe.afterPropertiesSet();
|
||||
|
@ -92,10 +86,7 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
|||
new Class[] {String.class}, new Object[] {"Hello world"});
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
mipe.setSecurityInterceptor(interceptor);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).getAttributes(mi); will(returnValue(role));
|
||||
oneOf(adm).decide(token, mi, role);
|
||||
}});
|
||||
when(mds.getAttributes(mi)).thenReturn(role);
|
||||
|
||||
assertTrue(mipe.isAllowed(mi, token));
|
||||
}
|
||||
|
@ -103,13 +94,11 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
|||
@Test
|
||||
public void declinesAccessUsingCreate() throws Exception {
|
||||
Object object = new TargetObject();
|
||||
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", new Object[] {"foobar"});
|
||||
final MethodInvocation mi = MethodInvocationUtils.create(object, "makeLowerCase", "foobar");
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
mipe.setSecurityInterceptor(interceptor);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).getAttributes(mi); will(returnValue(role));
|
||||
oneOf(adm).decide(token, mi, role); will(throwException(new AccessDeniedException("rejected")));
|
||||
}});
|
||||
when(mds.getAttributes(mi)).thenReturn(role);
|
||||
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
|
||||
|
||||
assertFalse(mipe.isAllowed(mi, token));
|
||||
}
|
||||
|
@ -121,10 +110,8 @@ public class MethodInvocationPrivilegeEvaluatorTests {
|
|||
|
||||
MethodInvocationPrivilegeEvaluator mipe = new MethodInvocationPrivilegeEvaluator();
|
||||
mipe.setSecurityInterceptor(interceptor);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(mds).getAttributes(mi); will(returnValue(role));
|
||||
oneOf(adm).decide(token, mi, role); will(throwException(new AccessDeniedException("rejected")));
|
||||
}});
|
||||
when(mds.getAttributes(mi)).thenReturn(role);
|
||||
doThrow(new AccessDeniedException("rejected")).when(adm).decide(token, mi, role);
|
||||
|
||||
assertFalse(mipe.isAllowed(mi, token));
|
||||
}
|
||||
|
|
|
@ -31,11 +31,7 @@ dependencies {
|
|||
}
|
||||
|
||||
testCompile 'junit:junit:4.7',
|
||||
'org.mockito:mockito-core:1.8.3',
|
||||
'org.jmock:jmock:2.5.1',
|
||||
'org.jmock:jmock-junit4:2.5.1',
|
||||
'org.hamcrest:hamcrest-core:1.1',
|
||||
'org.hamcrest:hamcrest-library:1.1',
|
||||
'org.mockito:mockito-core:1.8.5',
|
||||
"org.springframework:spring-test:$springVersion"
|
||||
|
||||
// Use slf4j/logback for logging
|
||||
|
|
|
@ -15,17 +15,13 @@
|
|||
|
||||
package org.springframework.security.ldap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import javax.naming.NamingException;
|
||||
import javax.naming.directory.DirContext;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JMock;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
|
||||
/**
|
||||
|
@ -33,41 +29,31 @@ import org.junit.runner.RunWith;
|
|||
*
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
@RunWith(JMock.class)
|
||||
public class LdapUtilsTests {
|
||||
Mockery context = new JUnit4Mockery();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testCloseContextSwallowsNamingException() throws Exception {
|
||||
final DirContext dirCtx = context.mock(DirContext.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(dirCtx).close(); will(throwException(new NamingException()));
|
||||
}});
|
||||
final DirContext dirCtx = mock(DirContext.class);
|
||||
doThrow(new NamingException()).when(dirCtx).close();
|
||||
|
||||
LdapUtils.closeContext(dirCtx);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
|
||||
final DirContext mockCtx = context.mock(DirContext.class);
|
||||
final DirContext mockCtx = mock(DirContext.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
|
||||
}});
|
||||
when(mockCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
|
||||
|
||||
assertEquals("", LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
|
||||
final DirContext mockCtx = context.mock(DirContext.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue(""));
|
||||
}});
|
||||
final DirContext mockCtx = mock(DirContext.class);
|
||||
when(mockCtx.getNameInNamespace()).thenReturn("");
|
||||
|
||||
assertEquals("cn=jane,dc=springframework,dc=org",
|
||||
LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx));
|
||||
|
@ -75,11 +61,8 @@ public class LdapUtilsTests {
|
|||
|
||||
@Test
|
||||
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
|
||||
final DirContext mockCtx = context.mock(DirContext.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
atLeast(1).of(mockCtx).getNameInNamespace(); will(returnValue("dc=springsecurity,dc = org"));
|
||||
}});
|
||||
final DirContext mockCtx = mock(DirContext.class);
|
||||
when(mockCtx.getNameInNamespace()).thenReturn("dc=springsecurity,dc = org");
|
||||
|
||||
assertEquals("cn=jane smith",
|
||||
LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx));
|
||||
|
|
|
@ -16,12 +16,10 @@
|
|||
package org.springframework.security.ldap.authentication;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.*;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Test;
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
import org.springframework.ldap.core.DirContextOperations;
|
||||
|
@ -43,7 +41,6 @@ import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
|
|||
* @author Luke Taylor
|
||||
*/
|
||||
public class LdapAuthenticationProviderTests {
|
||||
Mockery jmock = new JUnit4Mockery();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
@ -81,11 +78,9 @@ public class LdapAuthenticationProviderTests {
|
|||
|
||||
@Test(expected=BadCredentialsException.class)
|
||||
public void usernameNotFoundExceptionIsHiddenByDefault() {
|
||||
final LdapAuthenticator authenticator = jmock.mock(LdapAuthenticator.class);
|
||||
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
|
||||
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(authenticator).authenticate(joe); will(throwException(new UsernameNotFoundException("nobody")));
|
||||
}});
|
||||
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
|
||||
|
||||
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
|
||||
provider.authenticate(joe);
|
||||
|
@ -93,11 +88,9 @@ public class LdapAuthenticationProviderTests {
|
|||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
|
||||
final LdapAuthenticator authenticator = jmock.mock(LdapAuthenticator.class);
|
||||
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
|
||||
final UsernamePasswordAuthenticationToken joe = new UsernamePasswordAuthenticationToken("joe", "password");
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(authenticator).authenticate(joe); will(throwException(new UsernameNotFoundException("nobody")));
|
||||
}});
|
||||
when(authenticator.authenticate(joe)).thenThrow(new UsernameNotFoundException("nobody"));
|
||||
|
||||
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
|
||||
provider.setHideUserNotFoundExceptions(false);
|
||||
|
|
|
@ -15,19 +15,19 @@
|
|||
|
||||
package org.springframework.security.ldap.authentication;
|
||||
|
||||
import javax.naming.directory.Attributes;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import javax.naming.NamingEnumeration;
|
||||
import javax.naming.directory.BasicAttribute;
|
||||
import javax.naming.directory.BasicAttributes;
|
||||
import javax.naming.directory.DirContext;
|
||||
import javax.naming.directory.SearchControls;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Test;
|
||||
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator;
|
||||
|
||||
|
||||
/**
|
||||
|
@ -35,14 +35,13 @@ import org.springframework.security.ldap.authentication.PasswordComparisonAuthen
|
|||
* @author Luke Taylor
|
||||
*/
|
||||
public class PasswordComparisonAuthenticatorMockTests {
|
||||
Mockery jmock = new JUnit4Mockery();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void ldapCompareOperationIsUsedWhenPasswordIsNotRetrieved() throws Exception {
|
||||
final DirContext dirCtx = jmock.mock(DirContext.class);
|
||||
final BaseLdapPathContextSource source = jmock.mock(BaseLdapPathContextSource.class);
|
||||
final DirContext dirCtx = mock(DirContext.class);
|
||||
final BaseLdapPathContextSource source = mock(BaseLdapPathContextSource.class);
|
||||
final BasicAttributes attrs = new BasicAttributes();
|
||||
attrs.put(new BasicAttribute("uid", "bob"));
|
||||
|
||||
|
@ -51,26 +50,18 @@ public class PasswordComparisonAuthenticatorMockTests {
|
|||
authenticator.setUserDnPatterns(new String[] {"cn={0},ou=people"});
|
||||
|
||||
// Get the mock to return an empty attribute set
|
||||
jmock.checking(new Expectations() {{
|
||||
allowing(source).getReadOnlyContext(); will(returnValue(dirCtx));
|
||||
oneOf(dirCtx).getAttributes(with(equal("cn=Bob,ou=people")), with(aNull(String[].class))); will(returnValue(attrs));
|
||||
oneOf(dirCtx).getNameInNamespace(); will(returnValue("dc=springframework,dc=org"));
|
||||
}});
|
||||
when(source.getReadOnlyContext()).thenReturn(dirCtx);
|
||||
when(dirCtx.getAttributes(eq("cn=Bob,ou=people"), any(String[].class))).thenReturn(attrs);
|
||||
when(dirCtx.getNameInNamespace()).thenReturn("dc=springframework,dc=org");
|
||||
|
||||
// Setup a single return value (i.e. success)
|
||||
final Attributes searchResults = new BasicAttributes("", null);
|
||||
final NamingEnumeration searchResults = new BasicAttributes("", null).getAll();
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(dirCtx).search(with(equal("cn=Bob,ou=people")),
|
||||
with(equal("(userPassword={0})")),
|
||||
with(aNonNull(Object[].class)),
|
||||
with(aNonNull(SearchControls.class)));
|
||||
will(returnValue(searchResults.getAll()));
|
||||
atLeast(1).of(dirCtx).close();
|
||||
}});
|
||||
when(dirCtx.search(eq("cn=Bob,ou=people"),
|
||||
eq("(userPassword={0})"),
|
||||
any(Object[].class),
|
||||
any(SearchControls.class))).thenReturn(searchResults);
|
||||
|
||||
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Bob","bobspassword"));
|
||||
|
||||
jmock.assertIsSatisfied();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,7 +23,6 @@ import org.springframework.security.authentication.encoding.PlaintextPasswordEnc
|
|||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.ldap.AbstractLdapIntegrationTests;
|
||||
import org.springframework.security.ldap.authentication.PasswordComparisonAuthenticator;
|
||||
|
||||
|
||||
import org.springframework.ldap.core.DirContextAdapter;
|
||||
|
|
|
@ -20,8 +20,6 @@ import javax.servlet.jsp.el.VariableResolver;
|
|||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.jmock.Mockery;
|
||||
import org.springframework.mock.web.MockPageContext;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
@ -33,7 +31,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
|||
* Test case to implement commons-el expression language expansion.
|
||||
*/
|
||||
public class AuthorizeTagExpressionLanguageTests extends TestCase {
|
||||
Mockery jmock = new Mockery();
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final LegacyAuthorizeTag authorizeTag = new LegacyAuthorizeTag();
|
||||
|
|
|
@ -15,13 +15,12 @@
|
|||
|
||||
package org.springframework.security.web.access.intercept;
|
||||
|
||||
import java.util.List;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.*;
|
||||
import javax.servlet.FilterChain;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -38,17 +37,15 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
|
|||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link FilterSecurityInterceptor}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class FilterSecurityInterceptorTests {
|
||||
private Mockery jmock = new JUnit4Mockery();
|
||||
private AuthenticationManager am;
|
||||
private AccessDecisionManager adm;
|
||||
private FilterInvocationSecurityMetadataSource ods;
|
||||
|
@ -62,11 +59,11 @@ public class FilterSecurityInterceptorTests {
|
|||
@Before
|
||||
public final void setUp() throws Exception {
|
||||
interceptor = new FilterSecurityInterceptor();
|
||||
am = jmock.mock(AuthenticationManager.class);
|
||||
ods = jmock.mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = jmock.mock(AccessDecisionManager.class);
|
||||
ram = jmock.mock(RunAsManager.class);
|
||||
publisher = jmock.mock(ApplicationEventPublisher.class);
|
||||
am = mock(AuthenticationManager.class);
|
||||
ods = mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
ram = mock(RunAsManager.class);
|
||||
publisher = mock(ApplicationEventPublisher.class);
|
||||
interceptor.setAuthenticationManager(am);
|
||||
interceptor.setSecurityMetadataSource(ods);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
|
@ -82,19 +79,13 @@ public class FilterSecurityInterceptorTests {
|
|||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
ignoring(ods);
|
||||
allowing(adm).supports(FilterInvocation.class); will(returnValue(false));
|
||||
}});
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(true);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
|
||||
jmock.checking(new Expectations() {{
|
||||
ignoring(ods);
|
||||
allowing(ram).supports(FilterInvocation.class); will(returnValue(false));
|
||||
}});
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
|
@ -113,19 +104,14 @@ public class FilterSecurityInterceptorTests {
|
|||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
|
||||
// Create and test our secure object
|
||||
final FilterChain chain = jmock.mock(FilterChain.class);
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
final List<ConfigAttribute> attributes = SecurityConfig.createList("MOCK_OK");
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
ignoring(ram);
|
||||
allowing(ods).getAttributes(fi); will(returnValue(attributes));
|
||||
oneOf(adm).decide(token, fi, attributes);
|
||||
// Setup our expectation that the filter chain will be invoked, as access is granted
|
||||
oneOf(chain).doFilter(request, response);
|
||||
oneOf(publisher).publishEvent(with(aNonNull(AuthorizedEvent.class)));
|
||||
}});
|
||||
when(ods.getAttributes(fi)).thenReturn(attributes);
|
||||
|
||||
interceptor.invoke(fi);
|
||||
|
||||
verify(publisher).publishEvent(any(AuthorizedEvent.class));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,17 +16,15 @@
|
|||
package org.springframework.security.web.authentication.rememberme;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices.*;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import java.util.*;
|
||||
import javax.servlet.http.Cookie;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
@ -38,7 +36,6 @@ import org.springframework.security.core.userdetails.User;
|
|||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
|
@ -47,30 +44,27 @@ import org.springframework.util.StringUtils;
|
|||
* @author Ben Alex
|
||||
*/
|
||||
public class TokenBasedRememberMeServicesTests {
|
||||
private Mockery jmock = new JUnit4Mockery();
|
||||
private UserDetailsService uds;
|
||||
private UserDetails user = new User("someone", "password", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_ABC"));
|
||||
private TokenBasedRememberMeServices services;
|
||||
private Expectations udsWillReturnUser;
|
||||
private Expectations udsWillThrowNotFound;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Before
|
||||
public void createTokenBasedRememberMeServices() {
|
||||
services = new TokenBasedRememberMeServices();
|
||||
uds = jmock.mock(UserDetailsService.class);
|
||||
uds = mock(UserDetailsService.class);
|
||||
services.setKey("key");
|
||||
services.setUserDetailsService(uds);
|
||||
udsWillReturnUser = new Expectations() {{
|
||||
oneOf(uds).loadUserByUsername(with(aNonNull(String.class))); will(returnValue(user));
|
||||
}};
|
||||
udsWillThrowNotFound = new Expectations() {{
|
||||
oneOf(uds).loadUserByUsername(with(aNonNull(String.class)));
|
||||
will(throwException(new UsernameNotFoundException("")));
|
||||
}};
|
||||
}
|
||||
|
||||
void udsWillReturnUser() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenReturn(user);
|
||||
}
|
||||
|
||||
void udsWillThrowNotFound() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
|
||||
}
|
||||
|
||||
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
|
||||
|
@ -79,8 +73,8 @@ public class TokenBasedRememberMeServicesTests {
|
|||
|
||||
if (cookieTokens.length == 3) {
|
||||
try {
|
||||
return new Long(cookieTokens[1]).longValue();
|
||||
} catch (NumberFormatException nfe) {}
|
||||
return Long.parseLong(cookieTokens[1]);
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
|
||||
return -1;
|
||||
|
@ -89,11 +83,10 @@ public class TokenBasedRememberMeServicesTests {
|
|||
private String generateCorrectCookieContentForToken(long expiryTime, String username, String password, String key) {
|
||||
// format is:
|
||||
// username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" + password + ":" + key)
|
||||
String signatureValue = new String(DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key));
|
||||
String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key);
|
||||
String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
|
||||
String tokenValueBase64 = new String(Base64.encodeBase64(tokenValue.getBytes()));
|
||||
|
||||
return tokenValueBase64;
|
||||
return new String(Base64.encodeBase64(tokenValue.getBytes()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -110,7 +103,7 @@ public class TokenBasedRememberMeServicesTests {
|
|||
public void autoLoginIgnoresUnrelatedCookie() throws Exception {
|
||||
Cookie cookie = new Cookie("unrelated_cookie", "foobar");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
@ -124,7 +117,7 @@ public class TokenBasedRememberMeServicesTests {
|
|||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
|
@ -139,7 +132,7 @@ public class TokenBasedRememberMeServicesTests {
|
|||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
new String(Base64.encodeBase64("x".getBytes())));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
@ -154,7 +147,7 @@ public class TokenBasedRememberMeServicesTests {
|
|||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
"NOT_BASE_64_ENCODED");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
@ -166,12 +159,12 @@ public class TokenBasedRememberMeServicesTests {
|
|||
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() throws Exception {
|
||||
jmock.checking(udsWillReturnUser);
|
||||
udsWillReturnUser();
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
|
||||
"WRONG_KEY"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
|
@ -187,7 +180,7 @@ public class TokenBasedRememberMeServicesTests {
|
|||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
@ -199,11 +192,11 @@ public class TokenBasedRememberMeServicesTests {
|
|||
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfUserNotFound() throws Exception {
|
||||
jmock.checking(udsWillThrowNotFound);
|
||||
udsWillThrowNotFound();
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
|
@ -216,11 +209,11 @@ public class TokenBasedRememberMeServicesTests {
|
|||
|
||||
@Test
|
||||
public void autoLoginWithValidTokenAndUserSucceeds() throws Exception {
|
||||
jmock.checking(udsWillReturnUser);
|
||||
udsWillReturnUser();
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(new Cookie[] {cookie});
|
||||
request.setCookies(cookie);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
|
|
|
@ -19,8 +19,7 @@ import static org.junit.Assert.*;
|
|||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
import java.util.*;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
|
@ -28,9 +27,6 @@ import javax.servlet.ServletRequest;
|
|||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
@ -88,22 +84,17 @@ public class DigestAuthenticationFilterTests {
|
|||
final boolean expectChainToProceed) throws ServletException, IOException {
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Mockery jmockContext = new JUnit4Mockery();
|
||||
final FilterChain chain = jmockContext.mock(FilterChain.class);
|
||||
|
||||
jmockContext.checking(new Expectations() {{
|
||||
exactly(expectChainToProceed ? 1 : 0).of(chain).doFilter(request, response);
|
||||
}});
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
jmockContext.assertIsSatisfied();
|
||||
verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
private static String generateNonce(int validitySeconds) {
|
||||
long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
|
||||
String signatureValue = new String(DigestUtils.md5Hex(expiryTime + ":" + KEY));
|
||||
String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + KEY);
|
||||
String nonceValue = expiryTime + ":" + signatureValue;
|
||||
|
||||
return new String(Base64.encodeBase64(nonceValue.getBytes()));
|
||||
|
|
|
@ -1,22 +1,15 @@
|
|||
package org.springframework.security.web.context;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
@ -27,7 +20,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
|||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
|
||||
public class SecurityContextPersistenceFilterTests {
|
||||
Mockery jmock = new JUnit4Mockery();
|
||||
TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A");
|
||||
|
||||
@After
|
||||
|
@ -37,31 +29,25 @@ public class SecurityContextPersistenceFilterTests {
|
|||
|
||||
@Test
|
||||
public void contextIsClearedAfterChainProceeds() throws Exception {
|
||||
final FilterChain chain = jmock.mock(FilterChain.class);
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(chain).doFilter(with(aNonNull(HttpServletRequest.class)), with(aNonNull(HttpServletResponse.class)));
|
||||
}});
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception {
|
||||
final FilterChain chain = jmock.mock(FilterChain.class);
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(chain).doFilter(with(aNonNull(HttpServletRequest.class)), with(aNonNull(HttpServletResponse.class)));
|
||||
will(throwException(new IOException()));
|
||||
}});
|
||||
doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
try {
|
||||
filter.doFilter(request, response, chain);
|
||||
fail();
|
||||
|
@ -81,13 +67,10 @@ public class SecurityContextPersistenceFilterTests {
|
|||
final SecurityContext scExpectedAfter = new SecurityContextImpl();
|
||||
scExpectedAfter.setAuthentication(testToken);
|
||||
scBefore.setAuthentication(beforeAuth);
|
||||
final SecurityContextRepository repo = jmock.mock(SecurityContextRepository.class);
|
||||
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
|
||||
filter.setSecurityContextRepository(repo);
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(repo).loadContext(with(aNonNull(HttpRequestResponseHolder.class))); will(returnValue(scBefore));
|
||||
oneOf(repo).saveContext(scExpectedAfter, request, response);
|
||||
}});
|
||||
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
|
||||
|
||||
final FilterChain chain = new FilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
|
@ -99,30 +82,25 @@ public class SecurityContextPersistenceFilterTests {
|
|||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
jmock.assertIsSatisfied();
|
||||
verify(repo).saveContext(scExpectedAfter, request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
|
||||
final FilterChain chain = jmock.mock(FilterChain.class);
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
filter.setSecurityContextRepository(jmock.mock(SecurityContextRepository.class));
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
oneOf(chain).doFilter(request, response);
|
||||
}});
|
||||
filter.setSecurityContextRepository(mock(SecurityContextRepository.class));
|
||||
|
||||
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
|
||||
filter.doFilter(request, response, chain);
|
||||
jmock.assertIsSatisfied();
|
||||
verify(chain).doFilter(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
|
||||
final FilterChain chain = jmock.mock(FilterChain.class);
|
||||
jmock.checking(new Expectations() {{ ignoring(chain); }});
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
|
|
|
@ -15,17 +15,15 @@
|
|||
|
||||
package org.springframework.security.web.servletapi;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.Mockery;
|
||||
import org.jmock.integration.junit4.JUnit4Mockery;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
|
||||
|
||||
|
||||
/**
|
||||
|
@ -34,7 +32,6 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
|
|||
* @author Ben Alex
|
||||
*/
|
||||
public class SecurityContextHolderAwareRequestFilterTests {
|
||||
Mockery jmock = new JUnit4Mockery();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
@ -42,19 +39,15 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
|||
public void expectedRequestWrapperClassIsUsed() throws Exception {
|
||||
SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
|
||||
filter.setRolePrefix("ROLE_");
|
||||
// filter.init(jmock.mock(FilterConfig.class));
|
||||
final FilterChain filterChain = jmock.mock(FilterChain.class);
|
||||
|
||||
jmock.checking(new Expectations() {{
|
||||
exactly(2).of(filterChain).doFilter(
|
||||
with(aNonNull(SecurityContextHolderAwareRequestWrapper.class)), with(aNonNull(HttpServletResponse.class)));
|
||||
}});
|
||||
final FilterChain filterChain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
|
||||
|
||||
// Now re-execute the filter, ensuring our replacement wrapper is still used
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), filterChain);
|
||||
|
||||
verify(filterChain, times(2)).doFilter(any(SecurityContextHolderAwareRequestWrapper.class), any(HttpServletResponse.class));
|
||||
|
||||
filter.destroy();
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue