Replace try/catch with AssertJ

Replace manual try/catch/fail blocks with AssertJ calls.
This commit is contained in:
Phillip Webb 2020-09-10 12:06:07 -07:00 committed by Josh Cummings
parent d9276ed8f3
commit 910b81928f
98 changed files with 717 additions and 2122 deletions

View File

@ -22,7 +22,8 @@ import org.springframework.security.acls.domain.AclFormattingUtils;
import org.springframework.security.acls.model.Permission;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* Tests for {@link AclFormattingUtils}.
@ -33,30 +34,11 @@ public class AclFormattingUtilsTests {
@Test
public final void testDemergePatternsParametersConstraints() {
try {
AclFormattingUtils.demergePatterns(null, "SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING"));
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null));
assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"));
assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"));
}
@Test
@ -71,29 +53,11 @@ public class AclFormattingUtilsTests {
@Test
public final void testMergePatternsParametersConstraints() {
try {
AclFormattingUtils.mergePatterns(null, "SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
}
catch (IllegalArgumentException notExpected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING"));
assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null));
assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"));
assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"));
}
@Test
@ -108,18 +72,10 @@ public class AclFormattingUtilsTests {
@Test
public final void testBinaryPrints() {
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON));
assertThatIllegalArgumentException()
.isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF));
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx");
}

View File

@ -36,7 +36,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
@ -50,15 +51,12 @@ import static org.mockito.Mockito.verify;
@SuppressWarnings({ "unchecked" })
public class AclEntryAfterInvocationProviderTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void rejectsMissingPermissions() {
try {
new AclEntryAfterInvocationProvider(mock(AclService.class), null);
fail("Exception expected");
}
catch (IllegalArgumentException expected) {
}
new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList());
assertThatIllegalArgumentException()
.isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null));
assertThatIllegalArgumentException().isThrownBy(
() -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList()));
}
@Test
@ -98,7 +96,7 @@ public class AclEntryAfterInvocationProviderTests {
SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
@Test(expected = AccessDeniedException.class)
@Test
public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
@ -113,16 +111,13 @@ public class AclEntryAfterInvocationProviderTests {
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
try {
provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object());
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
// Second scenario with no acls found
provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object());
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
}
@Test

View File

@ -25,7 +25,7 @@ import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -39,27 +39,14 @@ public class AccessControlImplEntryTests {
@Test
public void testConstructorRequiredFields() {
// Check Acl field is present
try {
new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true,
true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, null,
new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, true, true));
// Check Sid field is present
try {
new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), null,
BasePermission.ADMINISTRATION, true, true, true));
// Check Permission field is present
try {
new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class),
new PrincipalSid("johndoe"), null, true, true, true));
}
@Test

View File

@ -46,7 +46,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -97,58 +98,38 @@ public class AclImplTests {
SecurityContextHolder.clearContext();
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorsRejectNullObjectIdentity() {
try {
new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger);
assertThatIllegalArgumentException().isThrownBy(
() -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")));
assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorsRejectNullId() {
try {
new AclImpl(this.objectIdentity, null, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger);
assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy,
this.pgs, null, null, true, new PrincipalSid("joe")));
assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger));
}
@SuppressWarnings("deprecation")
@Test(expected = IllegalArgumentException.class)
@Test
public void constructorsRejectNullAclAuthzStrategy() {
try {
new AclImpl(this.objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null,
null, true, new PrincipalSid("joe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger);
assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null,
new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true,
new PrincipalSid("joe")));
assertThatIllegalArgumentException()
.isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger));
}
@Test
public void insertAceRejectsNullParameters() {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
try {
acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
acl.insertAce(0, BasePermission.READ, null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true));
assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true));
}
@Test
@ -232,12 +213,7 @@ public class AclImplTests {
new SimpleGrantedAuthority("ROLE_GENERAL"));
MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
try {
acl.deleteAce(99);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(99));
}
@Test
@ -245,18 +221,9 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
Sid ben = new PrincipalSid("ben");
try {
acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
acl.isGranted(READ, new ArrayList<>(0), false);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false));
assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false));
}
@Test
@ -277,25 +244,16 @@ public class AclImplTests {
List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE);
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse();
try {
rootAcl.isGranted(permissions, SCOTT, false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false));
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse();
assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue();
try {
// Change the type of the Sid and check the granting process
rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Change the type of the Sid and check the granting process
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false));
}
@Test
@ -348,18 +306,9 @@ public class AclImplTests {
assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child2 (doesn't inherit the permissions from its
// parent)
try {
assertThat(childAcl2.isGranted(CREATE, SCOTT, false)).isTrue();
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false));
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false));
}
@Test

View File

@ -30,7 +30,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl} security
@ -72,24 +73,12 @@ public class AclImplementationSecurityCheckTests {
new SimpleGrantedAuthority("ROLE_THREE"));
Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL));
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING));
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
}
@Test
@ -112,28 +101,16 @@ public class AclImplementationSecurityCheckTests {
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities,
// nor granting access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
// Add granting access to this principal
aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag
// (false) will deny this access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING));
// Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access
MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
@ -143,27 +120,15 @@ public class AclImplementationSecurityCheckTests {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
// Add a deny ACE and test again for CHANGE_AUDITING
aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
assertThatNoException().isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING));
// Create an ACL with no ACE
MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING));
// and still grant access for CHANGE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
assertThatNoException().isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL));
}
@Test
@ -184,22 +149,14 @@ public class AclImplementationSecurityCheckTests {
MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger());
// Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
// Link the child with its parent and test again against the
// CHANGE_OWNERSHIP right
childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
assertThatNoException().isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
// Create a root parent and link it to the middle parent
MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
@ -207,12 +164,8 @@ public class AclImplementationSecurityCheckTests {
parentAcl.setEntriesInheriting(true);
parentAcl.setParent(rootParentAcl);
childAcl.setParent(parentAcl);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
assertThatNoException().isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
}
@Test
@ -227,24 +180,12 @@ public class AclImplementationSecurityCheckTests {
Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false,
new PrincipalSid(auth));
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It shouldn't have thrown AccessDeniedException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
assertThatNoException()
.isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL));
assertThatExceptionOfType(NotFoundException.class).isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING));
assertThatNoException().isThrownBy(
() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
}
}

View File

@ -21,7 +21,9 @@ import org.junit.Test;
import org.springframework.security.acls.model.ObjectIdentity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* Tests for {@link ObjectIdentityImpl}.
@ -36,40 +38,15 @@ public class ObjectIdentityImplTests {
@Test
public void constructorsRespectRequiredFields() {
// Check one-argument constructor required field
try {
new ObjectIdentityImpl(null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(null));
// Check String-Serializable constructor required field
try {
new ObjectIdentityImpl("", 1L);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L));
// Check Serializable parameter is not null
try {
new ObjectIdentityImpl(DOMAIN_CLASS, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, null));
// The correct way of using String-Serializable constructor
try {
new ObjectIdentityImpl(DOMAIN_CLASS, 1L);
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, 1L));
// Check the Class-Serializable constructor
try {
new ObjectIdentityImpl(MockIdDomainObject.class, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(MockIdDomainObject.class, null));
}
@Test
@ -82,35 +59,17 @@ public class ObjectIdentityImplTests {
@Test
public void testGetIdMethodConstraints() {
// Check the getId() method is present
try {
new ObjectIdentityImpl("A_STRING_OBJECT");
fail("It should have thrown IdentityUnavailableException");
}
catch (IdentityUnavailableException expected) {
}
assertThatExceptionOfType(IdentityUnavailableException.class)
.isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT"));
// getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject();
try {
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
// getId() should return a Serializable object
mockId.setId(new MockIdDomainObject());
try {
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
// getId() should return a Serializable object
mockId.setId(100L);
try {
new ObjectIdentityImpl(mockId);
}
catch (IllegalArgumentException expected) {
}
assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
}
@Test(expected = IllegalArgumentException.class)

View File

@ -48,14 +48,12 @@ import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AuditableAccessControlEntry;
import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/**
* Tests {@link BasicLookupStrategy}
@ -290,12 +288,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// is already in cache and the element before it must not be stored in
// cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try {
foundAcls = this.strategy.readAclsById(allOids, sids);
}
catch (NotFoundException notExpected) {
fail("It shouldn't have thrown NotFoundException");
}
foundAcls = this.strategy.readAclsById(allOids, sids);
Acl foundParent2Acl = foundAcls.get(parent2Oid);
assertThat(foundParent2Acl).isNotNull();
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();

View File

@ -52,7 +52,7 @@ import org.springframework.security.util.FieldUtils;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ -102,41 +102,11 @@ public class EhCacheBasedAclCacheTests {
@Test
public void methodsRejectNullParameters() {
try {
Serializable id = null;
this.myCache.evictFromCache(id);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.evictFromCache(obj);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
Serializable id = null;
this.myCache.getFromCache(id);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.getFromCache(obj);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
MutableAcl acl = null;
this.myCache.putInCache(acl);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((Serializable) null));
assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((ObjectIdentity) null));
assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((Serializable) null));
assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((ObjectIdentity) null));
assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.putInCache(null));
}
// SEC-527

View File

@ -55,7 +55,8 @@ import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.spy;
@ -161,91 +162,80 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService
.readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid()));
assertThat(map).hasSize(3);
// Replace our current objects with their retrieved versions
topParent = (MutableAcl) map.get(getTopParentOid());
middleParent = (MutableAcl) map.get(getMiddleParentOid());
child = (MutableAcl) map.get(getChildOid());
// Get the retrieved versions
MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid());
MutableAcl retrievedMiddleParent = (MutableAcl) map.get(getMiddleParentOid());
MutableAcl retrievedChild = (MutableAcl) map.get(getChildOid());
// Check the retrieved versions has IDs
assertThat(topParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull();
assertThat(retrievedTopParent.getId()).isNotNull();
assertThat(retrievedMiddleParent.getId()).isNotNull();
assertThat(retrievedChild.getId()).isNotNull();
// Check their parents were correctly persisted
assertThat(topParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid());
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
assertThat(retrievedTopParent.getParentAcl()).isNull();
assertThat(retrievedMiddleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid());
assertThat(retrievedChild.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Check their ACEs were correctly persisted
assertThat(topParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1);
assertThat(retrievedTopParent.getEntries()).hasSize(2);
assertThat(retrievedMiddleParent.getEntries()).hasSize(1);
assertThat(retrievedChild.getEntries()).hasSize(1);
// Check the retrieved rights are correct
List<Permission> read = Arrays.asList(BasePermission.READ);
List<Permission> write = Arrays.asList(BasePermission.WRITE);
List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth));
assertThat(topParent.isGranted(read, pSid, false)).isTrue();
assertThat(topParent.isGranted(write, pSid, false)).isFalse();
assertThat(middleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
try {
child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThat(retrievedTopParent.isGranted(read, pSid, false)).isTrue();
assertThat(retrievedTopParent.isGranted(write, pSid, false)).isFalse();
assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse();
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false));
// Now check the inherited rights (when not explicitly overridden) also look OK
assertThat(child.isGranted(read, pSid, false)).isTrue();
assertThat(child.isGranted(write, pSid, false)).isFalse();
assertThat(child.isGranted(delete, pSid, false)).isFalse();
assertThat(retrievedChild.isGranted(read, pSid, false)).isTrue();
assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse();
assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse();
// Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false);
this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.isEntriesInheriting()).isFalse();
retrievedChild.setEntriesInheriting(false);
this.jdbcMutableAclService.updateAcl(retrievedChild);
MutableAcl nonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(nonInheritingChild.isEntriesInheriting()).isFalse();
// Check the child permissions no longer inherit
assertThat(child.isGranted(delete, pSid, true)).isFalse();
try {
child.isGranted(read, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
child.isGranted(write, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse();
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true));
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true));
// Let's add an identical permission to the child, but it'll appear AFTER the
// current permission, so has no impact
child.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
// Let's also add another permission to the child
child.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true);
nonInheritingChild.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true);
// Save the changed child
this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.getEntries()).hasSize(3);
this.jdbcMutableAclService.updateAcl(nonInheritingChild);
MutableAcl retrievedNonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(retrievedNonInheritingChild.getEntries()).hasSize(3);
// Output permissions
for (int i = 0; i < child.getEntries().size(); i++) {
System.out.println(child.getEntries().get(i));
for (int i = 0; i < retrievedNonInheritingChild.getEntries().size(); i++) {
System.out.println(retrievedNonInheritingChild.getEntries().get(i));
}
// Check the permissions are as they should be
assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier
// permission
assertThat(retrievedNonInheritingChild.isGranted(delete, pSid, true)).isFalse(); // as
// earlier
// permission
// overrode
assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
assertThat(retrievedNonInheritingChild.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
// Now check the first ACE (index 0) really is DELETE for our Sid and is
// non-granting
AccessControlEntry entry = child.getEntries().get(0);
AccessControlEntry entry = retrievedNonInheritingChild.getEntries().get(0);
assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask());
assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth));
assertThat(entry.isGranting()).isFalse();
assertThat(entry.getId()).isNotNull();
// Now delete that first ACE
child.deleteAce(0);
retrievedNonInheritingChild.deleteAce(0);
// Save and check it worked
child = this.jdbcMutableAclService.updateAcl(child);
assertThat(child.getEntries()).hasSize(2);
assertThat(child.isGranted(delete, pSid, false)).isTrue();
MutableAcl savedChild = this.jdbcMutableAclService.updateAcl(retrievedNonInheritingChild);
assertThat(savedChild.getEntries()).hasSize(2);
assertThat(savedChild.isGranted(delete, pSid, false)).isTrue();
SecurityContextHolder.clearContext();
}
@ -267,18 +257,10 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Delete the mid-parent and test if the child was deleted, as well
this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true);
try {
this.jdbcMutableAclService.readAclById(getMiddleParentOid());
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
this.jdbcMutableAclService.readAclById(getChildOid());
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid()));
assertThatExceptionOfType(NotFoundException.class)
.isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid()));
Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid());
assertThat(acl).isNotNull();
assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity());
@ -286,34 +268,17 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test
public void constructorRejectsNullParameters() {
try {
new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new JdbcMutableAclService(this.dataSource, null, this.aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache));
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache));
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null));
}
@Test
public void createAclRejectsNullParameter() {
try {
this.jdbcMutableAclService.createAcl(null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.createAcl(null));
}
@Test
@ -323,23 +288,14 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
this.jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time
try {
this.jdbcMutableAclService.createAcl(duplicateOid);
fail("It should have thrown AlreadyExistsException");
}
catch (AlreadyExistsException expected) {
}
assertThatExceptionOfType(AlreadyExistsException.class)
.isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid));
}
@Test
@Transactional
public void deleteAclRejectsNullParameters() {
try {
this.jdbcMutableAclService.deleteAcl(null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(null, true));
}
@Test
@ -351,18 +307,16 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
// Specify the inheritance hierarchy
child.setParent(parent);
this.jdbcMutableAclService.updateAcl(child);
// switch on FK
this.jdbcMutableAclService.setForeignKeysInDatabase(false);
try {
this.jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK
// checking in the
// class, not database
this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false);
fail("It should have thrown ChildrenExistException");
}
catch (ChildrenExistException expected) {
// checking in the class, not database
assertThatExceptionOfType(ChildrenExistException.class)
.isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false));
}
finally {
this.jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the
// default
// restore to the default
this.jdbcMutableAclService.setForeignKeysInDatabase(true);
}
}

View File

@ -32,92 +32,36 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
public class SidTests {
@Test
public void testPrincipalSidConstructorsRequiredFields() {
// Check one String-argument constructor
try {
String string = null;
new PrincipalSid(string);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new PrincipalSid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new PrincipalSid("johndoe");
// throws no exception
assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((String) null));
assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid(""));
assertThatNoException().isThrownBy(() -> new PrincipalSid("johndoe"));
// Check one Authentication-argument constructor
try {
Authentication authentication = null;
new PrincipalSid(authentication);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
Authentication authentication = new TestingAuthenticationToken(null, "password");
new PrincipalSid(authentication);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
new PrincipalSid(authentication);
// throws no exception
assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null));
assertThatIllegalArgumentException()
.isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password")));
assertThatNoException()
.isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password")));
}
@Test
public void testGrantedAuthoritySidConstructorsRequiredFields() {
// Check one String-argument constructor
try {
String string = null;
new GrantedAuthoritySid(string);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("ROLE_TEST");
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((String) null));
assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid(""));
assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid("ROLE_TEST"));
// Check one GrantedAuthority-argument constructor
try {
GrantedAuthority ga = null;
new GrantedAuthoritySid(ga);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority(null);
new GrantedAuthoritySid(ga);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
new GrantedAuthoritySid(ga);
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null));
assertThatIllegalArgumentException()
.isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null)));
assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST")));
}
@Test

View File

@ -49,7 +49,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -112,12 +112,7 @@ public class AnnotationSecurityAspectTests {
@Test(expected = AccessDeniedException.class)
public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne);
try {
this.secured.publicCallsPrivate();
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate());
this.securedSub.publicCallsPrivate();
}

View File

@ -41,6 +41,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
@ -192,20 +193,10 @@ public class CasAuthenticationProviderTests {
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
try {
cap.authenticate(token);
fail("Expected Exception");
}
catch (IllegalStateException success) {
}
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.setServiceProperties(null);
cap.afterPropertiesSet();
try {
cap.authenticate(token);
fail("Expected Exception");
}
catch (IllegalStateException success) {
}
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
}
@Test(expected = BadCredentialsException.class)

View File

@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link CasAuthenticationToken}.
@ -52,44 +53,19 @@ public class CasAuthenticationTokenTests {
@Test
public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test");
try {
new CasAuthenticationToken(null, makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
Assertion assertion = new AssertionImpl("test");
assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken(null, makeUserDetails(),
"Password", this.ROLES, makeUserDetails(), assertion));
assertThatIllegalArgumentException().isThrownBy(
() -> new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion));
assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), null,
this.ROLES, makeUserDetails(), assertion));
assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(),
"Password", this.ROLES, makeUserDetails(), null));
assertThatIllegalArgumentException().isThrownBy(
() -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion));
assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(),
"Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion));
}
@Test(expected = IllegalArgumentException.class)
@ -125,12 +101,8 @@ public class CasAuthenticationTokenTests {
@Test
public void testNoArgConstructorDoesntExist() {
try {
CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
}
@Test

View File

@ -24,7 +24,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link EhCacheBasedTicketCache}.
@ -67,12 +67,7 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
@Test
public void testStartupDetectsMissingCache() throws Exception {
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
try {
cache.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet);
Ehcache myCache = cacheManager.getCache("castickets");
cache.setCache(myCache);
assertThat(cache.getCache()).isEqualTo(myCache);

View File

@ -25,7 +25,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.cas.ServiceProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link CasAuthenticationEntryPoint}.
@ -38,26 +38,16 @@ public class CasAuthenticationEntryPointTests {
public void testDetectsMissingLoginFormUrl() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setServiceProperties(new ServiceProperties());
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("loginUrl must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("loginUrl must be specified");
}
@Test
public void testDetectsMissingServiceProperties() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login");
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("serviceProperties must be specified");
}
@Test

View File

@ -22,7 +22,7 @@ import org.springframework.security.cas.SamlServiceProperties;
import org.springframework.security.cas.ServiceProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link ServiceProperties}.
@ -41,19 +41,9 @@ public class ServicePropertiesTests {
public void nullServiceWhenAuthenticateAllTokens() throws Exception {
ServiceProperties sp = new ServiceProperties();
sp.setAuthenticateAllArtifacts(true);
try {
sp.afterPropertiesSet();
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
sp.setAuthenticateAllArtifacts(false);
try {
sp.afterPropertiesSet();
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
}
@Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.config.authentication.AuthenticationManagerF
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests which make sure invalid configurations are rejected by the namespace. In
@ -59,17 +59,14 @@ public class InvalidConfigurationTests {
@Test
public void missingAuthenticationManagerGivesSensibleErrorMessage() {
try {
setContext("<http auto-config='true' />");
fail();
}
catch (BeanCreationException ex) {
Throwable cause = ultimateCause(ex);
assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue();
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
}
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> setContext("<http auto-config='true' />")).satisfies((ex) -> {
Throwable cause = ultimateCause(ex);
assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
});
}
private Throwable ultimateCause(Throwable ex) {

View File

@ -32,8 +32,7 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@ -78,15 +77,11 @@ public class SecurityNamespaceHandlerTests {
@Test
public void pre32SchemaAreNotSupported() {
try {
new InMemoryXmlApplicationContext("<user-service id='us'>"
+ " <user name='bob' password='bobspassword' authorities='ROLE_A' />" + "</user-service>", "3.0.3",
null);
fail("Expected BeanDefinitionParsingException");
}
catch (BeanDefinitionParsingException expected) {
assertThat(expected.getMessage().contains("You cannot use a spring-security-2.0.xsd"));
}
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> new InMemoryXmlApplicationContext(
"<user-service id='us'><user name='bob' password='bobspassword' authorities='ROLE_A' /></user-service>",
"3.0.3", null))
.withMessageContaining("You cannot use a spring-security-2.0.xsd");
}
// SEC-1868

View File

@ -54,6 +54,7 @@ import org.springframework.security.test.web.servlet.response.SecurityMockMvcRes
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -91,11 +92,8 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();
try {
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (AuthenticationException success) {
}
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")));
verify(aep).publishAuthenticationFailure(any(), any());
}

View File

@ -110,11 +110,8 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")));
assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
}

View File

@ -45,8 +45,7 @@ import org.springframework.web.socket.config.annotation.AbstractWebSocketMessage
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
@ -76,13 +75,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
public void securityMappings() {
loadConfig(WebSocketSecurityConfig.class);
clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE));
try {
clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
.withCauseInstanceOf(AccessDeniedException.class);
}
private void loadConfig(Class<?>... configs) {

View File

@ -78,7 +78,7 @@ import org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHa
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
@ -108,13 +108,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void simpleRegistryMappings() {
loadConfig(SockJsSecurityConfig.class);
clientInboundChannel().send(message("/permitAll"));
try {
clientInboundChannel().send(message("/denyAll"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
@ -158,13 +154,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel();
try {
messageChannel.send(message);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
.withCauseInstanceOf(MissingCsrfTokenException.class);
}
@Test
@ -173,13 +164,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel();
try {
messageChannel.send(message);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
.withCauseInstanceOf(MissingCsrfTokenException.class);
}
@Test
@ -236,39 +222,27 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void msmsRegistryCustomPatternMatcher() {
loadConfig(MsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a.b"));
try {
clientInboundChannel().send(message("/app/a.b.c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void overrideMsmsRegistryCustomPatternMatcher() {
loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b"));
try {
clientInboundChannel().send(message("/app/a/b/c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void defaultPatternMatcher() {
loadConfig(DefaultPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b"));
try {
clientInboundChannel().send(message("/app/a/b/c"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
@ -276,13 +250,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(CustomExpressionConfig.class);
clientInboundChannel().send(message("/denyRob"));
this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER");
try {
clientInboundChannel().send(message("/denyRob"));
fail("Expected Exception");
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
assertThatExceptionOfType(MessageDeliveryException.class)
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test

View File

@ -59,7 +59,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Ben Alex
@ -174,13 +174,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER
this.target.someOther(0);
try {
// String version should required admin role
this.target.someOther("somestring");
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// String version should required admin role
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.target.someOther("somestring"));
}
@Test
@ -199,12 +194,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// String method should not be protected
this.target.someOther("somestring");
// All others should require ROLE_USER
try {
this.target.someOther(0);
fail("Expected AuthenticationCredentialsNotFoundException");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.target.someOther(0));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
this.target.someOther(0);
@ -389,12 +380,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// External MDS should take precedence over PreAuthorize
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A"));
@ -415,12 +401,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// @formatter:on
SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target");
try {
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A"));

View File

@ -36,6 +36,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Ben Alex
*/
@ -93,11 +95,8 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Test(expected = AccessDeniedException.class)
public void targetIsSerializableAfterUse() throws Exception {
try {
this.target.someAdminMethod();
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(this.target::someAdminMethod);
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod();

View File

@ -26,7 +26,7 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for SEC-428 (and SEC-1204).
@ -97,12 +97,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
// Check both against interface and class
try {
target.makeLowerCase("TEST");
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
}
@ -128,12 +124,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target");
try {
target.makeLowerCase("TEST");
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> target.makeLowerCase("TEST"));
target.makeUpperCase("test");
}

View File

@ -25,7 +25,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* Tests for {@link RoleHierarchyImpl}.
@ -102,48 +103,23 @@ public class RoleHierarchyImplTests {
@Test
public void testCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"));
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"));
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"));
assertThatExceptionOfType(CycleInRoleHierarchyException.class).isThrownBy(() -> roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"));
assertThatExceptionOfType(CycleInRoleHierarchyException.class)
.isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B"));
}
@Test
public void testNoCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D");
}
catch (CycleInRoleHierarchyException ex) {
fail("A cycle in role hierarchy was incorrectly detected!");
}
assertThatNoException().isThrownBy(() -> roleHierarchyImpl
.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"));
}
// SEC-863

View File

@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AfterInvocationProviderManager}.
@ -72,13 +72,7 @@ public class AfterInvocationProviderManagerTests {
public void testRejectsEmptyProvidersList() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector();
try {
manager.setProviders(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list));
}
@Test
@ -88,25 +82,13 @@ public class AfterInvocationProviderManagerTests {
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(45);
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
try {
manager.setProviders(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list));
}
@Test
public void testRejectsNullProvidersList() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
try {
manager.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet);
}
@Test

View File

@ -26,6 +26,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
/**
@ -96,12 +97,7 @@ public class RunAsManagerImplTests {
@Test
public void testStartupDetectsMissingKey() throws Exception {
RunAsManagerImpl runAs = new RunAsManagerImpl();
try {
runAs.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(runAs::afterPropertiesSet);
}
@Test

View File

@ -22,7 +22,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests {@link RunAsUserToken}.
@ -52,14 +52,8 @@ public class RunAsUserTokenTests {
@Test
public void testNoArgConstructorDoesntExist() {
Class<RunAsUserToken> clazz = RunAsUserToken.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
assertThat(true).isTrue();
}
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> RunAsUserToken.class.getDeclaredConstructor((Class[]) null));
}
@Test

View File

@ -47,7 +47,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@ -251,12 +251,8 @@ public class MethodSecurityInterceptorTests {
given(this.authman.authenticate(this.token)).willReturn(this.token);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class));
try {
this.advisedTarget.makeUpperCase("HELLO");
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.advisedTarget.makeUpperCase("HELLO"));
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
}
@ -297,12 +293,7 @@ public class MethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
try {
this.advisedTarget.makeUpperCase("hello");
fail("Expected Exception");
}
catch (RuntimeException success) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@ -323,12 +314,7 @@ public class MethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
given(mi.proceed()).willThrow(new Throwable());
try {
this.interceptor.invoke(mi);
fail("Expected exception");
}
catch (Throwable expected) {
}
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.interceptor.invoke(mi));
verifyZeroInteractions(aim);
}

View File

@ -45,7 +45,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -127,12 +127,8 @@ public class AspectJMethodSecurityInterceptorTests {
public void callbackIsNotInvokedWhenPermissionDenied() {
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(this.token);
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
verify(this.aspectJCallback, never()).proceedWithObject();
}
@ -156,12 +152,8 @@ public class AspectJMethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
verifyZeroInteractions(aim);
}
@ -178,12 +170,8 @@ public class AspectJMethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint, this.aspectJCallback);
fail("Expected Exception");
}
catch (RuntimeException success) {
}
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@ -202,12 +190,7 @@ public class AspectJMethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
try {
this.interceptor.invoke(this.joinPoint);
fail("Expected Exception");
}
catch (RuntimeException success) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);

View File

@ -17,6 +17,7 @@
package org.springframework.security.access.vote;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
@ -28,7 +29,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AbstractAccessDecisionManager}.
@ -86,23 +87,12 @@ public class AbstractAccessDecisionManagerTests {
@Test
public void testRejectsEmptyList() {
List list = new Vector();
try {
new MockDecisionManagerImpl(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(Collections.emptyList()));
}
@Test
public void testRejectsNullVotersList() {
try {
new MockDecisionManagerImpl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null));
}
@Test
@ -113,12 +103,7 @@ public class AbstractAccessDecisionManagerTests {
@Test
public void testWillNotStartIfDecisionVotersNotSet() {
try {
new MockDecisionManagerImpl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null));
}
private class MockDecisionManagerImpl extends AbstractAccessDecisionManager {

View File

@ -30,7 +30,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AuthenticatedVoter}.
@ -82,12 +82,7 @@ public class AuthenticatedVoterTests {
@Test
public void testSetterRejectsNull() {
AuthenticatedVoter voter = new AuthenticatedVoter();
try {
voter.setAuthenticationTrustResolver(null);
fail("Expected IAE");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> voter.setAuthenticationTrustResolver(null));
}
@Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.TestingAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests {@link UnanimousBased}.
@ -73,12 +73,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" });
try {
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
}
@Test
@ -94,12 +89,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE");
try {
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
}
@Test
@ -116,12 +106,7 @@ public class UnanimousBasedTests {
UnanimousBased mgr = makeDecisionManager();
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
try {
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
}
@Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -171,12 +171,8 @@ public class ProviderManagerTests {
public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() {
ProviderManager mgr = new ProviderManager(Arrays
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
try {
mgr.authenticate(mock(Authentication.class));
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
}
// SEC-546
@ -186,12 +182,8 @@ public class ProviderManagerTests {
});
AuthenticationProvider otherProvider = mock(AuthenticationProvider.class);
ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider));
try {
authMgr.authenticate(mock(Authentication.class));
fail("Expected AccountStatusException");
}
catch (AccountStatusException expected) {
}
assertThatExceptionOfType(AccountStatusException.class)
.isThrownBy(() -> authMgr.authenticate(mock(Authentication.class)));
verifyNoInteractions(otherProvider);
}
@ -212,12 +204,8 @@ public class ProviderManagerTests {
});
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent);
try {
mgr.authenticate(mock(Authentication.class));
fail("Expected exception");
}
catch (AccountStatusException expected) {
}
assertThatExceptionOfType(AccountStatusException.class)
.isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
verifyNoInteractions(parent);
}
@ -232,13 +220,8 @@ public class ProviderManagerTests {
ProviderManager mgr = new ProviderManager(
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher);
try {
mgr.authenticate(authReq);
fail("Expected exception");
}
catch (BadCredentialsException expected) {
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
.satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
}
@Test
@ -251,15 +234,10 @@ public class ProviderManagerTests {
mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
given(parent.authenticate(authReq)).willThrow(expected);
try {
mgr.authenticate(authReq);
fail("Expected exception");
}
catch (BadCredentialsException ex) {
assertThat(ex).isSameAs(expected);
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
.isSameAs(expected);
}
@Test
@ -271,13 +249,7 @@ public class ProviderManagerTests {
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
try {
mgr.authenticate(authReq);
fail("Expected exception");
}
catch (LockedException ex) {
assertThat(ex).isSameAs(expected);
}
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
@ -287,13 +259,9 @@ public class ProviderManagerTests {
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected),
createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
final Authentication authReq = mock(Authentication.class);
try {
mgr.authenticate(authReq);
fail("Expected Exception");
}
catch (InternalAuthenticationServiceException success) {
}
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
.isThrownBy(() -> mgr.authenticate(authReq));
}
// gh-6281
@ -307,13 +275,8 @@ public class ProviderManagerTests {
parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher);
final Authentication authReq = mock(Authentication.class);
try {
childMgr.authenticate(authReq);
fail("Expected exception");
}
catch (BadCredentialsException ex) {
assertThat(ex).isSameAs(badCredentialsExParent);
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq))
.isSameAs(badCredentialsExParent);
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent
// publishes
verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event)

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link UsernamePasswordAuthenticationToken}.
@ -32,29 +32,25 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test
public void authenticatedPropertyContractIsSatisfied() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password",
UsernamePasswordAuthenticationToken grantedToken = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.NO_AUTHORITIES);
// check default given we passed some GrantedAuthorty[]s (well, we passed empty
// list)
assertThat(token.isAuthenticated()).isTrue();
assertThat(grantedToken.isAuthenticated()).isTrue();
// check explicit set to untrusted (we can safely go from trusted to untrusted,
// but not the reverse)
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
grantedToken.setAuthenticated(false);
assertThat(!grantedToken.isAuthenticated()).isTrue();
// Now let's create a UsernamePasswordAuthenticationToken without any
// GrantedAuthorty[]s (different constructor)
token = new UsernamePasswordAuthenticationToken("Test", "Password");
assertThat(!token.isAuthenticated()).isTrue();
UsernamePasswordAuthenticationToken noneGrantedToken = new UsernamePasswordAuthenticationToken("Test",
"Password");
assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
// check we're allowed to still set it to untrusted
token.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue();
noneGrantedToken.setAuthenticated(false);
assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
// check denied changing it to trusted
try {
token.setAuthenticated(true);
fail("Should have prohibited setAuthenticated(true)");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> noneGrantedToken.setAuthenticated(true));
}
@Test

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AnonymousAuthenticationProvider}.
@ -40,22 +41,12 @@ public class AnonymousAuthenticationProviderTests {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try {
aap.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token));
}
@Test
public void testDetectsMissingKey() {
try {
new AnonymousAuthenticationProvider(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationProvider(null));
}
@Test

View File

@ -27,7 +27,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AnonymousAuthenticationToken}.
@ -40,30 +41,11 @@ public class AnonymousAuthenticationTokenTests {
@Test
public void testConstructorRejectsNulls() {
try {
new AnonymousAuthenticationToken(null, "Test", ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", null, ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test", null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken(null, "Test", ROLES_12));
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", null, ROLES_12));
assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", null));
assertThatIllegalArgumentException()
.isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES));
}
@Test
@ -85,13 +67,8 @@ public class AnonymousAuthenticationTokenTests {
@Test
public void testNoArgConstructorDoesntExist() {
Class<?> clazz = AnonymousAuthenticationToken.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> AnonymousAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
}
@Test

View File

@ -50,6 +50,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@ -77,12 +78,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -92,12 +88,8 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try {
provider.authenticate(authenticationToken);
fail("Expected BadCredenialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> provider.authenticate(authenticationToken));
}
@Test
@ -106,12 +98,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown AccountExpiredException");
}
catch (AccountExpiredException expected) {
}
assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -120,35 +107,20 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown LockedException");
}
catch (LockedException expected) {
}
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
public void testAuthenticateFailsIfCredentialsExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown CredentialsExpiredException");
}
catch (CredentialsExpiredException expected) {
}
assertThatExceptionOfType(CredentialsExpiredException.class)
.isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "opal")));
// Check that wrong password causes BadCredentialsException, rather than
// CredentialsExpiredException
token = new UsernamePasswordAuthenticationToken("peter", "wrong_password");
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "wrong_password")));
}
@Test
@ -157,12 +129,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeter());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown DisabledException");
}
catch (DisabledException expected) {
}
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -171,12 +138,8 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown InternalAuthenticationServiceException");
}
catch (InternalAuthenticationServiceException expected) {
}
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
.isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -185,12 +148,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -199,12 +157,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -215,12 +168,7 @@ public class DaoAuthenticationProviderTests {
// UsernameNotFoundExceptions
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -230,12 +178,7 @@ public class DaoAuthenticationProviderTests {
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -245,19 +188,9 @@ public class DaoAuthenticationProviderTests {
assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -266,12 +199,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -389,14 +317,8 @@ public class DaoAuthenticationProviderTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
try {
provider.authenticate(token);
fail("Should have thrown AuthenticationServiceException");
}
catch (AuthenticationServiceException expected) {
assertThat("UserDetailsService returned null, which is an interface contract violation")
.isEqualTo(expected.getMessage());
}
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token))
.withMessage("UserDetailsService returned null, which is an interface contract violation");
}
@Test
@ -436,12 +358,7 @@ public class DaoAuthenticationProviderTests {
@Test
public void testStartupFailsIfNoAuthenticationDao() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
}
@Test
@ -450,12 +367,7 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class);
provider.setUserCache(null);
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
}
@Test
@ -486,12 +398,7 @@ public class DaoAuthenticationProviderTests {
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.afterPropertiesSet();
try {
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
// ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail
// if encoded password is null
verify(encoder).matches(isA(String.class), isA(String.class));
@ -507,12 +414,7 @@ public class DaoAuthenticationProviderTests {
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
userDetailsService.password = encoder.encode((CharSequence) token.getCredentials());
provider.setUserDetailsService(userDetailsService);
try {
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
}
@Test
@ -521,12 +423,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
try {
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
}
/**
@ -554,12 +451,8 @@ public class DaoAuthenticationProviderTests {
List<Long> userNotFoundTimes = new ArrayList<>(sampleSize);
for (int i = 0; i < sampleSize; i++) {
long start = System.currentTimeMillis();
try {
provider.authenticate(notFoundUser);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> provider.authenticate(notFoundUser));
userNotFoundTimes.add(System.currentTimeMillis() - start);
}
double userFoundAvg = avg(userFoundTimes);
@ -584,12 +477,7 @@ public class DaoAuthenticationProviderTests {
provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
try {
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
verify(encoder, times(0)).matches(anyString(), anyString());
}

View File

@ -24,7 +24,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link AbstractAuthenticationEvent} and its subclasses.
@ -59,22 +59,13 @@ public class AuthenticationEventTests {
@Test
public void testRejectsNullAuthentication() {
AuthenticationException exception = new DisabledException("TEST");
try {
new AuthenticationFailureDisabledEvent(null, exception);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationFailureDisabledEvent(null, exception));
}
@Test
public void testRejectsNullAuthenticationException() {
try {
new AuthenticationFailureDisabledEvent(getAuthentication(), null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthenticationFailureDisabledEvent(getAuthentication(), null));
}
}

View File

@ -44,7 +44,7 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
@ -112,23 +112,15 @@ public class DefaultJaasAuthenticationProviderTests {
@Test
public void authenticateBadPassword() {
try {
this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException success) {
}
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
verifyFailedLogin();
}
@Test
public void authenticateBadUser() {
try {
this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException success) {
}
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
verifyFailedLogin();
}

View File

@ -46,6 +46,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionDestroyedEvent;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -73,12 +75,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testBadPassword() {
try {
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
@ -87,12 +85,8 @@ public class JaasAuthenticationProviderTests {
@Test
public void testBadUser() {
try {
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password"));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull();
@ -115,13 +109,8 @@ public class JaasAuthenticationProviderTests {
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
try {
myJaasProvider.afterPropertiesSet();
fail("Should have thrown ApplicationContextException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().startsWith("loginConfig must be set on")).isTrue();
}
assertThatIllegalArgumentException().isThrownBy(() -> myJaasProvider.afterPropertiesSet())
.withMessageStartingWith("loginConfig must be set on");
}
// SEC-1239
@ -160,21 +149,11 @@ public class JaasAuthenticationProviderTests {
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig());
myJaasProvider.setLoginContextName(null);
try {
myJaasProvider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).startsWith("loginContextName must be set on");
}
assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
.withMessageStartingWith("loginContextName must be set on");
myJaasProvider.setLoginContextName("");
try {
myJaasProvider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().startsWith("loginContextName must be set on"));
}
assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
.withMessageStartingWith("loginContextName must be set on");
}
@Test

View File

@ -31,7 +31,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests SecurityContextLoginModule
@ -71,12 +71,7 @@ public class SecurityContextLoginModuleTests {
@Test
public void testLoginException() {
try {
this.module.login();
fail("LoginException expected, there is no Authentication in the SecurityContext");
}
catch (LoginException ex) {
}
assertThatExceptionOfType(LoginException.class).isThrownBy(this.module::login);
}
@Test
@ -101,13 +96,8 @@ public class SecurityContextLoginModuleTests {
@Test
public void testNullAuthenticationInSecurityContext() {
try {
SecurityContextHolder.getContext().setAuthentication(null);
this.module.login();
fail("LoginException expected, the authentication is null in the SecurityContext");
}
catch (Exception ex) {
}
SecurityContextHolder.getContext().setAuthentication(null);
assertThatExceptionOfType(Exception.class).isThrownBy(this.module::login);
}
@Test

View File

@ -23,7 +23,7 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -47,12 +47,7 @@ public class RemoteAuthenticationManagerImplTests {
@Test
public void testStartupChecksAuthenticationManagerSet() throws Exception {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
try {
manager.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet);
manager.setAuthenticationManager(mock(AuthenticationManager.class));
manager.afterPropertiesSet();
}

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link RemoteAuthenticationProvider}.
@ -39,12 +40,8 @@ public class RemoteAuthenticationProviderTests {
public void testExceptionsGetPassedBackToCaller() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
fail("Should have thrown RemoteAuthenticationException");
}
catch (RemoteAuthenticationException expected) {
}
assertThatExceptionOfType(RemoteAuthenticationException.class)
.isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")));
}
@Test
@ -57,12 +54,7 @@ public class RemoteAuthenticationProviderTests {
@Test
public void testStartupChecksAuthenticationManagerSet() throws Exception {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
provider.afterPropertiesSet();
}
@ -81,12 +73,8 @@ public class RemoteAuthenticationProviderTests {
public void testNullCredentialsDoesNotCauseNullPointerException() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try {
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null));
fail("Expected Exception");
}
catch (RemoteAuthenticationException success) {
}
assertThatExceptionOfType(RemoteAuthenticationException.class)
.isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null)));
}
@Test

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link RememberMeAuthenticationProvider}.
@ -40,22 +41,12 @@ public class RememberMeAuthenticationProviderTests {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try {
aap.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token));
}
@Test
public void testDetectsMissingKey() {
try {
new RememberMeAuthenticationProvider(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationProvider(null));
}
@Test

View File

@ -16,7 +16,7 @@
package org.springframework.security.authentication.rememberme;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
@ -27,7 +27,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link RememberMeAuthenticationToken}.
@ -40,26 +40,11 @@ public class RememberMeAuthenticationTokenTests {
@Test
public void testConstructorRejectsNulls() {
try {
new RememberMeAuthenticationToken(null, "Test", ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new RememberMeAuthenticationToken("key", null, ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
List<GrantedAuthority> authsContainingNull = new ArrayList<>();
authsContainingNull.add(null);
new RememberMeAuthenticationToken("key", "Test", authsContainingNull);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException()
.isThrownBy(() -> new RememberMeAuthenticationToken(null, "Test", ROLES_12));
assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationToken("key", null, ROLES_12));
assertThatIllegalArgumentException().isThrownBy(
() -> new RememberMeAuthenticationToken("key", "Test", Arrays.asList((GrantedAuthority) null)));
}
@Test

View File

@ -26,7 +26,8 @@ import org.junit.Test;
import org.springframework.security.core.GrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/**
* @author TSARDD
@ -39,26 +40,13 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true);
mapper.setConvertAttributeToUpperCase(true);
try {
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
}
@Test
public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try {
mapper.afterPropertiesSet();
}
catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
assertThatNoException().isThrownBy(mapper::afterPropertiesSet);
}
@Test

View File

@ -22,7 +22,7 @@ import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link SecurityContextHolder}.
@ -55,12 +55,7 @@ public class SecurityContextHolderTests {
@Test
public void testRejectsNulls() {
try {
SecurityContextHolder.setContext(null);
fail("Should have rejected null");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> SecurityContextHolder.setContext(null));
}
}

View File

@ -22,7 +22,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author TSARDD
@ -34,15 +34,7 @@ public class UserDetailsByNameServiceWrapperTests {
@Test
public final void testAfterPropertiesSet() {
UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper();
try {
svc.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
assertThatIllegalArgumentException().isThrownBy(svc::afterPropertiesSet);
}
@Test

View File

@ -30,7 +30,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link User}.
@ -63,50 +64,25 @@ public class UserTests {
@Test
public void testNoArgConstructorDoesntExist() {
Class<User> clazz = User.class;
try {
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
assertThatExceptionOfType(NoSuchMethodException.class)
.isThrownBy(() -> User.class.getDeclaredConstructor((Class[]) null));
}
@Test
public void testNullValuesRejected() {
try {
new User(null, "koala", true, true, true, true, ROLE_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new User("rod", null, true, true, true, true, ROLE_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null);
new User("rod", "koala", true, true, true, true, auths);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, ROLE_12));
assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", null, true, true, true, true, ROLE_12));
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null);
assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", "koala", true, true, true, true, auths));
}
@Test
public void testNullWithinGrantedAuthorityElementIsRejected() {
try {
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null);
auths.add(new SimpleGrantedAuthority("ROLE_THREE"));
new User(null, "koala", true, true, true, true, auths);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null);
auths.add(new SimpleGrantedAuthority("ROLE_THREE"));
assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, auths));
}
@Test

View File

@ -25,7 +25,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@ -92,23 +93,14 @@ public class JdbcDaoImplTests {
@Test
public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
try {
dao.loadUserByUsername("cooper");
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> dao.loadUserByUsername("cooper"));
}
@Test
public void testLookupFailsWithWrongUsername() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao();
try {
dao.loadUserByUsername("UNKNOWN_USER");
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> dao.loadUserByUsername("UNKNOWN_USER"));
}
@Test
@ -152,24 +144,16 @@ public class JdbcDaoImplTests {
@Test
public void testStartupFailsIfDataSourceNotSet() {
JdbcDaoImpl dao = new JdbcDaoImpl();
try {
dao.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(dao::afterPropertiesSet);
}
@Test
public void testStartupFailsIfUserMapSetToNull() {
JdbcDaoImpl dao = new JdbcDaoImpl();
try {
assertThatIllegalArgumentException().isThrownBy(() -> {
dao.setDataSource(null);
dao.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
});
}
@Test(expected = IllegalArgumentException.class)

View File

@ -44,7 +44,7 @@ import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -229,12 +229,8 @@ public class JdbcUserDetailsManagerTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.manager.setAuthenticationManager(am);
try {
this.manager.changePassword("password", "newPassword");
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.manager.changePassword("password", "newPassword"));
// Check password hasn't changed.
UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password");

View File

@ -19,6 +19,7 @@ package org.springframework.security.util;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Luke Taylor
@ -32,11 +33,7 @@ public class FieldUtilsTests {
assertThat(FieldUtils.getFieldValue(tc, "nested.protectedField")).isEqualTo("z");
FieldUtils.setProtectedFieldValue("protectedField", tc, "y");
assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("y");
try {
FieldUtils.getProtectedFieldValue("nonExistentField", tc);
}
catch (IllegalStateException expected) {
}
assertThatIllegalStateException().isThrownBy(() -> FieldUtils.getProtectedFieldValue("nonExistentField", tc));
}
@SuppressWarnings("unused")

View File

@ -38,7 +38,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -90,14 +90,10 @@ public class SpringSecurityLdapTemplateITests {
@Test
public void namingExceptionIsTranslatedCorrectly() {
try {
this.template.executeReadOnly((ContextExecutor) (dirContext) -> {
throw new NamingException();
});
fail("Expected UncategorizedLdapException on NamingException");
}
catch (UncategorizedLdapException expected) {
}
assertThatExceptionOfType(UncategorizedLdapException.class)
.isThrownBy(() -> this.template.executeReadOnly((ContextExecutor) (dirContext) -> {
throw new NamingException();
}));
}
@Test

View File

@ -33,7 +33,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link BindAuthenticator}.
@ -77,13 +77,8 @@ public class BindAuthenticatorTests {
@Test
public void testAuthenticationWithInvalidUserNameFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"));
fail("Shouldn't be able to bind with invalid username");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password")));
}
@Test
@ -131,13 +126,8 @@ public class BindAuthenticatorTests {
@Test
public void testAuthenticationWithWrongPasswordFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
try {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"));
fail("Shouldn't be able to bind with wrong password");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword")));
}
@Test

View File

@ -36,7 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link PasswordComparisonAuthenticator}.
@ -80,13 +80,8 @@ public class PasswordComparisonAuthenticatorTests {
.isEmpty();
this.authenticator.setUserSearch(new MockUserSearch(null));
this.authenticator.afterPropertiesSet();
try {
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
fail("Expected exception on failed user search");
}
catch (UsernameNotFoundException expected) {
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(
() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")));
}
@Test(expected = BadCredentialsException.class)

View File

@ -33,6 +33,7 @@ import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
/**
@ -112,14 +113,8 @@ public class ApacheDSContainerTests {
List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0));
server.setLdapOverSslEnabled(true);
try {
server.afterPropertiesSet();
fail("Expected an IllegalArgumentException to be thrown.");
}
catch (IllegalArgumentException ex) {
assertThat(ex).hasMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
}
assertThatIllegalArgumentException().isThrownBy(server::afterPropertiesSet)
.withMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
}
@Test

View File

@ -29,7 +29,7 @@ import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link UnboundIdContainer}, specifically relating to LDIF file detection.
@ -72,26 +72,18 @@ public class UnboundIdContainerLdifTests {
@Test
public void unboundIdContainerWhenMalformedLdifThenException() {
try {
this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
}
catch (Exception ex) {
assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:test-server-malformed.txt");
}
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class))
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("Unable to load LDIF classpath:test-server-malformed.txt");
}
@Test
public void unboundIdContainerWhenMissingLdifThenException() {
try {
this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class);
failBecauseExceptionWasNotThrown(IllegalStateException.class);
}
catch (Exception ex) {
assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:does-not-exist.ldif");
}
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class))
.withCauseInstanceOf(IllegalStateException.class)
.withMessageContaining("Unable to load LDIF classpath:does-not-exist.ldif");
}
@Test

View File

@ -39,7 +39,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -174,14 +174,7 @@ public class LdapUserDetailsManagerTests {
assertThat(don.getAuthorities()).hasSize(2);
this.mgr.deleteUser("don");
try {
this.mgr.loadUserByUsername("don");
fail("Expected UsernameNotFoundException after deleting user");
}
catch (UsernameNotFoundException expected) {
// expected
}
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.mgr.loadUserByUsername("don"));
// Check that no authorities are left
assertThat(this.mgr.getUserAuthorities(this.mgr.usernameMapper.buildDn("don"), "don")).hasSize(0);

View File

@ -36,7 +36,7 @@ import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -67,18 +67,10 @@ public class LdapAuthenticationProviderTests {
public void testEmptyOrNullUserNameThrowsException() {
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(),
new MockAuthoritiesPopulator());
try {
ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password"));
fail("Expected BadCredentialsException for empty username");
}
catch (BadCredentialsException expected) {
}
try {
ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword"));
fail("Expected BadCredentialsException for null username");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password")));
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword")));
}
@Test(expected = BadCredentialsException.class)
@ -156,13 +148,8 @@ public class LdapAuthenticationProviderTests {
CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException());
given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause);
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator);
try {
ldapProvider.authenticate(authRequest);
fail("Expected Exception");
}
catch (InternalAuthenticationServiceException success) {
assertThat(success.getCause()).isSameAs(expectedCause);
}
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
.isThrownBy(() -> ldapProvider.authenticate(authRequest)).havingCause().isSameAs(expectedCause);
}
class MockAuthenticator implements LdapAuthenticator {

View File

@ -54,7 +54,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -169,12 +169,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx);
try {
this.provider.authenticate(this.joe);
fail("Expected BadCredentialsException for user with no domain information");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
}
@ -278,12 +273,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = CredentialsExpiredException.class)
public void expiredPasswordIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));
try {
this.provider.authenticate(this.joe);
fail("BadCredentialsException should had been thrown");
}
catch (BadCredentialsException expected) {
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe);
}
@ -323,18 +313,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
this.provider.authenticate(this.joe);
}
@Test(expected = org.springframework.ldap.CommunicationException.class)
@Test
public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Throwable {
try {
assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> {
this.provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg));
this.provider.authenticate(this.joe);
}
catch (InternalAuthenticationServiceException ex) {
// Since GH-8418 ldap communication exception is wrapped into
// InternalAuthenticationServiceException.
// This test is about the wrapped exception, so we throw it.
throw ex.getCause();
}
}).withCauseInstanceOf(org.springframework.ldap.CommunicationException.class);
}
@Test(expected = org.springframework.security.authentication.InternalAuthenticationServiceException.class)
@ -368,16 +352,10 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
Hashtable<String, Object> env = new Hashtable<>();
env.put("java.naming.ldap.factory.socket", "unknown.package.NonExistingSocketFactory");
this.provider.setContextEnvironmentProperties(env);
try {
this.provider.authenticate(this.joe);
fail("CommunicationException was expected with a root cause of ClassNotFoundException");
}
catch (InternalAuthenticationServiceException expected) {
assertThat(expected.getCause()).isInstanceOf(org.springframework.ldap.CommunicationException.class);
org.springframework.ldap.CommunicationException cause = (org.springframework.ldap.CommunicationException) expected
.getCause();
assertThat(cause.getRootCause()).isInstanceOf(ClassNotFoundException.class);
}
assertThatExceptionOfType(InternalAuthenticationServiceException.class)
.isThrownBy(() -> this.provider.authenticate(this.joe))
.withCauseInstanceOf(org.springframework.ldap.CommunicationException.class)
.withRootCauseInstanceOf(ClassNotFoundException.class);
}
ContextFactory createContextFactoryThrowing(final NamingException ex) {

View File

@ -38,7 +38,7 @@ import org.openid4java.message.ax.FetchResponse;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -90,18 +90,10 @@ public class OpenID4JavaConsumerTests {
OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory());
given(mgr.authenticate(ArgumentMatchers.<DiscoveryInformation>any(), any(), any()))
.willThrow(new MessageException("msg"), new ConsumerException("msg"));
try {
consumer.beginConsumption(new MockHttpServletRequest(), "", "", "");
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.beginConsumption(new MockHttpServletRequest(), "", "", "");
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
assertThatExceptionOfType(OpenIDConsumerException.class)
.isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""));
assertThatExceptionOfType(OpenIDConsumerException.class)
.isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""));
}
@Test
@ -125,24 +117,9 @@ public class OpenID4JavaConsumerTests {
.willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException(""));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("x=5");
try {
consumer.endConsumption(request);
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
}
@SuppressWarnings("serial")

View File

@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.UserDetailsByNameServiceWra
import org.springframework.security.core.userdetails.UserDetailsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link OpenIDAuthenticationProvider}
@ -60,13 +61,8 @@ public class OpenIDAuthenticationProviderTests {
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.CANCELLED, USERNAME, "",
null);
assertThat(preAuth.isAuthenticated()).isFalse();
try {
provider.authenticate(preAuth);
fail("Should throw an AuthenticationException");
}
catch (AuthenticationCancelledException expected) {
assertThat(expected.getMessage()).isEqualTo("Log in cancelled");
}
assertThatExceptionOfType(AuthenticationCancelledException.class)
.isThrownBy(() -> provider.authenticate(preAuth)).withMessage("Log in cancelled");
}
/*
@ -80,13 +76,8 @@ public class OpenIDAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsService());
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.ERROR, USERNAME, "", null);
assertThat(preAuth.isAuthenticated()).isFalse();
try {
provider.authenticate(preAuth);
fail("Should throw an AuthenticationException");
}
catch (AuthenticationServiceException expected) {
assertThat(expected.getMessage()).isEqualTo("Error message from server: ");
}
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth))
.withMessage("Error message from server: ");
}
/*
@ -101,13 +92,8 @@ public class OpenIDAuthenticationProviderTests {
new UserDetailsByNameServiceWrapper<>(new MockUserDetailsService()));
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null);
assertThat(preAuth.isAuthenticated()).isFalse();
try {
provider.authenticate(preAuth);
fail("Should throw an AuthenticationException");
}
catch (BadCredentialsException expected) {
assertThat("Log in failed - identity could not be verified").isEqualTo(expected.getMessage());
}
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(preAuth))
.withMessage("Log in failed - identity could not be verified");
}
/*
@ -122,14 +108,8 @@ public class OpenIDAuthenticationProviderTests {
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SETUP_NEEDED, USERNAME, "",
null);
assertThat(preAuth.isAuthenticated()).isFalse();
try {
provider.authenticate(preAuth);
fail("Should throw an AuthenticationException");
}
catch (AuthenticationServiceException expected) {
assertThat("The server responded setup was needed, which shouldn't happen")
.isEqualTo(expected.getMessage());
}
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth))
.withMessage("The server responded setup was needed, which shouldn't happen");
}
/*
@ -158,13 +138,7 @@ public class OpenIDAuthenticationProviderTests {
@Test
public void testDetectsMissingAuthoritiesPopulator() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("Should have thrown Exception");
}
catch (IllegalArgumentException expected) {
// ignored
}
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
}
/*
@ -207,13 +181,7 @@ public class OpenIDAuthenticationProviderTests {
@Test
public void testValidation() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("IllegalArgumentException expected, ssoAuthoritiesPopulator is null");
}
catch (IllegalArgumentException ex) {
// expected
}
assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService());
provider.afterPropertiesSet();

View File

@ -30,7 +30,7 @@ import org.springframework.security.util.SimpleMethodInvocation;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link ContextPropagatingRemoteInvocation} and
@ -59,15 +59,10 @@ public class ContextPropagatingRemoteInvocationTests {
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
try {
// Set up the wrong arguments.
remoteInvocation.setArguments(new Object[] {});
remoteInvocation.invoke(TargetObject.class.newInstance());
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
// Set up the wrong arguments.
remoteInvocation.setArguments(new Object[] {});
assertThatIllegalArgumentException()
.isThrownBy(() -> remoteInvocation.invoke(TargetObject.class.newInstance()));
assertThat(SecurityContextHolder.getContext().getAuthentication())
.withFailMessage("Authentication must be null").isNull();
}

View File

@ -29,8 +29,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -85,14 +84,9 @@ public class Saml2WebSsoAuthenticationFilterTests {
this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}");
this.request.setPathInfo("/some/other/path/non-existent-id");
this.request.setParameter("SAMLResponse", "response");
try {
this.filter.attemptAuthentication(this.request, this.response);
failBecauseExceptionWasNotThrown(Saml2AuthenticationException.class);
}
catch (Exception ex) {
assertThat(ex).isInstanceOf(Saml2AuthenticationException.class);
assertThat(ex.getMessage()).isEqualTo("No relying party registration found");
}
assertThatExceptionOfType(Saml2AuthenticationException.class)
.isThrownBy(() -> this.filter.attemptAuthentication(this.request, this.response))
.withMessage("No relying party registration found");
}
}

View File

@ -29,7 +29,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests {@link AuthenticationTag}.
@ -106,13 +106,10 @@ public class AuthenticationTagTests {
public void testThrowsExceptionForUnrecognisedProperty() {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authenticationTag.setProperty("qsq");
try {
assertThatExceptionOfType(JspException.class).isThrownBy(() -> {
this.authenticationTag.doStartTag();
this.authenticationTag.doEndTag();
fail("Should have throwns JspException");
}
catch (JspException expected) {
}
});
}
@Test

View File

@ -43,7 +43,7 @@ import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -206,12 +206,8 @@ public class FilterChainProxyTests {
throw new ServletException("oops");
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
try {
this.fcp.doFilter(this.request, this.response, this.chain);
fail("Expected Exception");
}
catch (ServletException success) {
}
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

View File

@ -22,7 +22,7 @@ import java.util.Map;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link PortMapperImpl}.
@ -43,23 +43,13 @@ public class PortMapperImplTests {
@Test
public void testDetectsEmptyMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(new HashMap<>());
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(new HashMap<>()));
}
@Test
public void testDetectsNullMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(null));
}
@Test
@ -73,12 +63,7 @@ public class PortMapperImplTests {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("79", "80559");
try {
portMapper.setPortMappings(map);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(map));
}
@Test

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link PortResolverImpl}.
@ -51,12 +51,7 @@ public class PortResolverImplTests {
@Test
public void testDetectsEmptyPortMapper() {
PortResolverImpl pr = new PortResolverImpl();
try {
pr.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> pr.setPortMapper(null));
}
@Test

View File

@ -48,7 +48,6 @@ import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
@ -258,16 +257,12 @@ public class ExceptionTranslationFilterTests {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
for (Exception e : exceptions) {
for (Exception exception : exceptions) {
FilterChain fc = mock(FilterChain.class);
willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try {
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
fail("Should have thrown Exception");
}
catch (Exception expected) {
assertThat(expected).isSameAs(e);
}
willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc))
.isSameAs(exception);
}
}

View File

@ -33,6 +33,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
@ -47,14 +48,10 @@ public class ChannelDecisionManagerImplTests {
@Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(new Vector());
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}).withMessage("A list of ChannelProcessors is required");
}
@Test
@ -62,25 +59,16 @@ public class ChannelDecisionManagerImplTests {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
List list = new Vector();
list.add("THIS IS NOT A CHANNELPROCESSOR");
try {
cdm.setChannelProcessors(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list));
}
@Test
public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(null);
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}).withMessage("A list of ChannelProcessors is required");
}
@Test
@ -164,13 +152,8 @@ public class ChannelDecisionManagerImplTests {
@Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet)
.withMessage("A list of ChannelProcessors is required");
}
private class MockChannelProcessor implements ChannelProcessor {

View File

@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -74,12 +74,7 @@ public class InsecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
}
@Test
@ -97,34 +92,19 @@ public class InsecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
}
@Test
public void testMissingSecureChannelKeyword() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setInsecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
processor.setInsecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
}
@Test

View File

@ -30,7 +30,7 @@ import org.springframework.security.web.PortResolver;
import org.springframework.security.web.RedirectStrategy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -43,23 +43,13 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
}
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
}
@Test

View File

@ -27,7 +27,7 @@ import org.springframework.security.MockPortResolver;
import org.springframework.security.web.PortMapperImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link RetryWithHttpsEntryPoint}.
@ -39,23 +39,13 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
}
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
}
@Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -74,12 +74,7 @@ public class SecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
}
@Test
@ -97,34 +92,19 @@ public class SecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
}
@Test
public void testMissingSecureChannelKeyword() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setSecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("secureKeyword required");
processor.setSecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet())
.withMessage("secureKeyword required");
}
@Test

View File

@ -42,7 +42,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq;
@ -135,12 +135,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
verifyZeroInteractions(aim);
}
@ -163,12 +158,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);

View File

@ -48,6 +48,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@ -251,13 +252,8 @@ public class AbstractAuthenticationProcessingFilterTests {
this.successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login");
try {
filter.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified");
}
assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet)
.withMessage("authenticationManager must be specified");
}
@Test
@ -266,13 +262,8 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
try {
filter.setFilterProcessesUrl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty");
}
assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null))
.withMessage("Pattern cannot be null or empty");
}
@Test

View File

@ -43,6 +43,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -205,7 +206,7 @@ public class AuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@Test(expected = ServletException.class)
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
@ -216,14 +217,9 @@ public class AuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
try {
filter.doFilter(request, response, chain);
}
catch (ServletException ex) {
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
throw ex;
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test

View File

@ -25,7 +25,7 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -38,12 +38,7 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
handler.setDefaultTargetUrl("/acceptableRelativeUrl");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
try {
handler.setDefaultTargetUrl("missingSlash");
fail("Shouldn't accept default target without leading slash");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> handler.setDefaultTargetUrl("missingSlash"));
}
@Test

View File

@ -23,7 +23,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -104,18 +104,8 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void setTargetUrlParameterEmptyTargetUrlParameter() {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
try {
ash.setTargetUrlParameter("");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
try {
ash.setTargetUrlParameter(" ");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(""));
assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(" "));
}
}

View File

@ -27,7 +27,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -114,12 +114,8 @@ public class UsernamePasswordAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
try {
filter.attemptAuthentication(request, new MockHttpServletResponse());
fail("Expected AuthenticationException");
}
catch (AuthenticationException ex) {
}
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse()));
}
/**

View File

@ -29,7 +29,7 @@ import org.mockito.InOrder;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.inOrder;
@ -88,12 +88,8 @@ public class CompositeLogoutHandlerTests {
any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
try {
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class),
mock(HttpServletResponse.class), mock(Authentication.class)));
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));

View File

@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
@ -59,14 +59,8 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test
public void testThatSettNullHttpStatusThrowsException() {
try {
new HttpStatusReturningLogoutSuccessHandler(null);
}
catch (IllegalArgumentException ex) {
assertThat(ex).hasMessage("The provided HttpStatus must not be null.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null))
.withMessage("The provided HttpStatus must not be null.");
}
}

View File

@ -42,7 +42,7 @@ import org.springframework.security.web.authentication.ForwardAuthenticationSucc
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -105,15 +105,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void testAfterPropertiesSet() {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
try {
filter.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet);
}
// SEC-2045

View File

@ -26,22 +26,15 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class Http403ForbiddenEntryPointTests {
public void testCommence() {
public void testCommence() throws IOException {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse resp = new MockHttpServletResponse();
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
try {
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status")
.isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
catch (IOException ex) {
fail("Unexpected exception thrown: " + ex);
}
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
}

View File

@ -35,7 +35,7 @@ import org.springframework.security.core.authority.mapping.SimpleMappableAttribu
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author TSARDD
@ -45,15 +45,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
@Test
public final void testAfterPropertiesSetException() {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
try {
t.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
assertThatIllegalArgumentException().isThrownBy(t::afterPropertiesSet);
}
@Test
@ -139,12 +131,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
try {
result.afterPropertiesSet();
}
catch (Exception expected) {
fail("AfterPropertiesSet throws unexpected exception");
}
result.afterPropertiesSet();
return result;
}

View File

@ -29,7 +29,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ -86,12 +86,8 @@ public class CompositeSessionAuthenticationStrategyTests {
.onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));
try {
strategy.onAuthentication(this.authentication, this.request, this.response);
fail("Expected Exception");
}
catch (SessionAuthenticationException success) {
}
assertThatExceptionOfType(SessionAuthenticationException.class)
.isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response));
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response);
}

View File

@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.DisabledException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link BasicAuthenticationEntryPoint}.
@ -36,13 +36,8 @@ public class BasicAuthenticationEntryPointTests {
@Test
public void testDetectsMissingRealmName() {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
}
@Test

View File

@ -23,7 +23,7 @@ import org.junit.Test;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link org.springframework.security.util.StringSplitUtils}.
@ -90,36 +90,12 @@ public class DigestAuthUtilsTests {
@Test
public void testSplitRejectsNullsAndIncorrectLengthStrings() {
try {
DigestAuthUtils.split(null, "="); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("", "="); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("sdch=dfgf", null); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split(null, "="));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("", "="));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", ""));
assertThatIllegalArgumentException()
.isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"));
}
@Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.authentication.DisabledException;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests {@link DigestAuthenticationEntryPoint}.
@ -53,13 +53,7 @@ public class DigestAuthenticationEntryPointTests {
public void testDetectsMissingKey() throws Exception {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("realm");
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("key must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet).withMessage("key must be specified");
}
@Test
@ -67,13 +61,8 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setKey("dcdc");
ep.setNonceValiditySeconds(12);
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
}
@Test

View File

@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
@ -69,12 +69,7 @@ public class SecurityContextPersistenceFilterTests {
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try {
filter.doFilter(request, response, chain);
fail("IOException should have been thrown");
}
catch (IOException expected) {
}
assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

View File

@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Luke Taylor
@ -33,23 +33,14 @@ public class DefaultHttpFirewallTests {
@Test
public void unnormalizedPathsAreRejected() {
DefaultHttpFirewall fw = new DefaultHttpFirewall();
MockHttpServletRequest request;
for (String path : this.unnormalizedPaths) {
request = new MockHttpServletRequest();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path);
try {
fw.getFirewalledRequest(request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
request.setPathInfo(path);
try {
fw.getFirewalledRequest(request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
}
}

View File

@ -19,10 +19,9 @@ package org.springframework.security.web.firewall;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
public class DefaultRequestRejectedHandlerTests {
@ -31,14 +30,9 @@ public class DefaultRequestRejectedHandlerTests {
public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception {
RequestRejectedException requestRejectedException = new RequestRejectedException("rejected");
DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler();
try {
sut.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException);
}
catch (RequestRejectedException exception) {
Assert.assertThat(exception.getMessage(), CoreMatchers.is("rejected"));
return;
}
Assert.fail("Exception was not rethrown");
assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut
.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException))
.withMessage("rejected");
}
}

View File

@ -24,7 +24,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -166,12 +166,7 @@ public class FirewalledResponseTests {
}
private void validateLineEnding(String name, String value) {
try {
this.fwResponse.validateCrlf(name, value);
fail("IllegalArgumentException should have thrown");
}
catch (IllegalArgumentException expected) {
}
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.validateCrlf(name, value));
}
}

View File

@ -27,7 +27,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
/**
* @author Rob Winch
@ -94,12 +93,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setRequestURI(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@ -108,12 +103,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setContextPath(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@ -122,12 +113,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setServletPath(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@ -136,12 +123,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", "");
this.request.setPathInfo(path);
try {
this.firewall.getFirewalledRequest(this.request);
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}

View File

@ -51,7 +51,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@ -179,15 +179,11 @@ public class SecurityContextHolderAwareRequestFilterTests {
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(expectedAuth);
try {
wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()));
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
}
assertThatExceptionOfType(ServletException.class).isThrownBy(
() -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
}
@Test
@ -195,13 +191,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
AuthenticationException authException = new BadCredentialsException("Invalid");
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willThrow(authException);
try {
wrappedRequest().login("invalid", "credentials");
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success.getCause()).isEqualTo(authException);
}
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> wrappedRequest().login("invalid", "credentials")).withCause(authException);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString());
@ -226,13 +217,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
String password = "password";
ServletException authException = new ServletException("Failed Login");
willThrow(authException).given(this.request).login(username, password);
try {
wrappedRequest().login(username, password);
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success).isEqualTo(authException);
}
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password))
.isEqualTo(authException);
verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler);
}

View File

@ -22,7 +22,7 @@ import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Test cases for {@link ThrowableAnalyzer}.
@ -78,22 +78,15 @@ public class ThrowableAnalyzerTests {
@Test
public void testRegisterExtractorWithInvalidExtractor() {
try {
new ThrowableAnalyzer() {
/**
* @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
@Override
protected void initExtractorMap() {
// null is no valid extractor
super.registerExtractor(Exception.class, null);
}
};
fail("IllegalArgumentExpected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() {
@Override
protected void initExtractorMap() {
// null is no valid extractor
super.registerExtractor(Exception.class, null);
}
});
}
@Test
@ -199,25 +192,15 @@ public class ThrowableAnalyzerTests {
@Test
public void testVerifyThrowableHierarchyWithNull() {
try {
ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException()
.isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class));
}
@Test
public void testVerifyThrowableHierarchyWithNonmatchingType() {
Throwable throwable = new IllegalStateException("Test");
try {
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class);
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
assertThatIllegalArgumentException().isThrownBy(
() -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class));
}
/**