diff --git a/acl/src/main/java/org/springframework/security/acls/Acl.java b/acl/src/main/java/org/springframework/security/acls/Acl.java index b8dafaa7e5..476f57aeaa 100644 --- a/acl/src/main/java/org/springframework/security/acls/Acl.java +++ b/acl/src/main/java/org/springframework/security/acls/Acl.java @@ -44,7 +44,7 @@ import java.io.Serializable; */ public interface Acl extends Serializable { - /** + /** * Returns all of the entries represented by the present Acl. Entries associated with * the Acl parents are not returned. * diff --git a/acl/src/main/java/org/springframework/security/acls/AclService.java b/acl/src/main/java/org/springframework/security/acls/AclService.java index f159e45714..f9450b14f2 100644 --- a/acl/src/main/java/org/springframework/security/acls/AclService.java +++ b/acl/src/main/java/org/springframework/security/acls/AclService.java @@ -39,9 +39,10 @@ public interface AclService { ObjectIdentity[] findChildren(ObjectIdentity parentIdentity); /** - * Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.

This method - * should not be called as it does not leverage the underlaying implementation's potential ability to filter - * Acl entries based on a {@link Sid} parameter.

+ * Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl. + *

+ * This method should not be called as it does not leverage the underlying implementation's potential ability to + * filter Acl entries based on a {@link Sid} parameter.

* * @param object to locate an {@link Acl} for * @@ -55,7 +56,7 @@ public interface AclService { * Same as {@link #readAclsById(ObjectIdentity[], Sid[])} except it returns only a single Acl. * * @param object to locate an {@link Acl} for - * @param sids the security identities for which {@link Acl} information is required + * @param sids the security identities for which {@link Acl} information is required * (may be null to denote all entries) * * @return the {@link Acl} for the requested {@link ObjectIdentity} (never null) @@ -89,7 +90,7 @@ public interface AclService { * not have a map key.

* * @param objects the objects to find {@link Acl} information for - * @param sids the security identities for which {@link Acl} information is required + * @param sids the security identities for which {@link Acl} information is required * (may be null to denote all entries) * * @return a map with exactly one element for each {@link ObjectIdentity} passed as an argument (never null) diff --git a/acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java b/acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java index 8cd7c7f371..480f52489d 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java @@ -53,7 +53,7 @@ public abstract class AbstractPermission implements Permission { return this.getClass().getSimpleName() + "[" + getPattern() + "=" + mask + "]"; } - public final int hashCode() { - return this.mask; - } + public final int hashCode() { + return this.mask; + } } diff --git a/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java b/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java index 23ec5a8fe3..c24a752f68 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java @@ -68,45 +68,45 @@ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAcce AccessControlEntryImpl rhs = (AccessControlEntryImpl) arg0; if (this.acl == null) { - if (rhs.getAcl() != null) { - return false; - } - // Both this.acl and rhs.acl are null and thus equal + if (rhs.getAcl() != null) { + return false; + } + // Both this.acl and rhs.acl are null and thus equal } else { - // this.acl is non-null - if (rhs.getAcl() == null) { - return false; - } - - // Both this.acl and rhs.acl are non-null, so do a comparison - if (this.acl.getObjectIdentity() == null) { - if (rhs.acl.getObjectIdentity() != null) { - return false; - } - // Both this.acl and rhs.acl are null and thus equal - } else { - // Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null - if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) { - return false; - } - } + // this.acl is non-null + if (rhs.getAcl() == null) { + return false; + } + + // Both this.acl and rhs.acl are non-null, so do a comparison + if (this.acl.getObjectIdentity() == null) { + if (rhs.acl.getObjectIdentity() != null) { + return false; + } + // Both this.acl and rhs.acl are null and thus equal + } else { + // Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null + if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) { + return false; + } + } } if (this.id == null) { - if (rhs.id != null) { - return false; - } - // Both this.id and rhs.id are null and thus equal + if (rhs.id != null) { + return false; + } + // Both this.id and rhs.id are null and thus equal } else { - // this.id is non-null - if (rhs.id == null) { - return false; - } + // this.id is non-null + if (rhs.id == null) { + return false; + } - // Both this.id and rhs.id are non-null - if (!this.id.equals(rhs.id)) { - return false; - } + // Both this.id and rhs.id are non-null + if (!this.id.equals(rhs.id)) { + return false; + } } if ((this.auditFailure != rhs.isAuditFailure()) || (this.auditSuccess != rhs.isAuditSuccess()) diff --git a/acl/src/main/java/org/springframework/security/acls/domain/CumulativePermission.java b/acl/src/main/java/org/springframework/security/acls/domain/CumulativePermission.java index 5dca663072..0762808be8 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/CumulativePermission.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/CumulativePermission.java @@ -31,7 +31,7 @@ public class CumulativePermission extends AbstractPermission { private String pattern = THIRTY_TWO_RESERVED_OFF; public CumulativePermission() { - super(0, ' '); + super(0, ' '); } public CumulativePermission clear(Permission permission) { diff --git a/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionFactory.java b/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionFactory.java index 6baafbd73e..55f62c778f 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionFactory.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionFactory.java @@ -36,7 +36,7 @@ public class DefaultPermissionFactory implements PermissionFactory { Assert.notNull(clazz, "Class required"); Assert.isAssignable(Permission.class, clazz); - Field[] fields = clazz.getFields(); + Field[] fields = clazz.getFields(); for (int i = 0; i < fields.length; i++) { try { @@ -53,20 +53,20 @@ public class DefaultPermissionFactory implements PermissionFactory { } } - public void registerPermission(Permission perm, String permissionName) { - Assert.notNull(perm, "Permission required"); - Assert.hasText(permissionName, "Permission name required"); - - Integer mask = new Integer(perm.getMask()); + public void registerPermission(Permission perm, String permissionName) { + Assert.notNull(perm, "Permission required"); + Assert.hasText(permissionName, "Permission name required"); + + Integer mask = new Integer(perm.getMask()); - // Ensure no existing Permission uses this integer or code - Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask), "An existing Permission already provides mask " + mask); - Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), "An existing Permission already provides name '" + permissionName + "'"); - - // Register the new Permission - registeredPermissionsByInteger.put(mask, perm); - registeredPermissionsByName.put(permissionName, perm); - } + // Ensure no existing Permission uses this integer or code + Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask), "An existing Permission already provides mask " + mask); + Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), "An existing Permission already provides name '" + permissionName + "'"); + + // Register the new Permission + registeredPermissionsByInteger.put(mask, perm); + registeredPermissionsByName.put(permissionName, perm); + } public Permission buildFromMask(int mask) { if (registeredPermissionsByInteger.containsKey(new Integer(mask))) { diff --git a/acl/src/main/java/org/springframework/security/acls/domain/PermissionFactory.java b/acl/src/main/java/org/springframework/security/acls/domain/PermissionFactory.java index 86c303aa1c..08f68c33f3 100644 --- a/acl/src/main/java/org/springframework/security/acls/domain/PermissionFactory.java +++ b/acl/src/main/java/org/springframework/security/acls/domain/PermissionFactory.java @@ -11,14 +11,14 @@ import org.springframework.security.acls.Permission; */ public interface PermissionFactory { - /** - * Dynamically creates a CumulativePermission or BasePermission representing the - * active bits in the passed mask. - * - * @param mask to build - * - * @return a Permission representing the requested object - */ - public abstract Permission buildFromMask(int mask); + /** + * Dynamically creates a CumulativePermission or BasePermission representing the + * active bits in the passed mask. + * + * @param mask to build + * + * @return a Permission representing the requested object + */ + public abstract Permission buildFromMask(int mask); } \ No newline at end of file diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java index eaf121023c..99d8e0cdbc 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java @@ -290,7 +290,7 @@ public final class BasicLookupStrategy implements LookupStrategy { * already, and adding the returned elements to the cache etc.

*

* This subclass is required to return fully valid Acls, including properly-configured - * parent ACLs.

+ * parent ACLs. * */ private Map lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) { @@ -349,7 +349,7 @@ public final class BasicLookupStrategy implements LookupStrategy { * * @param acls the AclImpls (with StubAclParents) * @param findNow Long-based primary keys to retrieve - * @param sids DOCUMENT ME! + * @param sids */ private void lookupPrimaryKeys(final Map acls, final Set findNow, final Sid[] sids) { Assert.notNull(acls, "ACLs are required"); @@ -378,11 +378,14 @@ public final class BasicLookupStrategy implements LookupStrategy { } /** - * The main method.

WARNING: This implementation completely disregards the "sids" argument! Every item - * in the cache is expected to contain all SIDs. If you have serious performance needs (eg a very large number of + * The main method. + *

+ * WARNING: This implementation completely disregards the "sids" argument! Every item in the cache is expected to + * contain all SIDs. If you have serious performance needs (e.g. a very large number of * SIDs per object identity), you'll probably want to develop a custom {@link LookupStrategy} implementation - * instead.

- *

The implementation works in batch sizes specfied by {@link #batchSize}.

+ * instead. + *

+ * The implementation works in batch sizes specified by {@link #batchSize}. * * @param objects the identities to lookup (required) * @param sids the SIDs for which identities are required (ignored by this implementation) diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCache.java b/acl/src/main/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCache.java index aa2508b65a..11088160bd 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCache.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCache.java @@ -94,7 +94,7 @@ public class EhCacheBasedAclCache implements AclCache { return initializeTransientFields((MutableAcl)element.getValue()); } - public MutableAcl getFromCache(Serializable pk) { + public MutableAcl getFromCache(Serializable pk) { Assert.notNull(pk, "Primary key (identifier) required"); Element element = null; @@ -117,8 +117,8 @@ public class EhCacheBasedAclCache implements AclCache { if (this.aclAuthorizationStrategy == null) { if (acl instanceof AclImpl) { - this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl); - this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl); + this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl); + this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl); } } @@ -131,10 +131,10 @@ public class EhCacheBasedAclCache implements AclCache { } private MutableAcl initializeTransientFields(MutableAcl value) { - if (value instanceof AclImpl) { - FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy); - FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger); - } - return value; - } + if (value instanceof AclImpl) { + FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy); + FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger); + } + return value; + } } diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java index 25da4dcded..6c962cb2a9 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java @@ -89,7 +89,7 @@ public class JdbcAclService implements AclService { }); if (objects.size() == 0) { - return null; + return null; } return (ObjectIdentityImpl[]) objects.toArray(new ObjectIdentityImpl[objects.size()]); diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcMutableAclService.java b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcMutableAclService.java index aeafd06c49..af9d1fbc6d 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcMutableAclService.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcMutableAclService.java @@ -60,7 +60,7 @@ import javax.sql.DataSource; public class JdbcMutableAclService extends JdbcAclService implements MutableAclService { //~ Instance fields ================================================================================================ - private boolean foreignKeysInDatabase = true; + private boolean foreignKeysInDatabase = true; private AclCache aclCache; private String deleteEntryByObjectIdentityForeignKey = "delete from acl_entry where acl_object_identity=?"; private String deleteObjectIdentityByPrimaryKey = "delete from acl_object_identity where id=?"; @@ -237,22 +237,22 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS Assert.notNull(objectIdentity.getIdentifier(), "Object Identity doesn't provide an identifier"); if (deleteChildren) { - ObjectIdentity[] children = findChildren(objectIdentity); - if (children != null) { - for (int i = 0; i < children.length; i++) { + ObjectIdentity[] children = findChildren(objectIdentity); + if (children != null) { + for (int i = 0; i < children.length; i++) { deleteAcl(children[i], true); } - } + } } else { - if (!foreignKeysInDatabase) { - // We need to perform a manual verification for what a FK would normally do - // We generally don't do this, in the interests of deadlock management - ObjectIdentity[] children = findChildren(objectIdentity); - if (children != null) { + if (!foreignKeysInDatabase) { + // We need to perform a manual verification for what a FK would normally do + // We generally don't do this, in the interests of deadlock management + ObjectIdentity[] children = findChildren(objectIdentity); + if (children != null) { throw new ChildrenExistException("Cannot delete '" + objectIdentity + "' (has " + children.length + " children)"); - } - } + } + } } Long oidPrimaryKey = retrieveObjectIdentityPrimaryKey(objectIdentity); @@ -273,7 +273,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS * @param oidPrimaryKey the rows in acl_entry to delete */ protected void deleteEntries(Long oidPrimaryKey) { - jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey, + jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey, new Object[] {oidPrimaryKey}); } @@ -341,12 +341,12 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS } private void clearCacheIncludingChildren(ObjectIdentity objectIdentity) { - Assert.notNull(objectIdentity, "ObjectIdentity required"); + Assert.notNull(objectIdentity, "ObjectIdentity required"); ObjectIdentity[] children = findChildren(objectIdentity); if (children != null) { - for (int i = 0; i < children.length; i++) { - clearCacheIncludingChildren(children[i]); - } + for (int i = 0; i < children.length; i++) { + clearCacheIncludingChildren(children[i]); + } } aclCache.evictFromCache(objectIdentity); } @@ -381,20 +381,20 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS } } - public void setClassIdentityQuery(String identityQuery) { - Assert.hasText(identityQuery, "New identity query is required"); - this.classIdentityQuery = identityQuery; - } + public void setClassIdentityQuery(String identityQuery) { + Assert.hasText(identityQuery, "New identity query is required"); + this.classIdentityQuery = identityQuery; + } - public void setSidIdentityQuery(String identityQuery) { - Assert.hasText(identityQuery, "New identity query is required"); - this.sidIdentityQuery = identityQuery; - } - /** - * @param foreignKeysInDatabase if false this class will perform additional FK constrain checking, which may - * cause deadlocks (the default is true, so deadlocks are avoided but the database is expected to enforce FKs) - */ - public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) { - this.foreignKeysInDatabase = foreignKeysInDatabase; - } + public void setSidIdentityQuery(String identityQuery) { + Assert.hasText(identityQuery, "New identity query is required"); + this.sidIdentityQuery = identityQuery; + } + /** + * @param foreignKeysInDatabase if false this class will perform additional FK constrain checking, which may + * cause deadlocks (the default is true, so deadlocks are avoided but the database is expected to enforce FKs) + */ + public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) { + this.foreignKeysInDatabase = foreignKeysInDatabase; + } } diff --git a/acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentity.java b/acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentity.java index eedc824964..4f55721184 100644 --- a/acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentity.java +++ b/acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentity.java @@ -62,7 +62,7 @@ public interface ObjectIdentity extends Serializable { * * @return the Java type of the domain object (never null) */ - Class getJavaType(); + Class getJavaType(); /** * @return a hash code representation of the ObjectIdentity diff --git a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java index 6ddb8340bc..209109d162 100644 --- a/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java +++ b/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java @@ -10,115 +10,115 @@ import junit.framework.TestCase; */ public class AclFormattingUtilsTests extends TestCase { - //~ Methods ======================================================================================================== - - public final void testDemergePatternsParametersConstraints() throws Exception { - try { - AclFormattingUtils.demergePatterns(null, "SOME STRING"); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + //~ Methods ======================================================================================================== + + public final void testDemergePatternsParametersConstraints() throws Exception { + try { + AclFormattingUtils.demergePatterns(null, "SOME STRING"); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.demergePatterns("SOME STRING", null); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + try { + AclFormattingUtils.demergePatterns("SOME STRING", null); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + try { + AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"); - Assert.assertTrue(true); - } - catch (IllegalArgumentException notExpected) { - Assert.fail("It shouldn't have thrown IllegalArgumentException"); - } - } + try { + AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"); + Assert.assertTrue(true); + } + catch (IllegalArgumentException notExpected) { + Assert.fail("It shouldn't have thrown IllegalArgumentException"); + } + } - public final void testDemergePatterns() throws Exception { - String original = "...........................A...R"; - String removeBits = "...............................R"; - Assert.assertEquals("...........................A....", AclFormattingUtils - .demergePatterns(original, removeBits)); + public final void testDemergePatterns() throws Exception { + String original = "...........................A...R"; + String removeBits = "...............................R"; + Assert.assertEquals("...........................A....", AclFormattingUtils + .demergePatterns(original, removeBits)); - Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......")); - Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")); - } - - public final void testMergePatternsParametersConstraints() throws Exception { - try { - AclFormattingUtils.mergePatterns(null, "SOME STRING"); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......")); + Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")); + } + + public final void testMergePatternsParametersConstraints() throws Exception { + try { + AclFormattingUtils.mergePatterns(null, "SOME STRING"); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.mergePatterns("SOME STRING", null); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + try { + AclFormattingUtils.mergePatterns("SOME STRING", null); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - Assert.assertTrue(true); - } + try { + AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException expected) { + Assert.assertTrue(true); + } - try { - AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"); - Assert.assertTrue(true); - } - catch (IllegalArgumentException notExpected) { - Assert.fail("It shouldn't have thrown IllegalArgumentException"); - } - } + try { + AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"); + Assert.assertTrue(true); + } + catch (IllegalArgumentException notExpected) { + Assert.fail("It shouldn't have thrown IllegalArgumentException"); + } + } - public final void testMergePatterns() throws Exception { - String original = "...............................R"; - String extraBits = "...........................A...."; - Assert.assertEquals("...........................A...R", AclFormattingUtils - .mergePatterns(original, extraBits)); + public final void testMergePatterns() throws Exception { + String original = "...............................R"; + String extraBits = "...........................A...."; + Assert.assertEquals("...........................A...R", AclFormattingUtils + .mergePatterns(original, extraBits)); - Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......")); - Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")); - } - - public final void testBinaryPrints() throws Exception { - Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15)); - - try { - AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException notExpected) { - Assert.assertTrue(true); - } - - try { - AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF); - Assert.fail("It should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException notExpected) { - Assert.assertTrue(true); - } - - Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x')); - } + Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......")); + Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")); + } + + public final void testBinaryPrints() throws Exception { + Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15)); + + try { + AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException notExpected) { + Assert.assertTrue(true); + } + + try { + AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF); + Assert.fail("It should have thrown IllegalArgumentException"); + } + catch (IllegalArgumentException notExpected) { + Assert.assertTrue(true); + } + + Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x')); + } } diff --git a/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java b/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java index 48af0edb45..fe53a76f03 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java @@ -34,8 +34,8 @@ public class PermissionTests { @Test public void basePermissionTest() { - Permission p = BasePermission.buildFromName("WRITE"); - assertNotNull(p); + Permission p = BasePermission.buildFromName("WRITE"); + assertNotNull(p); } @Test diff --git a/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java b/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java index ce5cb0c9d5..7a741a6edc 100644 --- a/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java +++ b/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java @@ -31,10 +31,10 @@ public class SpecialPermission extends BasePermission { * that the static methods will operate correctly. */ static { - registerPermissionsFor(SpecialPermission.class); + registerPermissionsFor(SpecialPermission.class); } protected SpecialPermission(int mask, char code) { - super(mask, code); + super(mask, code); } } diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/AclPermissionInheritanceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/AclPermissionInheritanceTests.java index 188afe66ca..dcb60d5c4e 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/AclPermissionInheritanceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/AclPermissionInheritanceTests.java @@ -12,7 +12,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.security.Authentication; -import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.acls.MutableAcl; import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; @@ -24,155 +23,156 @@ import org.springframework.security.acls.sid.GrantedAuthoritySid; import org.springframework.security.acls.sid.PrincipalSid; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; public class AclPermissionInheritanceTests extends TestCase { - private JdbcMutableAclService aclService; - private JdbcTemplate jdbcTemplate; - private DriverManagerDataSource dataSource; - private DataSourceTransactionManager txManager; - private TransactionStatus txStatus; + private JdbcMutableAclService aclService; + private JdbcTemplate jdbcTemplate; + private DriverManagerDataSource dataSource; + private DataSourceTransactionManager txManager; + private TransactionStatus txStatus; - protected void setUp() throws Exception { - - dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); - dataSource.setUrl("jdbc:hsqldb:mem:permissiontest"); - dataSource.setUsername("sa"); - dataSource.setPassword(""); + protected void setUp() throws Exception { - jdbcTemplate = new JdbcTemplate(dataSource); - - txManager = new DataSourceTransactionManager(); - txManager.setDataSource(dataSource); - - txStatus = txManager.getTransaction(new DefaultTransactionDefinition()); - - aclService = createAclService(dataSource); - - Authentication auth = new UsernamePasswordAuthenticationToken( - "system", "secret", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")}); + dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); + dataSource.setUrl("jdbc:hsqldb:mem:permissiontest"); + dataSource.setUsername("sa"); + dataSource.setPassword(""); + + jdbcTemplate = new JdbcTemplate(dataSource); + + txManager = new DataSourceTransactionManager(); + txManager.setDataSource(dataSource); + + txStatus = txManager.getTransaction(new DefaultTransactionDefinition()); + + aclService = createAclService(dataSource); + + Authentication auth = new UsernamePasswordAuthenticationToken("system", "secret", + AuthorityUtils.createAuthorityList("ROLE_IGNORED")); SecurityContextHolder.getContext().setAuthentication(auth); - } + } - protected void tearDown() throws Exception { - txManager.rollback(txStatus); - SecurityContextHolder.clearContext(); - } + protected void tearDown() throws Exception { + txManager.rollback(txStatus); + SecurityContextHolder.clearContext(); + } - public void test1() throws Exception { + public void test1() throws Exception { - createAclSchema(jdbcTemplate); + createAclSchema(jdbcTemplate); - ObjectIdentityImpl rootObject = - new ObjectIdentityImpl(TestDomainObject.class, new Long(1)); + ObjectIdentityImpl rootObject = + new ObjectIdentityImpl(TestDomainObject.class, new Long(1)); - MutableAcl parent = aclService.createAcl(rootObject); - MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); - child.setParent(parent); - aclService.updateAcl(child); + MutableAcl parent = aclService.createAcl(rootObject); + MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); + child.setParent(parent); + aclService.updateAcl(child); - parent = (AclImpl) aclService.readAclById(rootObject); - parent.insertAce(0, BasePermission.READ, - new PrincipalSid("john"), true); - aclService.updateAcl(parent); + parent = (AclImpl) aclService.readAclById(rootObject); + parent.insertAce(0, BasePermission.READ, + new PrincipalSid("john"), true); + aclService.updateAcl(parent); - parent = (AclImpl) aclService.readAclById(rootObject); - parent.insertAce(1, BasePermission.READ, - new PrincipalSid("joe"), true); - aclService.updateAcl(parent); + parent = (AclImpl) aclService.readAclById(rootObject); + parent.insertAce(1, BasePermission.READ, + new PrincipalSid("joe"), true); + aclService.updateAcl(parent); - child = (MutableAcl) aclService.readAclById( - new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); + child = (MutableAcl) aclService.readAclById( + new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); - parent = (MutableAcl) child.getParentAcl(); + parent = (MutableAcl) child.getParentAcl(); - assertEquals("Fails because child has a stale reference to its parent", - 2, parent.getEntries().length); - assertEquals(1, parent.getEntries()[0].getPermission().getMask()); - assertEquals(new PrincipalSid("john"), parent.getEntries()[0].getSid()); - assertEquals(1, parent.getEntries()[1].getPermission().getMask()); - assertEquals(new PrincipalSid("joe"), parent.getEntries()[1].getSid()); + assertEquals("Fails because child has a stale reference to its parent", + 2, parent.getEntries().length); + assertEquals(1, parent.getEntries()[0].getPermission().getMask()); + assertEquals(new PrincipalSid("john"), parent.getEntries()[0].getSid()); + assertEquals(1, parent.getEntries()[1].getPermission().getMask()); + assertEquals(new PrincipalSid("joe"), parent.getEntries()[1].getSid()); - } - public void test2() throws Exception { + } + public void test2() throws Exception { - createAclSchema(jdbcTemplate); + createAclSchema(jdbcTemplate); - ObjectIdentityImpl rootObject = - new ObjectIdentityImpl(TestDomainObject.class, new Long(1)); + ObjectIdentityImpl rootObject = + new ObjectIdentityImpl(TestDomainObject.class, new Long(1)); - MutableAcl parent = aclService.createAcl(rootObject); - MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); - child.setParent(parent); - aclService.updateAcl(child); + MutableAcl parent = aclService.createAcl(rootObject); + MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); + child.setParent(parent); + aclService.updateAcl(child); - parent.insertAce(0, BasePermission.ADMINISTRATION, - new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true); - aclService.updateAcl(parent); + parent.insertAce(0, BasePermission.ADMINISTRATION, + new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true); + aclService.updateAcl(parent); - parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true); - aclService.updateAcl(parent); + parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true); + aclService.updateAcl(parent); - child = (MutableAcl) aclService.readAclById( - new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); + child = (MutableAcl) aclService.readAclById( + new ObjectIdentityImpl(TestDomainObject.class, new Long(2))); - parent = (MutableAcl) child.getParentAcl(); + parent = (MutableAcl) child.getParentAcl(); - assertEquals(2, parent.getEntries().length); - assertEquals(16, parent.getEntries()[0].getPermission().getMask()); - assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()[0].getSid()); - assertEquals(8, parent.getEntries()[1].getPermission().getMask()); - assertEquals(new PrincipalSid("terry"), parent.getEntries()[1].getSid()); + assertEquals(2, parent.getEntries().length); + assertEquals(16, parent.getEntries()[0].getPermission().getMask()); + assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()[0].getSid()); + assertEquals(8, parent.getEntries()[1].getPermission().getMask()); + assertEquals(new PrincipalSid("terry"), parent.getEntries()[1].getSid()); - } + } - private JdbcMutableAclService createAclService(DriverManagerDataSource ds) - throws IOException { + private JdbcMutableAclService createAclService(DriverManagerDataSource ds) + throws IOException { - GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR"); - AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl( - new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority}); + GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR"); + AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl( + new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority}); - EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); - ehCacheManagerFactoryBean.afterPropertiesSet(); - CacheManager cacheManager = (CacheManager) ehCacheManagerFactoryBean.getObject(); - - EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); - ehCacheFactoryBean.setCacheName("aclAche"); - ehCacheFactoryBean.setCacheManager(cacheManager); - ehCacheFactoryBean.afterPropertiesSet(); - Ehcache ehCache = (Ehcache) ehCacheFactoryBean.getObject(); - - AclCache aclAche = new EhCacheBasedAclCache(ehCache); - - BasicLookupStrategy lookupStrategy = - new BasicLookupStrategy(ds, aclAche, authStrategy, new ConsoleAuditLogger()); - - return new JdbcMutableAclService(ds,lookupStrategy, aclAche); - } + EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); + ehCacheManagerFactoryBean.afterPropertiesSet(); + CacheManager cacheManager = (CacheManager) ehCacheManagerFactoryBean.getObject(); - private void createAclSchema(JdbcTemplate jdbcTemplate) { - - jdbcTemplate.execute("DROP TABLE ACL_ENTRY IF EXISTS;"); - jdbcTemplate.execute("DROP TABLE ACL_OBJECT_IDENTITY IF EXISTS;"); - jdbcTemplate.execute("DROP TABLE ACL_CLASS IF EXISTS"); - jdbcTemplate.execute("DROP TABLE ACL_SID IF EXISTS"); - - jdbcTemplate.execute( + EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); + ehCacheFactoryBean.setCacheName("aclAche"); + ehCacheFactoryBean.setCacheManager(cacheManager); + ehCacheFactoryBean.afterPropertiesSet(); + Ehcache ehCache = (Ehcache) ehCacheFactoryBean.getObject(); + + AclCache aclAche = new EhCacheBasedAclCache(ehCache); + + BasicLookupStrategy lookupStrategy = + new BasicLookupStrategy(ds, aclAche, authStrategy, new ConsoleAuditLogger()); + + return new JdbcMutableAclService(ds,lookupStrategy, aclAche); + } + + private void createAclSchema(JdbcTemplate jdbcTemplate) { + + jdbcTemplate.execute("DROP TABLE ACL_ENTRY IF EXISTS;"); + jdbcTemplate.execute("DROP TABLE ACL_OBJECT_IDENTITY IF EXISTS;"); + jdbcTemplate.execute("DROP TABLE ACL_CLASS IF EXISTS"); + jdbcTemplate.execute("DROP TABLE ACL_SID IF EXISTS"); + + jdbcTemplate.execute( "CREATE TABLE ACL_SID(" + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," + "PRINCIPAL BOOLEAN NOT NULL," + "SID VARCHAR_IGNORECASE(100) NOT NULL," + "CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));"); - jdbcTemplate.execute( + jdbcTemplate.execute( "CREATE TABLE ACL_CLASS(" + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," + "CLASS VARCHAR_IGNORECASE(100) NOT NULL," + "CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));"); - jdbcTemplate.execute( + jdbcTemplate.execute( "CREATE TABLE ACL_OBJECT_IDENTITY(" + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," + "OBJECT_ID_CLASS BIGINT NOT NULL," + @@ -184,7 +184,7 @@ public class AclPermissionInheritanceTests extends TestCase { "CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID)," + "CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID)," + "CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));"); - jdbcTemplate.execute( + jdbcTemplate.execute( "CREATE TABLE ACL_ENTRY(" + "ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," + "ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL," + @@ -192,18 +192,18 @@ public class AclPermissionInheritanceTests extends TestCase { "AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER)," + "CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID)," + "CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));"); - } + } - public static class TestDomainObject { - - private Long id; + public static class TestDomainObject { - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - } -} \ No newline at end of file + private Long id; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + } +} diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java index 2c1d5a84c7..8fde9dc0ea 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java @@ -35,12 +35,12 @@ import org.springframework.util.FileCopyUtils; /** * Tests {@link BasicLookupStrategy} - * + * * @author Andrei Stefan */ public class BasicLookupStrategyTests { //~ Instance fields ================================================================================================ - + private static JdbcTemplate jdbcTemplate; private LookupStrategy strategy; @@ -123,7 +123,7 @@ public class BasicLookupStrategyTests { // Deliberately use an integer for the child, to reproduce bug report in SEC-819 ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(102)); - Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); + Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); checkEntries(topParentOid, middleParentOid, childOid, map); } @@ -138,7 +138,7 @@ public class BasicLookupStrategyTests { // Let's empty the database to force acls retrieval from cache emptyDatabase(); - Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); + Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); checkEntries(topParentOid, middleParentOid, childOid, map); } @@ -151,12 +151,12 @@ public class BasicLookupStrategyTests { // Set a batch size to allow multiple database queries in order to retrieve all acls ((BasicLookupStrategy) this.strategy).setBatchSize(1); - Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); + Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null); checkEntries(topParentOid, middleParentOid, childOid, map); } - private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid, Map map) - throws Exception { + private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid, + Map map) throws Exception { Assert.assertEquals(3, map.size()); MutableAcl topParent = (MutableAcl) map.get(topParentOid); @@ -221,20 +221,20 @@ public class BasicLookupStrategyTests { Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries()[0]).isAuditSuccess()); Assert.assertFalse((child.getEntries()[0]).isGranting()); } - + @Test public void testAllParentsAreRetrievedWhenChildIsLoaded() throws Exception { String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,2,103,1,1,1);"; jdbcTemplate.execute(query); - + ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100)); ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(101)); ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102)); ObjectIdentity middleParent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(103)); - + // Retrieve the child - Map map = this.strategy.readAclsById(new ObjectIdentity[] { childOid }, null); - + Map map = this.strategy.readAclsById(new ObjectIdentity[] { childOid }, null); + // Check that the child and all its parents were retrieved Assert.assertNotNull(map.get(childOid)); Assert.assertEquals(childOid, ((Acl) map.get(childOid)).getObjectIdentity()); @@ -242,7 +242,7 @@ public class BasicLookupStrategyTests { Assert.assertEquals(middleParentOid, ((Acl) map.get(middleParentOid)).getObjectIdentity()); Assert.assertNotNull(map.get(topParentOid)); Assert.assertEquals(topParentOid, ((Acl) map.get(topParentOid)).getObjectIdentity()); - + // The second parent shouldn't have been retrieved Assert.assertNull(map.get(middleParent2Oid)); } @@ -268,9 +268,9 @@ public class BasicLookupStrategyTests { Permission[] checkPermission = new Permission[] { BasePermission.READ }; Sid[] sids = new Sid[] { new PrincipalSid("ben") }; ObjectIdentity[] childOids = new ObjectIdentity[] { childOid }; - + ((BasicLookupStrategy) this.strategy).setBatchSize(6); - Map foundAcls = strategy.readAclsById(childOids, sids); + Map foundAcls = strategy.readAclsById(childOids, sids); Acl foundChildAcl = (Acl) foundAcls.get(childOid); Assert.assertNotNull(foundChildAcl); @@ -290,5 +290,5 @@ public class BasicLookupStrategyTests { Assert.assertNotNull(foundParent2Acl); Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false)); } - -} \ No newline at end of file + +} diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java index 4d227b2774..3a83570ce1 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/EhCacheBasedAclCacheTests.java @@ -68,11 +68,10 @@ public class EhCacheBasedAclCacheTests { return cache; } - + @Test(expected=IllegalArgumentException.class) public void constructorRejectsNullParameters() throws Exception { - AclCache aclCache = new EhCacheBasedAclCache(null); - fail("It should have thrown IllegalArgumentException"); + new EhCacheBasedAclCache(null); } @Test @@ -125,7 +124,7 @@ public class EhCacheBasedAclCacheTests { assertTrue(true); } } - + // SEC-527 @Test public void testDiskSerializationOfMutableAclObjectInstance() throws Exception { @@ -138,20 +137,20 @@ public class EhCacheBasedAclCacheTests { // Serialization test File file = File.createTempFile("SEC_TEST", ".object"); FileOutputStream fos = new FileOutputStream(file); - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(acl); - oos.close(); - - FileInputStream fis = new FileInputStream(file); - ObjectInputStream ois = new ObjectInputStream(fis); - MutableAcl retrieved = (MutableAcl) ois.readObject(); - ois.close(); - + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(acl); + oos.close(); + + FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(fis); + MutableAcl retrieved = (MutableAcl) ois.readObject(); + ois.close(); + assertEquals(acl, retrieved); - + Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved); assertEquals(null, retrieved1); - + Object retrieved2 = FieldUtils.getProtectedFieldValue("auditLogger", retrieved); assertEquals(null, retrieved2); } @@ -173,7 +172,7 @@ public class EhCacheBasedAclCacheTests { assertEquals(2, cache.getDiskStoreSize()); assertTrue(cache.isElementOnDisk(acl.getObjectIdentity())); assertFalse(cache.isElementInMemory(acl.getObjectIdentity())); - + // Check we can get from cache the same objects we put in assertEquals(myCache.getFromCache(new Long(1)), acl); assertEquals(myCache.getFromCache(identity), acl); @@ -208,7 +207,7 @@ public class EhCacheBasedAclCacheTests { public void cacheOperationsAclWithParent() throws Exception { Ehcache cache = getCache(); EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache); - + Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") }); auth.setAuthenticated(true); @@ -221,7 +220,7 @@ public class EhCacheBasedAclCacheTests { new GrantedAuthorityImpl("ROLE_GENERAL") }); MutableAcl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl parentAcl = new AclImpl(identityParent, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger()); - + acl.setParent(parentAcl); assertEquals(0, cache.getDiskStoreSize()); diff --git a/acl/src/test/java/org/springframework/security/acls/objectidentity/ObjectIdentityTests.java b/acl/src/test/java/org/springframework/security/acls/objectidentity/ObjectIdentityTests.java index e168594ecd..5e1ea5396a 100644 --- a/acl/src/test/java/org/springframework/security/acls/objectidentity/ObjectIdentityTests.java +++ b/acl/src/test/java/org/springframework/security/acls/objectidentity/ObjectIdentityTests.java @@ -163,6 +163,7 @@ public class ObjectIdentityTests { } } + @SuppressWarnings("unused") private class MockOtherIdDomainObject { private Object id; diff --git a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java index 8dda20ff4a..2a05f75067 100644 --- a/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java +++ b/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java @@ -19,7 +19,7 @@ public class SidTests extends TestCase { // Check one String-argument constructor try { String string = null; - Sid principalSid = new PrincipalSid(string); + new PrincipalSid(string); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -27,7 +27,7 @@ public class SidTests extends TestCase { } try { - Sid principalSid = new PrincipalSid(""); + new PrincipalSid(""); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -35,7 +35,7 @@ public class SidTests extends TestCase { } try { - Sid principalSid = new PrincipalSid("johndoe"); + new PrincipalSid("johndoe"); Assert.assertTrue(true); } catch (IllegalArgumentException notExpected) { @@ -45,7 +45,7 @@ public class SidTests extends TestCase { // Check one Authentication-argument constructor try { Authentication authentication = null; - Sid principalSid = new PrincipalSid(authentication); + new PrincipalSid(authentication); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -54,7 +54,7 @@ public class SidTests extends TestCase { try { Authentication authentication = new TestingAuthenticationToken(null, "password"); - Sid principalSid = new PrincipalSid(authentication); + new PrincipalSid(authentication); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -63,7 +63,7 @@ public class SidTests extends TestCase { try { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); - Sid principalSid = new PrincipalSid(authentication); + new PrincipalSid(authentication); Assert.assertTrue(true); } catch (IllegalArgumentException notExpected) { @@ -75,7 +75,7 @@ public class SidTests extends TestCase { // Check one String-argument constructor try { String string = null; - Sid gaSid = new GrantedAuthoritySid(string); + new GrantedAuthoritySid(string); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -83,7 +83,7 @@ public class SidTests extends TestCase { } try { - Sid gaSid = new GrantedAuthoritySid(""); + new GrantedAuthoritySid(""); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -91,7 +91,7 @@ public class SidTests extends TestCase { } try { - Sid gaSid = new GrantedAuthoritySid("ROLE_TEST"); + new GrantedAuthoritySid("ROLE_TEST"); Assert.assertTrue(true); } catch (IllegalArgumentException notExpected) { @@ -101,7 +101,7 @@ public class SidTests extends TestCase { // Check one GrantedAuthority-argument constructor try { GrantedAuthority ga = null; - Sid gaSid = new GrantedAuthoritySid(ga); + new GrantedAuthoritySid(ga); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -110,7 +110,7 @@ public class SidTests extends TestCase { try { GrantedAuthority ga = new GrantedAuthorityImpl(null); - Sid gaSid = new GrantedAuthoritySid(ga); + new GrantedAuthoritySid(ga); Assert.fail("It should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { @@ -119,7 +119,7 @@ public class SidTests extends TestCase { try { GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST"); - Sid gaSid = new GrantedAuthoritySid(ga); + new GrantedAuthoritySid(ga); Assert.assertTrue(true); } catch (IllegalArgumentException notExpected) { diff --git a/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java b/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java index ed2c6b2f02..f2e4cb5a67 100644 --- a/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java +++ b/cas/src/main/java/org/springframework/security/providers/cas/CasAuthenticationProvider.java @@ -18,32 +18,23 @@ package org.springframework.security.providers.cas; import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.TicketValidationException; import org.jasig.cas.client.validation.TicketValidator; -import org.springframework.security.SpringSecurityMessageSource; -import org.springframework.security.Authentication; -import org.springframework.security.AuthenticationException; -import org.springframework.security.BadCredentialsException; - -import org.springframework.security.providers.AuthenticationProvider; -import org.springframework.security.providers.UsernamePasswordAuthenticationToken; -import org.springframework.security.providers.cas.cache.NullStatelessTicketCache; - -import org.springframework.security.ui.cas.CasProcessingFilter; -import org.springframework.security.ui.cas.ServiceProperties; - -import org.springframework.security.userdetails.UserDetails; -import org.springframework.security.userdetails.UserDetailsService; -import org.springframework.security.userdetails.UserDetailsChecker; -import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.springframework.beans.factory.InitializingBean; - import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; - +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationException; +import org.springframework.security.BadCredentialsException; +import org.springframework.security.SpringSecurityMessageSource; +import org.springframework.security.providers.AuthenticationProvider; +import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.providers.cas.cache.NullStatelessTicketCache; +import org.springframework.security.ui.cas.CasProcessingFilter; +import org.springframework.security.ui.cas.ServiceProperties; +import org.springframework.security.userdetails.UserDetails; +import org.springframework.security.userdetails.UserDetailsChecker; +import org.springframework.security.userdetails.UserDetailsService; +import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker; import org.springframework.util.Assert; @@ -60,9 +51,6 @@ import org.springframework.util.Assert; * @version $Id$ */ public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { - //~ Static fields/initializers ===================================================================================== - - private static final Log logger = LogFactory.getLog(CasAuthenticationProvider.class); //~ Instance fields ================================================================================================ @@ -144,17 +132,17 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia try { final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService()); final UserDetails userDetails = loadUserByAssertion(assertion); - userDetailsChecker.check(userDetails); + userDetailsChecker.check(userDetails); return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), userDetails.getAuthorities(), userDetails, assertion); } catch (final TicketValidationException e) { throw new BadCredentialsException(e.getMessage(), e); } } - + /** * Template method for retrieving the UserDetails based on the assertion. Default is to call configured userDetailsService and pass the username. Deployers * can override this method and retrieve the user based on any criteria they desire. - * + * * @param assertion The CAS Assertion. * @returns the UserDetails. */ @@ -169,7 +157,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia public void setUserDetailsService(final UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } - + public void setServiceProperties(final ServiceProperties serviceProperties) { this.serviceProperties = serviceProperties; } diff --git a/cas/src/main/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCache.java b/cas/src/main/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCache.java index 20853fbb34..daa8fe1fbe 100644 --- a/cas/src/main/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCache.java +++ b/cas/src/main/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCache.java @@ -33,31 +33,31 @@ import org.springframework.security.providers.cas.StatelessTicketCache; */ public final class NullStatelessTicketCache implements StatelessTicketCache { - /** - * @return null since we are not storing any tickets. - */ - public CasAuthenticationToken getByTicketId(final String serviceTicket) { - return null; - } + /** + * @return null since we are not storing any tickets. + */ + public CasAuthenticationToken getByTicketId(final String serviceTicket) { + return null; + } - /** - * This is a no-op since we are not storing tickets. - */ - public void putTicketInCache(final CasAuthenticationToken token) { - // nothing to do - } + /** + * This is a no-op since we are not storing tickets. + */ + public void putTicketInCache(final CasAuthenticationToken token) { + // nothing to do + } - /** - * This is a no-op since we are not storing tickets. - */ - public void removeTicketFromCache(final CasAuthenticationToken token) { - // nothing to do - } + /** + * This is a no-op since we are not storing tickets. + */ + public void removeTicketFromCache(final CasAuthenticationToken token) { + // nothing to do + } - /** - * This is a no-op since we are not storing tickets. - */ - public void removeTicketFromCache(final String serviceTicket) { - // nothing to do - } + /** + * This is a no-op since we are not storing tickets. + */ + public void removeTicketFromCache(final String serviceTicket) { + // nothing to do + } } diff --git a/cas/src/main/java/org/springframework/security/ui/cas/CasProcessingFilterEntryPoint.java b/cas/src/main/java/org/springframework/security/ui/cas/CasProcessingFilterEntryPoint.java index 5c9b0d17cb..460faaae1f 100644 --- a/cas/src/main/java/org/springframework/security/ui/cas/CasProcessingFilterEntryPoint.java +++ b/cas/src/main/java/org/springframework/security/ui/cas/CasProcessingFilterEntryPoint.java @@ -60,13 +60,13 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint, //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { Assert.hasLength(this.loginUrl, "loginUrl must be specified"); Assert.notNull(this.serviceProperties, "serviceProperties must be specified"); } public void commence(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, - final AuthenticationException authenticationException) throws IOException, ServletException { + final AuthenticationException authenticationException) throws IOException, ServletException { final HttpServletResponse response = (HttpServletResponse) servletResponse; final String urlEncodedService = CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, "ticket", this.encodeServiceUrlWithSessionId); @@ -98,6 +98,6 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint, } public void setEncodeServiceUrlWithSessionId(final boolean encodeServiceUrlWithSessionId) { - this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; + this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; } } diff --git a/cas/src/main/java/org/springframework/security/ui/cas/ServiceProperties.java b/cas/src/main/java/org/springframework/security/ui/cas/ServiceProperties.java index 8086ce6501..d964bf3b4c 100644 --- a/cas/src/main/java/org/springframework/security/ui/cas/ServiceProperties.java +++ b/cas/src/main/java/org/springframework/security/ui/cas/ServiceProperties.java @@ -38,7 +38,7 @@ public class ServiceProperties implements InitializingBean { //~ Methods ======================================================================================================== public void afterPropertiesSet() throws Exception { - Assert.hasLength(this.service, "service must be specified."); + Assert.hasLength(this.service, "service must be specified."); } /** diff --git a/cas/src/test/java/org/springframework/security/providers/cas/CasAuthenticationProviderTests.java b/cas/src/test/java/org/springframework/security/providers/cas/CasAuthenticationProviderTests.java index e276aa6644..a0fe7b9ad3 100644 --- a/cas/src/test/java/org/springframework/security/providers/cas/CasAuthenticationProviderTests.java +++ b/cas/src/test/java/org/springframework/security/providers/cas/CasAuthenticationProviderTests.java @@ -30,6 +30,7 @@ import org.springframework.security.ui.cas.ServiceProperties; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; +import org.springframework.security.util.AuthorityUtils; import java.util.HashMap; import java.util.Map; @@ -54,12 +55,12 @@ public class CasAuthenticationProviderTests { private UserDetails makeUserDetails() { return new User("user", "password", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } private UserDetails makeUserDetailsFromAuthoritiesPopulator() { return new User("user", "password", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")}); + AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); } private ServiceProperties makeServiceProperties() { @@ -83,8 +84,8 @@ public class CasAuthenticationProviderTests { cap.setTicketValidator(new MockTicketValidator(true)); cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, - "ST-123"); + UsernamePasswordAuthenticationToken token = + new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, "ST-123"); token.setDetails("details"); Authentication result = cap.authenticate(token); @@ -124,8 +125,8 @@ public class CasAuthenticationProviderTests { cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER, - "ST-456"); + UsernamePasswordAuthenticationToken token = + new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER, "ST-456"); token.setDetails("details"); Authentication result = cap.authenticate(token); @@ -183,7 +184,7 @@ public class CasAuthenticationProviderTests { cap.afterPropertiesSet(); CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials", - new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), assertion); + AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion); cap.authenticate(token); } @@ -275,7 +276,7 @@ public class CasAuthenticationProviderTests { cap.afterPropertiesSet(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user", - "password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")}); + "password", AuthorityUtils.createAuthorityList("ROLE_A")); assertEquals(null, cap.authenticate(token)); } @@ -295,10 +296,10 @@ public class CasAuthenticationProviderTests { } private class MockStatelessTicketCache implements StatelessTicketCache { - private Map cache = new HashMap(); + private Map cache = new HashMap(); public CasAuthenticationToken getByTicketId(String serviceTicket) { - return (CasAuthenticationToken) cache.get(serviceTicket); + return cache.get(serviceTicket); } public void putTicketInCache(CasAuthenticationToken token) { diff --git a/cas/src/test/java/org/springframework/security/providers/cas/cache/AbstractStatelessTicketCacheTests.java b/cas/src/test/java/org/springframework/security/providers/cas/cache/AbstractStatelessTicketCacheTests.java index 6af289b8b0..3a6be6ffaa 100644 --- a/cas/src/test/java/org/springframework/security/providers/cas/cache/AbstractStatelessTicketCacheTests.java +++ b/cas/src/test/java/org/springframework/security/providers/cas/cache/AbstractStatelessTicketCacheTests.java @@ -5,31 +5,28 @@ import java.util.List; import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.AssertionImpl; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.cas.CasAuthenticationToken; import org.springframework.security.userdetails.User; +import org.springframework.security.util.AuthorityUtils; /** - * + * * @author Scott Battaglia - * @version $Revision$ $Date$ + * @version $Id$ * @since 2.0 * */ public abstract class AbstractStatelessTicketCacheTests { - - protected CasAuthenticationToken getToken() { + + protected CasAuthenticationToken getToken() { List proxyList = new ArrayList(); proxyList.add("https://localhost/newPortal/j_spring_cas_security_check"); - User user = new User("rod", "password", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + User user = new User("rod", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); final Assertion assertion = new AssertionImpl("rod"); return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user, - assertion); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion); } } diff --git a/cas/src/test/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCacheTests.java b/cas/src/test/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCacheTests.java index ea0724178f..7ab118198b 100644 --- a/cas/src/test/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCacheTests.java +++ b/cas/src/test/java/org/springframework/security/providers/cas/cache/NullStatelessTicketCacheTests.java @@ -30,18 +30,18 @@ import static org.junit.Assert.*; */ public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests { - private StatelessTicketCache cache = new NullStatelessTicketCache(); - - @Test - public void testGetter() { - assertNull(cache.getByTicketId(null)); - assertNull(cache.getByTicketId("test")); - } - - @Test - public void testInsertAndGet() { - final CasAuthenticationToken token = getToken(); - cache.putTicketInCache(token); - assertNull(cache.getByTicketId((String) token.getCredentials())); - } + private StatelessTicketCache cache = new NullStatelessTicketCache(); + + @Test + public void testGetter() { + assertNull(cache.getByTicketId(null)); + assertNull(cache.getByTicketId("test")); + } + + @Test + public void testInsertAndGet() { + final CasAuthenticationToken token = getToken(); + cache.putTicketInCache(token); + assertNull(cache.getByTicketId((String) token.getCredentials())); + } } diff --git a/core/src/main/java/org/springframework/security/GrantedAuthority.java b/core/src/main/java/org/springframework/security/GrantedAuthority.java index a0c8ed40f7..ed6b379147 100644 --- a/core/src/main/java/org/springframework/security/GrantedAuthority.java +++ b/core/src/main/java/org/springframework/security/GrantedAuthority.java @@ -26,13 +26,10 @@ import org.springframework.security.userdetails.UserDetails; * A GrantedAuthority must either represent itself as a * String or be specifically supported by an {@link * AccessDecisionManager}. - *

- * *

* Implementations must implement {@link Comparable} in order to ensure that * array sorting logic guaranteed by {@link UserDetails#getAuthorities()} can * be reliably implemented. - *

* * @author Ben Alex * @version $Id$ diff --git a/core/src/main/java/org/springframework/security/GrantedAuthorityImpl.java b/core/src/main/java/org/springframework/security/GrantedAuthorityImpl.java index f9aa32986a..c705dd89c3 100644 --- a/core/src/main/java/org/springframework/security/GrantedAuthorityImpl.java +++ b/core/src/main/java/org/springframework/security/GrantedAuthorityImpl.java @@ -73,16 +73,16 @@ public class GrantedAuthorityImpl implements GrantedAuthority, Serializable { return this.role; } - public int compareTo(Object o) { - if (o != null && o instanceof GrantedAuthority) { - String rhsRole = ((GrantedAuthority) o).getAuthority(); - - if (rhsRole == null) { - return -1; - } - - return role.compareTo(rhsRole); - } - return -1; - } + public int compareTo(Object o) { + if (o != null && o instanceof GrantedAuthority) { + String rhsRole = ((GrantedAuthority) o).getAuthority(); + + if (rhsRole == null) { + return -1; + } + + return role.compareTo(rhsRole); + } + return -1; + } } diff --git a/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionControllerImpl.java b/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionControllerImpl.java index 4435509701..bc838ad036 100644 --- a/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionControllerImpl.java +++ b/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionControllerImpl.java @@ -159,7 +159,7 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl this.sessionRegistry = sessionRegistry; } - public SessionRegistry getSessionRegistry() { - return sessionRegistry; - } + public SessionRegistry getSessionRegistry() { + return sessionRegistry; + } } diff --git a/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionFilter.java b/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionFilter.java index 5b626ab3ee..c8721b1144 100644 --- a/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionFilter.java +++ b/core/src/main/java/org/springframework/security/concurrent/ConcurrentSessionFilter.java @@ -24,7 +24,6 @@ import org.springframework.security.ui.logout.SecurityContextLogoutHandler; import org.springframework.security.util.UrlUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; import javax.servlet.FilterChain; import javax.servlet.ServletException; diff --git a/core/src/main/java/org/springframework/security/config/AbstractUserDetailsServiceBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/AbstractUserDetailsServiceBeanDefinitionParser.java index f67a3c3af6..afcf879d1b 100644 --- a/core/src/main/java/org/springframework/security/config/AbstractUserDetailsServiceBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/AbstractUserDetailsServiceBeanDefinitionParser.java @@ -17,45 +17,45 @@ import org.w3c.dom.Element; * @version $Id$ */ public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements BeanDefinitionParser { - private static final String CACHE_REF = "cache-ref"; - public static final String CACHING_SUFFIX = ".caching"; - - /** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */ - private String id; - - protected abstract String getBeanClassName(Element element); - - protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder); - - public BeanDefinition parse(Element element, ParserContext parserContext) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element)); - - doParse(element, parserContext, builder); - - RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition(); - String beanId = resolveId(element, userService, parserContext); - - parserContext.getRegistry().registerBeanDefinition(beanId, userService); - - String cacheRef = element.getAttribute(CACHE_REF); - - // Register a caching version of the user service if there's a cache-ref - if (StringUtils.hasText(cacheRef)) { - BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class); - cachingUSBuilder.addConstructorArgReference(beanId); - - cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef)); - BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition(); - parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService); - } + private static final String CACHE_REF = "cache-ref"; + public static final String CACHING_SUFFIX = ".caching"; + + /** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */ + private String id; + + protected abstract String getBeanClassName(Element element); + + protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder); + + public BeanDefinition parse(Element element, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element)); + + doParse(element, parserContext, builder); + + RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition(); + String beanId = resolveId(element, userService, parserContext); + + parserContext.getRegistry().registerBeanDefinition(beanId, userService); + + String cacheRef = element.getAttribute(CACHE_REF); + + // Register a caching version of the user service if there's a cache-ref + if (StringUtils.hasText(cacheRef)) { + BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class); + cachingUSBuilder.addConstructorArgReference(beanId); + + cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef)); + BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition(); + parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService); + } - id = beanId; - - return null; - } + id = beanId; + + return null; + } private String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) - throws BeanDefinitionStoreException { + throws BeanDefinitionStoreException { String id = element.getAttribute("id"); @@ -76,7 +76,7 @@ public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements return BeanIds.USER_DETAILS_SERVICE; } - String getId() { - return id; - } + String getId() { + return id; + } } diff --git a/core/src/main/java/org/springframework/security/config/AuthenticationManagerBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/AuthenticationManagerBeanDefinitionParser.java index d69428f263..d0fe957de3 100644 --- a/core/src/main/java/org/springframework/security/config/AuthenticationManagerBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/AuthenticationManagerBeanDefinitionParser.java @@ -19,11 +19,11 @@ import org.w3c.dom.Element; */ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinitionParser { private static final String ATT_SESSION_CONTROLLER_REF = "session-controller-ref"; - private static final String ATT_ALIAS = "alias"; + private static final String ATT_ALIAS = "alias"; public BeanDefinition parse(Element element, ParserContext parserContext) { - ConfigUtils.registerProviderManagerIfNecessary(parserContext); - + ConfigUtils.registerProviderManagerIfNecessary(parserContext); + String alias = element.getAttribute(ATT_ALIAS); if (!StringUtils.hasText(alias)) { @@ -33,16 +33,16 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition String sessionControllerRef = element.getAttribute(ATT_SESSION_CONTROLLER_REF); if (StringUtils.hasText(sessionControllerRef)) { - BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER); + BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER); ConfigUtils.setSessionControllerOnAuthenticationManager(parserContext, - BeanIds.CONCURRENT_SESSION_CONTROLLER, element); - authManager.getPropertyValues().addPropertyValue("sessionController", - new RuntimeBeanReference(sessionControllerRef)); + BeanIds.CONCURRENT_SESSION_CONTROLLER, element); + authManager.getPropertyValues().addPropertyValue("sessionController", + new RuntimeBeanReference(sessionControllerRef)); RootBeanDefinition sessionRegistryInjector = new RootBeanDefinition(SessionRegistryInjectionBeanPostProcessor.class); sessionRegistryInjector.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); sessionRegistryInjector.getConstructorArgumentValues().addGenericArgumentValue(sessionControllerRef); - - parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_REGISTRY_INJECTION_POST_PROCESSOR, sessionRegistryInjector); + + parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_REGISTRY_INJECTION_POST_PROCESSOR, sessionRegistryInjector); } parserContext.getRegistry().registerAlias(BeanIds.AUTHENTICATION_MANAGER, alias); diff --git a/core/src/main/java/org/springframework/security/config/BasicAuthenticationBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/BasicAuthenticationBeanDefinitionParser.java index 2d7470ff2d..6f12f10dd5 100644 --- a/core/src/main/java/org/springframework/security/config/BasicAuthenticationBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/BasicAuthenticationBeanDefinitionParser.java @@ -20,30 +20,30 @@ import org.w3c.dom.Element; * @version $Id$ */ public class BasicAuthenticationBeanDefinitionParser implements BeanDefinitionParser { - private String realmName; + private String realmName; - public BasicAuthenticationBeanDefinitionParser(String realmName) { - this.realmName = realmName; - } + public BasicAuthenticationBeanDefinitionParser(String realmName) { + this.realmName = realmName; + } - public BeanDefinition parse(Element elt, ParserContext parserContext) { + public BeanDefinition parse(Element elt, ParserContext parserContext) { BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder.rootBeanDefinition(BasicProcessingFilter.class); - RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class); - entryPoint.setSource(parserContext.extractSource(elt)); - entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - - entryPoint.getPropertyValues().addPropertyValue("realmName", realmName); - - parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint); + RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class); + entryPoint.setSource(parserContext.extractSource(elt)); + entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + + entryPoint.getPropertyValues().addPropertyValue("realmName", realmName); + + parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint); - filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER)); - filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT)); + filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER)); + filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT)); - parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER, - filterBuilder.getBeanDefinition()); - ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER)); - parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(), - BeanIds.BASIC_AUTHENTICATION_FILTER)); - return null; - } + parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER, + filterBuilder.getBeanDefinition()); + ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER)); + parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(), + BeanIds.BASIC_AUTHENTICATION_FILTER)); + return null; + } } diff --git a/core/src/main/java/org/springframework/security/config/CachingUserDetailsService.java b/core/src/main/java/org/springframework/security/config/CachingUserDetailsService.java index 505e3ada79..dac53a5fa0 100644 --- a/core/src/main/java/org/springframework/security/config/CachingUserDetailsService.java +++ b/core/src/main/java/org/springframework/security/config/CachingUserDetailsService.java @@ -12,33 +12,33 @@ import org.springframework.util.Assert; * @since 2.0 */ class CachingUserDetailsService implements UserDetailsService { - private UserCache userCache = new NullUserCache(); - private UserDetailsService delegate; + private UserCache userCache = new NullUserCache(); + private UserDetailsService delegate; - CachingUserDetailsService(UserDetailsService delegate) { - this.delegate = delegate; - } + CachingUserDetailsService(UserDetailsService delegate) { + this.delegate = delegate; + } - public UserCache getUserCache() { - return userCache; - } + public UserCache getUserCache() { + return userCache; + } - public void setUserCache(UserCache userCache) { - this.userCache = userCache; - } + public void setUserCache(UserCache userCache) { + this.userCache = userCache; + } - public UserDetails loadUserByUsername(String username) { - UserDetails user = userCache.getUserFromCache(username); - - if (user == null) { - user = delegate.loadUserByUsername(username); - } - - Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " + - "This is an interface contract violation"); - - userCache.putUserInCache(user); - - return user; - } + public UserDetails loadUserByUsername(String username) { + UserDetails user = userCache.getUserFromCache(username); + + if (user == null) { + user = delegate.loadUserByUsername(username); + } + + Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " + + "This is an interface contract violation"); + + userCache.putUserInCache(user); + + return user; + } } diff --git a/core/src/main/java/org/springframework/security/config/ConfigUtils.java b/core/src/main/java/org/springframework/security/config/ConfigUtils.java index b6d6033e5d..e3ff23b1aa 100644 --- a/core/src/main/java/org/springframework/security/config/ConfigUtils.java +++ b/core/src/main/java/org/springframework/security/config/ConfigUtils.java @@ -87,11 +87,13 @@ abstract class ConfigUtils { ((ArrayList) authManager.getPropertyValues().getPropertyValue("providerBeanNames").getValue()).add(beanName); } + @SuppressWarnings("unchecked") static ManagedList getRegisteredAfterInvocationProviders(ParserContext parserContext) { BeanDefinition manager = registerAfterInvocationProviderManagerIfNecessary(parserContext); return (ManagedList) manager.getPropertyValues().getPropertyValue("providers").getValue(); } + @SuppressWarnings("unchecked") private static BeanDefinition registerAfterInvocationProviderManagerIfNecessary(ParserContext parserContext) { if(parserContext.getRegistry().containsBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER)) { return parserContext.getRegistry().getBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER); diff --git a/core/src/main/java/org/springframework/security/config/FilterInvocationDefinitionSourceBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/FilterInvocationDefinitionSourceBeanDefinitionParser.java index 836d1e44ed..20a6ac91ec 100644 --- a/core/src/main/java/org/springframework/security/config/FilterInvocationDefinitionSourceBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/FilterInvocationDefinitionSourceBeanDefinitionParser.java @@ -27,7 +27,6 @@ public class FilterInvocationDefinitionSourceBeanDefinitionParser extends Abstra return "org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource"; } - @SuppressWarnings("unchecked") protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { List interceptUrls = DomUtils.getChildElementsByTagName(element, "intercept-url"); diff --git a/core/src/main/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParser.java index 731d43ea9b..fe0ad5ce28 100644 --- a/core/src/main/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParser.java @@ -166,6 +166,7 @@ class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionParser { pc.getRegistry().registerBeanDefinition(ACCESS_MANAGER_ID, accessMgrBuilder.getBeanDefinition()); } + @SuppressWarnings("unchecked") private void registerDelegatingMethodDefinitionSource(ParserContext parserContext, ManagedList delegates, Object source) { if (parserContext.getRegistry().containsBeanDefinition(DELEGATING_METHOD_DEFINITION_SOURCE_ID)) { parserContext.getReaderContext().error("Duplicate detected.", source); diff --git a/core/src/main/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecorator.java b/core/src/main/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecorator.java index 5c0468190a..199d628513 100644 --- a/core/src/main/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecorator.java +++ b/core/src/main/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecorator.java @@ -42,7 +42,6 @@ class InternalInterceptMethodsBeanDefinitionDecorator extends AbstractIntercepto static final String ATT_ACCESS = "access"; private static final String ATT_ACCESS_MGR = "access-decision-manager-ref"; - @SuppressWarnings("unchecked") protected BeanDefinition createInterceptorDefinition(Node node) { Element interceptMethodsElt = (Element)node; BeanDefinitionBuilder interceptor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityInterceptor.class); diff --git a/core/src/main/java/org/springframework/security/config/JdbcUserServiceBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/JdbcUserServiceBeanDefinitionParser.java index 8b7b15d713..4a78a92e61 100644 --- a/core/src/main/java/org/springframework/security/config/JdbcUserServiceBeanDefinitionParser.java +++ b/core/src/main/java/org/springframework/security/config/JdbcUserServiceBeanDefinitionParser.java @@ -11,11 +11,11 @@ import org.w3c.dom.Element; * @version $Id$ */ public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServiceBeanDefinitionParser { - static final String ATT_DATA_SOURCE = "data-source-ref"; - static final String ATT_USERS_BY_USERNAME_QUERY = "users-by-username-query"; - static final String ATT_AUTHORITIES_BY_USERNAME_QUERY = "authorities-by-username-query"; - static final String ATT_GROUP_AUTHORITIES_QUERY = "group-authorities-by-username-query"; - static final String ATT_ROLE_PREFIX = "role-prefix"; + static final String ATT_DATA_SOURCE = "data-source-ref"; + static final String ATT_USERS_BY_USERNAME_QUERY = "users-by-username-query"; + static final String ATT_AUTHORITIES_BY_USERNAME_QUERY = "authorities-by-username-query"; + static final String ATT_GROUP_AUTHORITIES_QUERY = "group-authorities-by-username-query"; + static final String ATT_ROLE_PREFIX = "role-prefix"; protected String getBeanClassName(Element element) { return "org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager"; diff --git a/core/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java b/core/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java index 3f5339323d..6a003ee819 100644 --- a/core/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java +++ b/core/src/main/java/org/springframework/security/config/SecurityNamespaceHandler.java @@ -14,8 +14,8 @@ public class SecurityNamespaceHandler extends NamespaceHandlerSupport { public void init() { // Parsers - registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser()); - registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser()); + registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser()); + registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser()); registerBeanDefinitionParser(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser()); registerBeanDefinitionParser(Elements.HTTP, new HttpSecurityBeanDefinitionParser()); registerBeanDefinitionParser(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser()); diff --git a/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java b/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java index 68e9fda709..2302d4e03c 100644 --- a/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java +++ b/core/src/main/java/org/springframework/security/config/SessionRegistryInjectionBeanPostProcessor.java @@ -56,7 +56,6 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be return bean; } - @SuppressWarnings("unchecked") private SessionRegistry getSessionRegistry() { if (sessionRegistry != null) { return sessionRegistry; @@ -84,7 +83,7 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be logger.warn("More than one SessionRegistry instance in application context. Possible configuration errors may result."); } - sessionRegistry = (SessionRegistry) sessionRegs.get(0); + sessionRegistry = sessionRegs.get(0); return sessionRegistry; } diff --git a/core/src/main/java/org/springframework/security/event/authentication/InteractiveAuthenticationSuccessEvent.java b/core/src/main/java/org/springframework/security/event/authentication/InteractiveAuthenticationSuccessEvent.java index 6321db7b4d..831cddc6a2 100644 --- a/core/src/main/java/org/springframework/security/event/authentication/InteractiveAuthenticationSuccessEvent.java +++ b/core/src/main/java/org/springframework/security/event/authentication/InteractiveAuthenticationSuccessEvent.java @@ -30,11 +30,11 @@ import org.springframework.util.Assert; public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticationEvent { //~ Instance fields ================================================================================================ - private Class generatedBy; + private Class generatedBy; //~ Constructors =================================================================================================== - public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class generatedBy) { + public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class generatedBy) { super(authentication); Assert.notNull(generatedBy); this.generatedBy = generatedBy; @@ -48,7 +48,7 @@ public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticatio * * @return the class */ - public Class getGeneratedBy() { + public Class getGeneratedBy() { return generatedBy; } } diff --git a/core/src/main/java/org/springframework/security/event/authentication/LoggerListener.java b/core/src/main/java/org/springframework/security/event/authentication/LoggerListener.java index 076bf5c10b..bcbe38d7c1 100644 --- a/core/src/main/java/org/springframework/security/event/authentication/LoggerListener.java +++ b/core/src/main/java/org/springframework/security/event/authentication/LoggerListener.java @@ -23,8 +23,9 @@ import org.springframework.util.ClassUtils; /** - * Outputs authentication-related application events to Commons Logging.

All authentication events are logged at - * the warning level.

+ * Outputs authentication-related application events to Commons Logging. + *

+ * All authentication events are logged at the warning level. * * @author Ben Alex * @version $Id$ @@ -44,7 +45,7 @@ public class LoggerListener implements ApplicationListener { AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event; if (!logInteractiveAuthenticationSuccessEvents && authEvent instanceof InteractiveAuthenticationSuccessEvent) { - return; + return; } if (logger.isWarnEnabled()) { @@ -62,12 +63,12 @@ public class LoggerListener implements ApplicationListener { } } - public boolean isLogInteractiveAuthenticationSuccessEvents() { - return logInteractiveAuthenticationSuccessEvents; - } + public boolean isLogInteractiveAuthenticationSuccessEvents() { + return logInteractiveAuthenticationSuccessEvents; + } - public void setLogInteractiveAuthenticationSuccessEvents( - boolean logInteractiveAuthenticationSuccessEvents) { - this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents; - } + public void setLogInteractiveAuthenticationSuccessEvents( + boolean logInteractiveAuthenticationSuccessEvents) { + this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents; + } } diff --git a/core/src/main/java/org/springframework/security/intercept/method/MapBasedMethodDefinitionSource.java b/core/src/main/java/org/springframework/security/intercept/method/MapBasedMethodDefinitionSource.java index 80a11ae346..d61a2d9457 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/MapBasedMethodDefinitionSource.java +++ b/core/src/main/java/org/springframework/security/intercept/method/MapBasedMethodDefinitionSource.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @@ -88,7 +87,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini return findAttributesSpecifiedAgainst(method, targetClass); } - private List findAttributesSpecifiedAgainst(Method method, Class clazz) { + private List findAttributesSpecifiedAgainst(Method method, Class clazz) { RegisteredMethod registeredMethod = new RegisteredMethod(method, clazz); if (methodMap.containsKey(registeredMethod)) { return (List) methodMap.get(registeredMethod); @@ -118,7 +117,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini Assert.hasText(methodName, "Method not found for '" + name + "'"); String typeName = name.substring(0, lastDotIndex); - Class type = ClassUtils.resolveClassName(typeName, this.beanClassLoader); + Class type = ClassUtils.resolveClassName(typeName, this.beanClassLoader); addSecureMethod(type, methodName, attr); } @@ -131,7 +130,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini * @param mappedName mapped method name, which the javaType has declared or inherited * @param attr required authorities associated with the method */ - public void addSecureMethod(Class javaType, String mappedName, List attr) { + public void addSecureMethod(Class javaType, String mappedName, List attr) { String name = javaType.getName() + '.' + mappedName; if (logger.isDebugEnabled()) { @@ -179,7 +178,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini * the existing match will be retained, so that if this method is called for a more general pointcut * it will not override a more specific one which has already been added. This */ - public void addSecureMethod(Class javaType, Method method, List attr) { + public void addSecureMethod(Class javaType, Method method, List attr) { RegisteredMethod key = new RegisteredMethod(method, javaType); if (methodMap.containsKey(key)) { @@ -255,9 +254,9 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini */ private class RegisteredMethod { private Method method; - private Class registeredJavaType; + private Class registeredJavaType; - public RegisteredMethod(Method method, Class registeredJavaType) { + public RegisteredMethod(Method method, Class registeredJavaType) { Assert.notNull(method, "Method required"); Assert.notNull(registeredJavaType, "Registered Java Type required"); this.method = method; diff --git a/core/src/main/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditor.java b/core/src/main/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditor.java index 203052c891..913513548b 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditor.java @@ -15,23 +15,18 @@ package org.springframework.security.intercept.method; -import org.springframework.security.ConfigAttribute; -import org.springframework.security.SecurityConfig; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.propertyeditors.PropertiesEditor; -import org.springframework.util.StringUtils; - import java.beans.PropertyEditorSupport; - import java.util.ArrayList; import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Map; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.springframework.beans.propertyeditors.PropertiesEditor; +import org.springframework.security.ConfigAttribute; +import org.springframework.security.SecurityConfig; +import org.springframework.util.StringUtils; /** @@ -44,12 +39,9 @@ import java.util.LinkedHashMap; * @version $Id$ */ public class MethodDefinitionSourceEditor extends PropertyEditorSupport { - //~ Static fields/initializers ===================================================================================== - - private static final Log logger = LogFactory.getLog(MethodDefinitionSourceEditor.class); - //~ Methods ======================================================================================================== + @SuppressWarnings("unchecked") public void setAsText(String s) throws IllegalArgumentException { if ((s == null) || "".equals(s)) { setValue(new MapBasedMethodDefinitionSource()); @@ -63,7 +55,7 @@ public class MethodDefinitionSourceEditor extends PropertyEditorSupport { Properties props = (Properties) propertiesEditor.getValue(); // Now we have properties, process each one individually - Map mappings = new LinkedHashMap(); + Map> mappings = new LinkedHashMap>(); for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); diff --git a/core/src/main/java/org/springframework/security/intercept/method/ProtectPointcutPostProcessor.java b/core/src/main/java/org/springframework/security/intercept/method/ProtectPointcutPostProcessor.java index 0e07e9286b..8037381848 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/ProtectPointcutPostProcessor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/ProtectPointcutPostProcessor.java @@ -2,7 +2,6 @@ package org.springframework.security.intercept.method; import java.lang.reflect.Method; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -29,25 +28,18 @@ import org.springframework.util.StringUtils; * having every method of every bean defined in the Spring application context compared with * those pointcuts. Where a match is found, the matching method will be registered with the * {@link MapBasedMethodDefinitionSource}. - *

- * *

* It is very important to understand that only the first pointcut that matches a given * method will be taken as authoritative for that method. This is why pointcuts should be provided * as a LinkedHashMap, because their order is very important. - *

- * *

* Note also that only beans defined in the Spring application context will be examined by this * class. - *

- * *

* Because this class registers method security metadata with {@link MapBasedMethodDefinitionSource}, * normal Spring Security capabilities such as {@link MethodDefinitionSourceAdvisor} can be used. * It does not matter the fact the method metadata was originally obtained from an AspectJ pointcut * expression evaluation. - *

* * @author Ben Alex * @verion $Id$ @@ -58,7 +50,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor { private static final Log logger = LogFactory.getLog(ProtectPointcutPostProcessor.class); - private Map> pointcutMap = new LinkedHashMap(); + private Map> pointcutMap = new LinkedHashMap>(); private MapBasedMethodDefinitionSource mapBasedMethodDefinitionSource; private PointcutParser parser; @@ -66,18 +58,18 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor { Assert.notNull(mapBasedMethodDefinitionSource, "MapBasedMethodDefinitionSource to populate is required"); this.mapBasedMethodDefinitionSource = mapBasedMethodDefinitionSource; - // Setup AspectJ pointcut expression parser - Set supportedPrimitives = new HashSet(); + // Set up AspectJ pointcut expression parser + Set supportedPrimitives = new HashSet(3); supportedPrimitives.add(PointcutPrimitive.EXECUTION); supportedPrimitives.add(PointcutPrimitive.ARGS); supportedPrimitives.add(PointcutPrimitive.REFERENCE); -// supportedPrimitives.add(PointcutPrimitive.THIS); -// supportedPrimitives.add(PointcutPrimitive.TARGET); -// supportedPrimitives.add(PointcutPrimitive.WITHIN); -// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION); -// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN); -// supportedPrimitives.add(PointcutPrimitive.AT_ARGS); -// supportedPrimitives.add(PointcutPrimitive.AT_TARGET); +// supportedPrimitives.add(PointcutPrimitive.THIS); +// supportedPrimitives.add(PointcutPrimitive.TARGET); +// supportedPrimitives.add(PointcutPrimitive.WITHIN); +// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION); +// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN); +// supportedPrimitives.add(PointcutPrimitive.AT_ARGS); +// supportedPrimitives.add(PointcutPrimitive.AT_TARGET); parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives); } @@ -96,10 +88,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor { // Check to see if any of those methods are compatible with our pointcut expressions for (int i = 0; i < methods.length; i++) { - Iterator iter = pointcutMap.keySet().iterator(); - while (iter.hasNext()) { - String ex = iter.next().toString(); - + for (String ex : pointcutMap.keySet()) { // Parse the presented AspectJ pointcut expression PointcutExpression expression = parser.parsePointcutExpression(ex); @@ -114,7 +103,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor { return bean; } - private boolean attemptMatch(Class targetClass, Method method, PointcutExpression expression, String beanName) { + private boolean attemptMatch(Class targetClass, Method method, PointcutExpression expression, String beanName) { // Determine if the presented AspectJ pointcut expression matches this method boolean matches = expression.matchesMethodExecution(method).alwaysMatches(); @@ -134,9 +123,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor { public void setPointcutMap(Map> map) { Assert.notEmpty(map); - Iterator i = map.keySet().iterator(); - while (i.hasNext()) { - String expression = i.next().toString(); + for (String expression : map.keySet()) { List value = map.get(expression); addPointcut(expression, value); } diff --git a/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java b/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java index e070225385..6e82df2dfb 100644 --- a/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java +++ b/core/src/main/java/org/springframework/security/intercept/method/aopalliance/MethodDefinitionSourceAdvisor.java @@ -115,6 +115,7 @@ public class MethodDefinitionSourceAdvisor extends AbstractPointcutAdvisor imple //~ Inner Classes ================================================================================================== class MethodDefinitionSourcePointcut extends StaticMethodMatcherPointcut { + @SuppressWarnings("unchecked") public boolean matches(Method m, Class targetClass) { return attributeSource.getAttributes(m, targetClass) != null; } diff --git a/core/src/main/java/org/springframework/security/intercept/web/RequestKey.java b/core/src/main/java/org/springframework/security/intercept/web/RequestKey.java index aed8977461..56ed979644 100644 --- a/core/src/main/java/org/springframework/security/intercept/web/RequestKey.java +++ b/core/src/main/java/org/springframework/security/intercept/web/RequestKey.java @@ -49,21 +49,21 @@ public class RequestKey { } if (method == null) { - return key.method == null; + return key.method == null; } return method.equals(key.method); } - public String toString() { - StringBuffer sb = new StringBuffer(url.length() + 7); - sb.append("["); - if (method != null) { - sb.append(method).append(","); - } - sb.append(url); - sb.append("]"); - - return sb.toString(); - } + public String toString() { + StringBuffer sb = new StringBuffer(url.length() + 7); + sb.append("["); + if (method != null) { + sb.append(method).append(","); + } + sb.append(url); + sb.append("]"); + + return sb.toString(); + } } diff --git a/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java b/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java index 250dbd8fcf..81ec626330 100644 --- a/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java +++ b/core/src/main/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulator.java @@ -29,8 +29,8 @@ import org.apache.commons.logging.LogFactory; import javax.naming.directory.SearchControls; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -181,7 +181,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator Set roles = getGroupMembershipRoles(userDn, username); - Set extraRoles = getAdditionalRoles(user, username); + Set extraRoles = getAdditionalRoles(user, username); if (extraRoles != null) { roles.addAll(extraRoles); @@ -198,28 +198,25 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator } public Set getGroupMembershipRoles(String userDn, String username) { - Set authorities = new HashSet(); - if (getGroupSearchBase() == null) { - return authorities; + return Collections.emptySet(); } + Set authorities = new HashSet(); + if (logger.isDebugEnabled()) { logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter " + groupSearchFilter + " in search base '" + getGroupSearchBase() + "'"); } - Set userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter, + Set userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter, new String[]{userDn, username}, groupRoleAttribute); if (logger.isDebugEnabled()) { logger.debug("Roles from search: " + userRoles); } - Iterator it = userRoles.iterator(); - - while (it.hasNext()) { - String role = (String) it.next(); + for (String role : userRoles) { if (convertToUpperCase) { role = role.toUpperCase(); diff --git a/core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java b/core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java index 3189c8ce99..7c7377fc09 100644 --- a/core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java +++ b/core/src/main/java/org/springframework/security/ldap/search/FilterBasedLdapUserSearch.java @@ -155,18 +155,18 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch { searchControls.setTimeLimit(searchTimeLimit); } - /** - * Specifies the attributes that will be returned as part of the search. - *

- * null indicates that all attributes will be returned. - * An empty array indicates no attributes are returned. - * - * @param attrs An array of attribute names identifying the attributes that - * will be returned. Can be null. - */ - public void setReturningAttributes(String[] attrs) { - searchControls.setReturningAttributes(attrs); - } + /** + * Specifies the attributes that will be returned as part of the search. + *

+ * null indicates that all attributes will be returned. + * An empty array indicates no attributes are returned. + * + * @param attrs An array of attribute names identifying the attributes that + * will be returned. Can be null. + */ + public void setReturningAttributes(String[] attrs) { + searchControls.setReturningAttributes(attrs); + } public String toString() { StringBuffer sb = new StringBuffer(); diff --git a/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousProcessingFilter.java b/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousProcessingFilter.java index 9a6640dcba..8af99a42a2 100644 --- a/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousProcessingFilter.java +++ b/core/src/main/java/org/springframework/security/providers/anonymous/AnonymousProcessingFilter.java @@ -81,7 +81,7 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements return auth; } - protected void doFilterHttp(HttpServletRequest request,HttpServletResponse response, FilterChain chain) throws IOException, ServletException { + protected void doFilterHttp(HttpServletRequest request,HttpServletResponse response, FilterChain chain) throws IOException, ServletException { boolean addedToken = false; if (applyAnonymousForThisRequest(request)) { @@ -109,11 +109,11 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements SecurityContextHolder.getContext().setAuthentication(null); } } - } + } - public int getOrder() { + public int getOrder() { return FilterChainOrder.ANONYMOUS_FILTER; - } + } public String getKey() { return key; diff --git a/core/src/main/java/org/springframework/security/providers/dao/DaoAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/dao/DaoAuthenticationProvider.java index 1b51ccb15e..81ed329297 100644 --- a/core/src/main/java/org/springframework/security/providers/dao/DaoAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/dao/DaoAuthenticationProvider.java @@ -50,7 +50,7 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { - Object salt = null; + Object salt = null; if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); @@ -143,6 +143,6 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication */ public void setIncludeDetailsObject(boolean includeDetailsObject) { this.includeDetailsObject = includeDetailsObject; - } + } } diff --git a/core/src/main/java/org/springframework/security/providers/encoding/Md4.java b/core/src/main/java/org/springframework/security/providers/encoding/Md4.java index 0723433b1d..d22f88d169 100644 --- a/core/src/main/java/org/springframework/security/providers/encoding/Md4.java +++ b/core/src/main/java/org/springframework/security/providers/encoding/Md4.java @@ -20,160 +20,160 @@ package org.springframework.security.providers.encoding; * @author Alan Stewart */ class Md4 { - private static final int BLOCK_SIZE = 64; - private static final int HASH_SIZE = 16; - private final byte[] buffer = new byte[BLOCK_SIZE]; - private int bufferOffset; - private long byteCount; - private int[] state = new int[4]; - private int[] tmp = new int[16]; + private static final int BLOCK_SIZE = 64; + private static final int HASH_SIZE = 16; + private final byte[] buffer = new byte[BLOCK_SIZE]; + private int bufferOffset; + private long byteCount; + private int[] state = new int[4]; + private int[] tmp = new int[16]; - Md4() { - reset(); - } + Md4() { + reset(); + } - public void reset() { - bufferOffset = 0; - byteCount = 0; - state[0] = 0x67452301; - state[1] = 0xEFCDAB89; - state[2] = 0x98BADCFE; - state[3] = 0x10325476; - } + public void reset() { + bufferOffset = 0; + byteCount = 0; + state[0] = 0x67452301; + state[1] = 0xEFCDAB89; + state[2] = 0x98BADCFE; + state[3] = 0x10325476; + } - public byte[] digest() { - byte[] resBuf = new byte[HASH_SIZE]; - digest(resBuf, 0, HASH_SIZE); - return resBuf; - } + public byte[] digest() { + byte[] resBuf = new byte[HASH_SIZE]; + digest(resBuf, 0, HASH_SIZE); + return resBuf; + } - private void digest(byte[] buffer, int off) { - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j)); - } - } - } + private void digest(byte[] buffer, int off) { + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j)); + } + } + } - private void digest(byte[] buffer, int offset, int len) { - this.buffer[this.bufferOffset++] = (byte) 0x80; - int lenOfBitLen = 8; - int C = BLOCK_SIZE - lenOfBitLen; - if (this.bufferOffset > C) { - while (this.bufferOffset < BLOCK_SIZE) { - this.buffer[this.bufferOffset++] = (byte) 0x00; - } - update(this.buffer, 0); - this.bufferOffset = 0; - } + private void digest(byte[] buffer, int offset, int len) { + this.buffer[this.bufferOffset++] = (byte) 0x80; + int lenOfBitLen = 8; + int C = BLOCK_SIZE - lenOfBitLen; + if (this.bufferOffset > C) { + while (this.bufferOffset < BLOCK_SIZE) { + this.buffer[this.bufferOffset++] = (byte) 0x00; + } + update(this.buffer, 0); + this.bufferOffset = 0; + } - while (this.bufferOffset < C) { - this.buffer[this.bufferOffset++] = (byte) 0x00; - } + while (this.bufferOffset < C) { + this.buffer[this.bufferOffset++] = (byte) 0x00; + } - long bitCount = byteCount * 8; - for (int i = 0; i < 64; i += 8) { - this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i)); - } + long bitCount = byteCount * 8; + for (int i = 0; i < 64; i += 8) { + this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i)); + } - update(this.buffer, 0); - digest(buffer, offset); - } + update(this.buffer, 0); + digest(buffer, offset); + } - public void update(byte[] input, int offset, int length) { - byteCount += length; - int todo; - while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) { - System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo); - update(this.buffer, 0); - length -= todo; - offset += todo; - this.bufferOffset = 0; - } + public void update(byte[] input, int offset, int length) { + byteCount += length; + int todo; + while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) { + System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo); + update(this.buffer, 0); + length -= todo; + offset += todo; + this.bufferOffset = 0; + } - System.arraycopy(input, offset, this.buffer, this.bufferOffset, length); - bufferOffset += length; - } + System.arraycopy(input, offset, this.buffer, this.bufferOffset, length); + bufferOffset += length; + } - private void update(byte[] block, int offset) { - for (int i = 0; i < 16; i++) { - tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24; - } + private void update(byte[] block, int offset) { + for (int i = 0; i < 16; i++) { + tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24; + } - int A = state[0]; - int B = state[1]; - int C = state[2]; - int D = state[3]; + int A = state[0]; + int B = state[1]; + int C = state[2]; + int D = state[3]; - A = FF(A, B, C, D, tmp[0], 3); - D = FF(D, A, B, C, tmp[1], 7); - C = FF(C, D, A, B, tmp[2], 11); - B = FF(B, C, D, A, tmp[3], 19); - A = FF(A, B, C, D, tmp[4], 3); - D = FF(D, A, B, C, tmp[5], 7); - C = FF(C, D, A, B, tmp[6], 11); - B = FF(B, C, D, A, tmp[7], 19); - A = FF(A, B, C, D, tmp[8], 3); - D = FF(D, A, B, C, tmp[9], 7); - C = FF(C, D, A, B, tmp[10], 11); - B = FF(B, C, D, A, tmp[11], 19); - A = FF(A, B, C, D, tmp[12], 3); - D = FF(D, A, B, C, tmp[13], 7); - C = FF(C, D, A, B, tmp[14], 11); - B = FF(B, C, D, A, tmp[15], 19); + A = FF(A, B, C, D, tmp[0], 3); + D = FF(D, A, B, C, tmp[1], 7); + C = FF(C, D, A, B, tmp[2], 11); + B = FF(B, C, D, A, tmp[3], 19); + A = FF(A, B, C, D, tmp[4], 3); + D = FF(D, A, B, C, tmp[5], 7); + C = FF(C, D, A, B, tmp[6], 11); + B = FF(B, C, D, A, tmp[7], 19); + A = FF(A, B, C, D, tmp[8], 3); + D = FF(D, A, B, C, tmp[9], 7); + C = FF(C, D, A, B, tmp[10], 11); + B = FF(B, C, D, A, tmp[11], 19); + A = FF(A, B, C, D, tmp[12], 3); + D = FF(D, A, B, C, tmp[13], 7); + C = FF(C, D, A, B, tmp[14], 11); + B = FF(B, C, D, A, tmp[15], 19); - A = GG(A, B, C, D, tmp[0], 3); - D = GG(D, A, B, C, tmp[4], 5); - C = GG(C, D, A, B, tmp[8], 9); - B = GG(B, C, D, A, tmp[12], 13); - A = GG(A, B, C, D, tmp[1], 3); - D = GG(D, A, B, C, tmp[5], 5); - C = GG(C, D, A, B, tmp[9], 9); - B = GG(B, C, D, A, tmp[13], 13); - A = GG(A, B, C, D, tmp[2], 3); - D = GG(D, A, B, C, tmp[6], 5); - C = GG(C, D, A, B, tmp[10], 9); - B = GG(B, C, D, A, tmp[14], 13); - A = GG(A, B, C, D, tmp[3], 3); - D = GG(D, A, B, C, tmp[7], 5); - C = GG(C, D, A, B, tmp[11], 9); - B = GG(B, C, D, A, tmp[15], 13); + A = GG(A, B, C, D, tmp[0], 3); + D = GG(D, A, B, C, tmp[4], 5); + C = GG(C, D, A, B, tmp[8], 9); + B = GG(B, C, D, A, tmp[12], 13); + A = GG(A, B, C, D, tmp[1], 3); + D = GG(D, A, B, C, tmp[5], 5); + C = GG(C, D, A, B, tmp[9], 9); + B = GG(B, C, D, A, tmp[13], 13); + A = GG(A, B, C, D, tmp[2], 3); + D = GG(D, A, B, C, tmp[6], 5); + C = GG(C, D, A, B, tmp[10], 9); + B = GG(B, C, D, A, tmp[14], 13); + A = GG(A, B, C, D, tmp[3], 3); + D = GG(D, A, B, C, tmp[7], 5); + C = GG(C, D, A, B, tmp[11], 9); + B = GG(B, C, D, A, tmp[15], 13); - A = HH(A, B, C, D, tmp[0], 3); - D = HH(D, A, B, C, tmp[8], 9); - C = HH(C, D, A, B, tmp[4], 11); - B = HH(B, C, D, A, tmp[12], 15); - A = HH(A, B, C, D, tmp[2], 3); - D = HH(D, A, B, C, tmp[10], 9); - C = HH(C, D, A, B, tmp[6], 11); - B = HH(B, C, D, A, tmp[14], 15); - A = HH(A, B, C, D, tmp[1], 3); - D = HH(D, A, B, C, tmp[9], 9); - C = HH(C, D, A, B, tmp[5], 11); - B = HH(B, C, D, A, tmp[13], 15); - A = HH(A, B, C, D, tmp[3], 3); - D = HH(D, A, B, C, tmp[11], 9); - C = HH(C, D, A, B, tmp[7], 11); - B = HH(B, C, D, A, tmp[15], 15); + A = HH(A, B, C, D, tmp[0], 3); + D = HH(D, A, B, C, tmp[8], 9); + C = HH(C, D, A, B, tmp[4], 11); + B = HH(B, C, D, A, tmp[12], 15); + A = HH(A, B, C, D, tmp[2], 3); + D = HH(D, A, B, C, tmp[10], 9); + C = HH(C, D, A, B, tmp[6], 11); + B = HH(B, C, D, A, tmp[14], 15); + A = HH(A, B, C, D, tmp[1], 3); + D = HH(D, A, B, C, tmp[9], 9); + C = HH(C, D, A, B, tmp[5], 11); + B = HH(B, C, D, A, tmp[13], 15); + A = HH(A, B, C, D, tmp[3], 3); + D = HH(D, A, B, C, tmp[11], 9); + C = HH(C, D, A, B, tmp[7], 11); + B = HH(B, C, D, A, tmp[15], 15); - state[0] += A; - state[1] += B; - state[2] += C; - state[3] += D; - } + state[0] += A; + state[1] += B; + state[2] += C; + state[3] += D; + } - private int FF(int a, int b, int c, int d, int x, int s) { - int t = a + ((b & c) | (~b & d)) + x; - return t << s | t >>> (32 - s); - } + private int FF(int a, int b, int c, int d, int x, int s) { + int t = a + ((b & c) | (~b & d)) + x; + return t << s | t >>> (32 - s); + } - private int GG(int a, int b, int c, int d, int x, int s) { - int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999; - return t << s | t >>> (32 - s); - } + private int GG(int a, int b, int c, int d, int x, int s) { + int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999; + return t << s | t >>> (32 - s); + } - private int HH(int a, int b, int c, int d, int x, int s) { - int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1; - return t << s | t >>> (32 - s); - } + private int HH(int a, int b, int c, int d, int x, int s) { + int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1; + return t << s | t >>> (32 - s); + } } diff --git a/core/src/main/java/org/springframework/security/providers/encoding/Md4PasswordEncoder.java b/core/src/main/java/org/springframework/security/providers/encoding/Md4PasswordEncoder.java index 730e7b9540..16f4acd049 100644 --- a/core/src/main/java/org/springframework/security/providers/encoding/Md4PasswordEncoder.java +++ b/core/src/main/java/org/springframework/security/providers/encoding/Md4PasswordEncoder.java @@ -36,52 +36,52 @@ public class Md4PasswordEncoder extends BaseDigestPasswordEncoder { //~ Methods ======================================================================================================== /** - * Encodes the rawPass using an MD4 message digest. If a salt is specified it will be merged with the password + * Encodes the rawPass using an MD4 message digest. If a salt is specified it will be merged with the password * before encoding. - * - * @param rawPass The plain text password - * @param salt The salt to sprinkle - * @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled. - */ - public String encodePassword(String rawPass, Object salt) { - String saltedPass = mergePasswordAndSalt(rawPass, salt, false); - - byte[] passBytes; + * + * @param rawPass The plain text password + * @param salt The salt to sprinkle + * @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled. + */ + public String encodePassword(String rawPass, Object salt) { + String saltedPass = mergePasswordAndSalt(rawPass, salt, false); + + byte[] passBytes; - try { - passBytes = saltedPass.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 not supported!"); - } - - Md4 md4 = new Md4(); - md4.update(passBytes, 0, passBytes.length); - - byte[] resBuf = md4.digest(); + try { + passBytes = saltedPass.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8 not supported!"); + } + + Md4 md4 = new Md4(); + md4.update(passBytes, 0, passBytes.length); + + byte[] resBuf = md4.digest(); - if (getEncodeHashAsBase64()) { - return new String(Base64.encodeBase64(resBuf)); - } else { - return new String(Hex.encodeHex(resBuf)); - } - } + if (getEncodeHashAsBase64()) { + return new String(Base64.encodeBase64(resBuf)); + } else { + return new String(Hex.encodeHex(resBuf)); + } + } - /** - * Takes a previously encoded password and compares it with a raw password after mixing in the salt and + /** + * Takes a previously encoded password and compares it with a raw password after mixing in the salt and * encoding that value. - * - * @param encPass previously encoded password - * @param rawPass plain text password - * @param salt salt to mix into password - * @return true or false - */ - public boolean isPasswordValid(String encPass, String rawPass, Object salt) { - String pass1 = "" + encPass; - String pass2 = encodePassword(rawPass, salt); - return pass1.equals(pass2); - } + * + * @param encPass previously encoded password + * @param rawPass plain text password + * @param salt salt to mix into password + * @return true or false + */ + public boolean isPasswordValid(String encPass, String rawPass, Object salt) { + String pass1 = "" + encPass; + String pass2 = encodePassword(rawPass, salt); + return pass1.equals(pass2); + } - public String getAlgorithm() { - return "MD4"; - } + public String getAlgorithm() { + return "MD4"; + } } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/security/providers/encoding/MessageDigestPasswordEncoder.java b/core/src/main/java/org/springframework/security/providers/encoding/MessageDigestPasswordEncoder.java index 892b2f8ded..1ce21cb6ce 100644 --- a/core/src/main/java/org/springframework/security/providers/encoding/MessageDigestPasswordEncoder.java +++ b/core/src/main/java/org/springframework/security/providers/encoding/MessageDigestPasswordEncoder.java @@ -74,12 +74,12 @@ public class MessageDigestPasswordEncoder extends BaseDigestPasswordEncoder { MessageDigest messageDigest = getMessageDigest(); byte[] digest; - + try { - digest = messageDigest.digest(saltedPass.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("UTF-8 not supported!"); - } + digest = messageDigest.digest(saltedPass.getBytes("UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8 not supported!"); + } if (getEncodeHashAsBase64()) { return new String(Base64.encodeBase64(digest)); diff --git a/core/src/main/java/org/springframework/security/providers/jaas/AuthorityGranter.java b/core/src/main/java/org/springframework/security/providers/jaas/AuthorityGranter.java index a16cf7350e..c597bebcc8 100644 --- a/core/src/main/java/org/springframework/security/providers/jaas/AuthorityGranter.java +++ b/core/src/main/java/org/springframework/security/providers/jaas/AuthorityGranter.java @@ -21,14 +21,11 @@ import java.util.Set; /** - * The AuthorityGranter interface is used to map a given principal to role - * names. - * - *

+ * The AuthorityGranter interface is used to map a given principal to role names. + *

* If a Windows NT login module were to be used from JAAS, an AuthrityGranter * implementation could be created to map a NT Group Principal to a ROLE_USER - * role for instance.
- *

+ * role for instance. * * @author Ray Krueger * @version $Id$ @@ -40,13 +37,14 @@ public interface AuthorityGranter { * The grant method is called for each principal returned from the LoginContext subject. If the * AuthorityGranter wishes to grant any authorities, it should return a java.util.Set containing the role names it * wishes to grant, such as ROLE_USER. If the AuthrityGranter does not wish to grant any authorities it should - * return null.
+ * return null. + *

* The set may contain any object as all objects in the returned set will be passed to the JaasGrantedAuthority * constructor using toString(). * * @param principal One of the principals from the LoginContext.getSubect().getPrincipals() method. * - * @return A java.util.Set of role names to grant, or null meaning no roles should be granted for the principal. + * @return the role names to grant, or null, meaning no roles should be granted to the principal. */ - Set grant(Principal principal); + Set grant(Principal principal); } diff --git a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java index 7396e2261a..a62c1d2085 100644 --- a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationProvider.java @@ -15,40 +15,11 @@ package org.springframework.security.providers.jaas; -import org.springframework.security.SpringSecurityException; -import org.springframework.security.Authentication; -import org.springframework.security.AuthenticationException; -import org.springframework.security.GrantedAuthority; - -import org.springframework.security.context.HttpSessionContextIntegrationFilter; -import org.springframework.security.context.SecurityContext; - -import org.springframework.security.providers.AuthenticationProvider; -import org.springframework.security.providers.UsernamePasswordAuthenticationToken; -import org.springframework.security.providers.jaas.event.JaasAuthenticationFailedEvent; -import org.springframework.security.providers.jaas.event.JaasAuthenticationSuccessEvent; - -import org.springframework.security.ui.session.HttpSessionDestroyedEvent; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.factory.InitializingBean; - -import org.springframework.context.*; - -import org.springframework.core.io.Resource; - -import org.springframework.util.Assert; - import java.io.IOException; - import java.security.Principal; import java.security.Security; - -import java.util.Arrays; +import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import javax.security.auth.callback.Callback; @@ -58,6 +29,27 @@ import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.ApplicationEventPublisherAware; +import org.springframework.context.ApplicationListener; +import org.springframework.core.io.Resource; +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationException; +import org.springframework.security.GrantedAuthority; +import org.springframework.security.SpringSecurityException; +import org.springframework.security.context.HttpSessionSecurityContextRepository; +import org.springframework.security.context.SecurityContext; +import org.springframework.security.providers.AuthenticationProvider; +import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.providers.jaas.event.JaasAuthenticationFailedEvent; +import org.springframework.security.providers.jaas.event.JaasAuthenticationSuccessEvent; +import org.springframework.security.ui.session.HttpSessionDestroyedEvent; +import org.springframework.util.Assert; + /** * An {@link AuthenticationProvider} implementation that retrieves user details from a JAAS login configuration. @@ -177,64 +169,61 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli * only throws a AuthenticationServiceException, with the message of the LoginException that will be * thrown, should the loginContext.login() method fail. */ - public Authentication authenticate(Authentication auth) - throws AuthenticationException { - if (auth instanceof UsernamePasswordAuthenticationToken) { - UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth; + public Authentication authenticate(Authentication auth) throws AuthenticationException { + if (!(auth instanceof UsernamePasswordAuthenticationToken)) { + return null; + } - try { - //Create the LoginContext object, and pass our InternallCallbackHandler - LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth)); + UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth; + Set authorities; - //Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point. - loginContext.login(); + try { + // Create the LoginContext object, and pass our InternallCallbackHandler + LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth)); - //create a set to hold the authorities, and add any that have already been applied. - Set authorities = new HashSet(); + // Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point. + loginContext.login(); - if (request.getAuthorities() != null) { - authorities.addAll(request.getAuthorities()); - } + // Create a set to hold the authorities, and add any that have already been applied. + authorities = new HashSet(); - //get the subject principals and pass them to each of the AuthorityGranters - Set principals = loginContext.getSubject().getPrincipals(); + if (request.getAuthorities() != null) { + authorities.addAll(request.getAuthorities()); + } - for (Iterator iterator = principals.iterator(); iterator.hasNext();) { - Principal principal = (Principal) iterator.next(); + // Get the subject principals and pass them to each of the AuthorityGranters + Set principals = loginContext.getSubject().getPrincipals(); - for (int i = 0; i < authorityGranters.length; i++) { - AuthorityGranter granter = authorityGranters[i]; - Set roles = granter.grant(principal); + for (Principal principal : principals) { + for (int i = 0; i < authorityGranters.length; i++) { + AuthorityGranter granter = authorityGranters[i]; + Set roles = granter.grant(principal); - //If the granter doesn't wish to grant any authorities, it should return null. - if ((roles != null) && !roles.isEmpty()) { - for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();) { - String role = roleIterator.next().toString(); - authorities.add(new JaasGrantedAuthority(role, principal)); - } + // If the granter doesn't wish to grant any authorities, it should return null. + if ((roles != null) && !roles.isEmpty()) { + for (String role : roles) { + authorities.add(new JaasGrantedAuthority(role, principal)); } } } - - //Convert the authorities set back to an array and apply it to the token. - JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), - request.getCredentials(), - (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[0]), loginContext); - - //Publish the success event - publishSuccessEvent(result); - - //we're done, return the token. - return result; - } catch (LoginException loginException) { - SpringSecurityException ase = loginExceptionResolver.resolveException(loginException); - - publishFailureEvent(request, ase); - throw ase; } - } - return null; + //Convert the authorities set back to an array and apply it to the token. + JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(), + request.getCredentials(), new ArrayList(authorities), loginContext); + + //Publish the success event + publishSuccessEvent(result); + + //we're done, return the token. + return result; + + } catch (LoginException loginException) { + SpringSecurityException ase = loginExceptionResolver.resolveException(loginException); + + publishFailureEvent(request, ase); + throw ase; + } } /** @@ -318,13 +307,13 @@ public class JaasAuthenticationProvider implements AuthenticationProvider, Appli /** * Handles the logout by getting the SecurityContext for the session that was destroyed. MUST NOT use - * SecurityContextHolder we are logging out a session that is not related to the current user. + * SecurityContextHolder as we are logging out a session that is not related to the current user. * * @param event */ protected void handleLogout(HttpSessionDestroyedEvent event) { SecurityContext context = (SecurityContext) - event.getSession().getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY); + event.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); if (context == null) { log.debug("The destroyed session has no SecurityContext"); diff --git a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationToken.java b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationToken.java index 523e96a13d..65b16a8936 100644 --- a/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationToken.java +++ b/core/src/main/java/org/springframework/security/providers/jaas/JaasAuthenticationToken.java @@ -15,6 +15,8 @@ package org.springframework.security.providers.jaas; +import java.util.List; + import org.springframework.security.GrantedAuthority; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; @@ -40,8 +42,8 @@ public class JaasAuthenticationToken extends UsernamePasswordAuthenticationToken this.loginContext = loginContext; } - public JaasAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities, - LoginContext loginContext) { + public JaasAuthenticationToken(Object principal, Object credentials, List authorities, + LoginContext loginContext) { super(principal, credentials, authorities); this.loginContext = loginContext; } diff --git a/core/src/main/java/org/springframework/security/providers/jaas/SecurityContextLoginModule.java b/core/src/main/java/org/springframework/security/providers/jaas/SecurityContextLoginModule.java index 9a4c040e30..c5d2ad7720 100644 --- a/core/src/main/java/org/springframework/security/providers/jaas/SecurityContextLoginModule.java +++ b/core/src/main/java/org/springframework/security/providers/jaas/SecurityContextLoginModule.java @@ -32,16 +32,18 @@ import javax.security.auth.spi.LoginModule; /** * An implementation of {@link LoginModule} that uses a Spring Security {@link - * org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.

This LoginModule - * provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not really be used in - * conjunction with it.

- *

The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.

- *

The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security. + * org.springframework.security.context.SecurityContext SecurityContext} to provide authentication. + *

+ * This LoginModule provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not + * really be used in conjunction with it. + *

+ * The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas. + *

+ * The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security. * If there is no Authentication in the {@link SecurityContextHolder} the login() method will throw a LoginException - * by default. - * This functionality can be changed with the ignoreMissingAuthentication option by setting it to "true". - * Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false and be - * ignored if the authentication is null.

+ * by default. This functionality can be changed with the ignoreMissingAuthentication option by setting it + * to "true". Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false + * and be ignored if the authentication is null. * * @author Brian Moseley * @author Ray Krueger @@ -107,11 +109,12 @@ public class SecurityContextLoginModule implements LoginModule { * LoginContext likely won't provide one that understands Spring Security. Also ignores the * sharedState and options parameters, since none are recognized. * - * @param subject the Subject to be authenticated.

+ * @param subject the Subject to be authenticated. * @param callbackHandler is ignored * @param sharedState is ignored * @param options are ignored */ + @SuppressWarnings("unchecked") public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { this.subject = subject; diff --git a/core/src/main/java/org/springframework/security/providers/ldap/authenticator/PasswordComparisonAuthenticator.java b/core/src/main/java/org/springframework/security/providers/ldap/authenticator/PasswordComparisonAuthenticator.java index 3a68a9aca7..3687fa0f51 100644 --- a/core/src/main/java/org/springframework/security/providers/ldap/authenticator/PasswordComparisonAuthenticator.java +++ b/core/src/main/java/org/springframework/security/providers/ldap/authenticator/PasswordComparisonAuthenticator.java @@ -15,6 +15,11 @@ package org.springframework.security.providers.ldap.authenticator; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.support.BaseLdapPathContextSource; import org.springframework.security.Authentication; import org.springframework.security.BadCredentialsException; import org.springframework.security.ldap.LdapUtils; @@ -22,16 +27,8 @@ import org.springframework.security.ldap.SpringSecurityLdapTemplate; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.providers.encoding.PasswordEncoder; import org.springframework.security.userdetails.UsernameNotFoundException; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.support.BaseLdapPathContextSource; import org.springframework.util.Assert; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Iterator; - /** * An {@link org.springframework.security.providers.ldap.LdapAuthenticator LdapAuthenticator} which compares the login @@ -71,17 +68,16 @@ public final class PasswordComparisonAuthenticator extends AbstractLdapAuthentic String username = authentication.getName(); String password = (String)authentication.getCredentials(); - Iterator dns = getUserDns(username).iterator(); - SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource()); - while (dns.hasNext() && user == null) { - final String userDn = (String) dns.next(); - + for (String userDn : getUserDns(username)) { try { user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); } catch (NameNotFoundException ignore) { } + if (user != null) { + break; + } } if (user == null && getUserSearch() != null) { diff --git a/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java index 37e61e430a..f39bc9f6b2 100644 --- a/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProvider.java @@ -1,21 +1,17 @@ package org.springframework.security.providers.preauth; -import java.util.Arrays; - -import org.springframework.security.providers.AuthenticationProvider; -import org.springframework.security.Authentication; -import org.springframework.security.AuthenticationException; -import org.springframework.security.BadCredentialsException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.userdetails.AuthenticationUserDetailsService; -import org.springframework.security.userdetails.UserDetails; -import org.springframework.security.userdetails.UserDetailsChecker; -import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.Ordered; +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationException; +import org.springframework.security.BadCredentialsException; +import org.springframework.security.providers.AuthenticationProvider; +import org.springframework.security.userdetails.AuthenticationUserDetailsService; +import org.springframework.security.userdetails.UserDetails; +import org.springframework.security.userdetails.UserDetailsChecker; +import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker; import org.springframework.util.Assert; /** @@ -87,8 +83,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro userDetailsChecker.check(ud); PreAuthenticatedAuthenticationToken result = - new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), - ud.getAuthorities().toArray(new GrantedAuthority[0])); + new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities()); result.setDetails(authentication.getDetails()); return result; diff --git a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationManager.java b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationManager.java index 221caf5d7c..4f999ee4fc 100644 --- a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationManager.java +++ b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationManager.java @@ -29,11 +29,12 @@ public interface RemoteAuthenticationManager { /** * Attempts to authenticate the remote client using the presented username and password. If authentication - * is successful, an array of GrantedAuthority[] objects will be returned.

In order to - * maximise remoting protocol compatibility, a design decision was taken to operate with minimal arguments and - * return only the minimal amount of information required for remote clients to enable/disable relevant user - * interface commands etc. There is nothing preventing users from implementing their own equivalent package that - * works with more complex object types.

+ * is successful, an array of GrantedAuthority[] objects will be returned. + *

+ * In order to maximise remoting protocol compatibility, a design decision was taken to operate with minimal + * arguments and return only the minimal amount of information required for remote clients to enable/disable + * relevant user interface commands etc. There is nothing preventing users from implementing their own equivalent + * package that works with more complex object types. * * @param username the username the remote client wishes to authenticate with. * @param password the password the remote client wishes to authenticate with. diff --git a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java index 6b1c83239b..c9821b4608 100644 --- a/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/rcp/RemoteAuthenticationProvider.java @@ -15,6 +15,8 @@ package org.springframework.security.providers.rcp; +import java.util.Arrays; + import org.springframework.security.Authentication; import org.springframework.security.AuthenticationException; import org.springframework.security.GrantedAuthority; @@ -28,11 +30,13 @@ import org.springframework.util.Assert; /** - * Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request.

A - * new Authentication object is created by this class comprising the request Authentication + * Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request. + *

+ * A new Authentication object is created by this class comprising the request Authentication * object's principal, credentials and the GrantedAuthority[]s returned by the - * RemoteAuthenticationManager.

- *

The RemoteAuthenticationManager should not require any special username or password setting on + * RemoteAuthenticationManager. + *

+ * The RemoteAuthenticationManager should not require any special username or password setting on * the remoting client proxy factory to execute the call. Instead the entire authentication request must be * encapsulated solely within the Authentication request object. In practical terms this means the * RemoteAuthenticationManager will not be protected by BASIC or any other HTTP-level @@ -50,7 +54,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { Assert.notNull(this.remoteAuthenticationManager, "remoteAuthenticationManager is mandatory"); } @@ -60,7 +64,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini String password = authentication.getCredentials().toString(); GrantedAuthority[] authorities = remoteAuthenticationManager.attemptAuthentication(username, password); - return new UsernamePasswordAuthenticationToken(username, password, authorities); + return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList(authorities)); } public RemoteAuthenticationManager getRemoteAuthenticationManager() { diff --git a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java index cc7295f85e..f9d2492ba4 100644 --- a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProvider.java @@ -15,36 +15,25 @@ package org.springframework.security.providers.rememberme; -import org.springframework.security.SpringSecurityMessageSource; -import org.springframework.security.Authentication; -import org.springframework.security.AuthenticationException; -import org.springframework.security.BadCredentialsException; - -import org.springframework.security.providers.AuthenticationProvider; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.springframework.beans.factory.InitializingBean; - import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; - +import org.springframework.security.Authentication; +import org.springframework.security.AuthenticationException; +import org.springframework.security.BadCredentialsException; +import org.springframework.security.SpringSecurityMessageSource; +import org.springframework.security.providers.AuthenticationProvider; import org.springframework.util.Assert; /** - * An {@link AuthenticationProvider} implementation that validates {@link - * org.springframework.security.providers.rememberme.RememberMeAuthenticationToken}s.

To be successfully validated, the - * {@link org.springframework.security.providers.rememberme.RememberMeAuthenticationToken#getKeyHash()} must match this class' - * {@link #getKey()}.

+ * An {@link AuthenticationProvider} implementation that validates {@link RememberMeAuthenticationToken}s. + *

+ * To be successfully validated, the {@link RememberMeAuthenticationToken#getKeyHash()} must match this class' + * {@link #getKey()}. */ public class RememberMeAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware { - //~ Static fields/initializers ===================================================================================== - - private static final Log logger = LogFactory.getLog(RememberMeAuthenticationProvider.class); - //~ Instance fields ================================================================================================ protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); @@ -52,13 +41,12 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider, //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { Assert.hasLength(key); Assert.notNull(this.messages, "A message source must be set"); } - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { + public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!supports(authentication.getClass())) { return null; } diff --git a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationToken.java b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationToken.java index dad8b91b00..a07c455f16 100644 --- a/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationToken.java +++ b/core/src/main/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationToken.java @@ -39,6 +39,9 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i //~ Constructors =================================================================================================== + /** + * @deprecated + */ public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) { this(key, principal, Arrays.asList(authorities)); } diff --git a/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java b/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java index 25e233361e..37161efc5b 100644 --- a/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java +++ b/core/src/main/java/org/springframework/security/runas/RunAsImplAuthenticationProvider.java @@ -46,7 +46,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { Assert.notNull(key, "A Key is required and should match that configured for the RunAsManagerImpl"); } diff --git a/core/src/main/java/org/springframework/security/securechannel/ChannelDecisionManagerImpl.java b/core/src/main/java/org/springframework/security/securechannel/ChannelDecisionManagerImpl.java index 99345ffe60..c4f2153cd5 100644 --- a/core/src/main/java/org/springframework/security/securechannel/ChannelDecisionManagerImpl.java +++ b/core/src/main/java/org/springframework/security/securechannel/ChannelDecisionManagerImpl.java @@ -24,6 +24,7 @@ import org.springframework.util.Assert; import java.io.IOException; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -52,35 +53,26 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi //~ Instance fields ================================================================================================ - private List channelProcessors; + private List channelProcessors; //~ Methods ======================================================================================================== public void afterPropertiesSet() throws Exception { - checkIfValidList(this.channelProcessors); + Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required"); } - private void checkIfValidList(List listToCheck) { - Assert.notEmpty(listToCheck, "A list of ChannelProcessors is required"); - } + public void decide(FilterInvocation invocation, List config) throws IOException, ServletException { - public void decide(FilterInvocation invocation, List config) - throws IOException, ServletException { - - Iterator attrs = config.iterator(); + Iterator attrs = config.iterator(); while (attrs.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) attrs.next(); + ConfigAttribute attribute = attrs.next(); if (ANY_CHANNEL.equals(attribute.getAttribute())) { return; } } - Iterator iter = this.channelProcessors.iterator(); - - while (iter.hasNext()) { - ChannelProcessor processor = (ChannelProcessor) iter.next(); - + for (ChannelProcessor processor : channelProcessors) { processor.decide(invocation, config); if (invocation.getResponse().isCommitted()) { @@ -89,22 +81,20 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi } } - protected List getChannelProcessors() { + protected List getChannelProcessors() { return this.channelProcessors; } - public void setChannelProcessors(List newList) { - checkIfValidList(newList); + @SuppressWarnings("cast") + public void setChannelProcessors(List newList) { + Assert.notEmpty(newList, "A list of ChannelProcessors is required"); + channelProcessors = new ArrayList(newList.size()); - Iterator iter = newList.iterator(); - - while (iter.hasNext()) { - Object currentObject = iter.next(); + for (Object currentObject : newList) { Assert.isInstanceOf(ChannelProcessor.class, currentObject, "ChannelProcessor " + currentObject.getClass().getName() + " must implement ChannelProcessor"); + channelProcessors.add((ChannelProcessor)currentObject); } - - this.channelProcessors = newList; } public boolean supports(ConfigAttribute attribute) { @@ -112,11 +102,7 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi return true; } - Iterator iter = this.channelProcessors.iterator(); - - while (iter.hasNext()) { - ChannelProcessor processor = (ChannelProcessor) iter.next(); - + for (ChannelProcessor processor : channelProcessors) { if (processor.supports(attribute)) { return true; } diff --git a/core/src/main/java/org/springframework/security/securechannel/ChannelProcessor.java b/core/src/main/java/org/springframework/security/securechannel/ChannelProcessor.java index 6fdcb81f1c..808786682e 100644 --- a/core/src/main/java/org/springframework/security/securechannel/ChannelProcessor.java +++ b/core/src/main/java/org/springframework/security/securechannel/ChannelProcessor.java @@ -26,17 +26,12 @@ import javax.servlet.ServletException; /** * Decides whether a web channel meets a specific security condition. - * - *

- * ChannelProcessor implementations are iterated by the {@link - * ChannelDecisionManagerImpl}. - *

- * - *

+ *

+ * ChannelProcessor implementations are iterated by the {@link ChannelDecisionManagerImpl}. + *

* If an implementation has an issue with the channel security, they should * take action themselves. The callers of the implementation do not take any * action. - *

* * @author Ben Alex * @version $Id$ @@ -49,16 +44,16 @@ public interface ChannelProcessor { * security based on the requested list of ConfigAttributes. * */ - void decide(FilterInvocation invocation, List config) - throws IOException, ServletException; + void decide(FilterInvocation invocation, List config) throws IOException, ServletException; /** * Indicates whether this ChannelProcessor is able to process the passed - * ConfigAttribute.

This allows the ChannelProcessingFilter to check every - * configuration attribute can be consumed by the configured ChannelDecisionManager.

+ * ConfigAttribute. + *

+ * This allows the ChannelProcessingFilter to check every configuration attribute can be consumed + * by the configured ChannelDecisionManager. * - * @param attribute a configuration attribute that has been configured against the - * ChannelProcessingFilter + * @param attribute a configuration attribute that has been configured against the ChannelProcessingFilter. * * @return true if this ChannelProcessor can support the passed configuration attribute */ diff --git a/core/src/main/java/org/springframework/security/securechannel/InsecureChannelProcessor.java b/core/src/main/java/org/springframework/security/securechannel/InsecureChannelProcessor.java index f7cbdb01ea..bf93170c36 100644 --- a/core/src/main/java/org/springframework/security/securechannel/InsecureChannelProcessor.java +++ b/core/src/main/java/org/springframework/security/securechannel/InsecureChannelProcessor.java @@ -15,29 +15,26 @@ package org.springframework.security.securechannel; -import org.springframework.security.ConfigAttribute; - -import org.springframework.security.intercept.web.FilterInvocation; - -import org.springframework.beans.factory.InitializingBean; - -import org.springframework.util.Assert; - import java.io.IOException; - -import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.security.ConfigAttribute; +import org.springframework.security.intercept.web.FilterInvocation; +import org.springframework.util.Assert; + /** - *

Ensures channel security is inactive by review of HttpServletRequest.isSecure() responses.

- *

The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected, + * Ensures channel security is inactive by review of HttpServletRequest.isSecure() responses. + *

+ * The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected, * HttpServletRequest.isSecure() is used to determine the channel security offered. If channel security * is present, the configured ChannelEntryPoint is called. By default the entry point is {@link - * RetryWithHttpEntryPoint}.

- *

The default insecureKeyword is REQUIRES_INSECURE_CHANNEL.

+ * RetryWithHttpEntryPoint}. + *

+ * The default insecureKeyword is REQUIRES_INSECURE_CHANNEL. * * @author Ben Alex * @version $Id$ @@ -55,17 +52,12 @@ public class InsecureChannelProcessor implements InitializingBean, ChannelProces Assert.notNull(entryPoint, "entryPoint required"); } - public void decide(FilterInvocation invocation, List config) - throws IOException, ServletException { + public void decide(FilterInvocation invocation, List config) throws IOException, ServletException { if ((invocation == null) || (config == null)) { throw new IllegalArgumentException("Nulls cannot be provided"); } - Iterator iter = config.iterator(); - - while (iter.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) iter.next(); - + for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (invocation.getHttpRequest().isSecure()) { entryPoint.commence(invocation.getRequest(), invocation.getResponse()); diff --git a/core/src/main/java/org/springframework/security/securechannel/SecureChannelProcessor.java b/core/src/main/java/org/springframework/security/securechannel/SecureChannelProcessor.java index 2d538d3641..19b58dc600 100644 --- a/core/src/main/java/org/springframework/security/securechannel/SecureChannelProcessor.java +++ b/core/src/main/java/org/springframework/security/securechannel/SecureChannelProcessor.java @@ -15,29 +15,26 @@ package org.springframework.security.securechannel; -import org.springframework.security.ConfigAttribute; - -import org.springframework.security.intercept.web.FilterInvocation; - -import org.springframework.beans.factory.InitializingBean; - -import org.springframework.util.Assert; - import java.io.IOException; - -import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.security.ConfigAttribute; +import org.springframework.security.intercept.web.FilterInvocation; +import org.springframework.util.Assert; + /** - *

Ensures channel security is active by review of HttpServletRequest.isSecure() responses.

- *

The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected, + * Ensures channel security is active by review of HttpServletRequest.isSecure() responses. + *

+ * The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected, * HttpServletRequest.isSecure() is used to determine the channel security offered. If channel security * is not present, the configured ChannelEntryPoint is called. By default the entry point is {@link - * RetryWithHttpsEntryPoint}.

- *

The default secureKeyword is REQUIRES_SECURE_CHANNEL.

+ * RetryWithHttpsEntryPoint}. + *

+ * The default secureKeyword is REQUIRES_SECURE_CHANNEL. * * @author Ben Alex * @version $Id$ @@ -55,15 +52,10 @@ public class SecureChannelProcessor implements InitializingBean, ChannelProcesso Assert.notNull(entryPoint, "entryPoint required"); } - public void decide(FilterInvocation invocation, List config) - throws IOException, ServletException { + public void decide(FilterInvocation invocation, List config) throws IOException, ServletException { Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided"); - Iterator iter = config.iterator(); - - while (iter.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) iter.next(); - + for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (!invocation.getHttpRequest().isSecure()) { entryPoint.commence(invocation.getRequest(), invocation.getResponse()); diff --git a/core/src/main/java/org/springframework/security/token/DefaultToken.java b/core/src/main/java/org/springframework/security/token/DefaultToken.java index b6ecf96672..80bd53424a 100644 --- a/core/src/main/java/org/springframework/security/token/DefaultToken.java +++ b/core/src/main/java/org/springframework/security/token/DefaultToken.java @@ -11,49 +11,49 @@ import org.springframework.util.Assert; * @since 2.0.1 */ public class DefaultToken implements Token { - private String key; - private long keyCreationTime; - private String extendedInformation; - - public DefaultToken(String key, long keyCreationTime, String extendedInformation) { - Assert.hasText(key, "Key required"); - Assert.notNull(extendedInformation, "Extended information cannot be null"); - this.key = key; - this.keyCreationTime = keyCreationTime; - this.extendedInformation = extendedInformation; - } + private String key; + private long keyCreationTime; + private String extendedInformation; + + public DefaultToken(String key, long keyCreationTime, String extendedInformation) { + Assert.hasText(key, "Key required"); + Assert.notNull(extendedInformation, "Extended information cannot be null"); + this.key = key; + this.keyCreationTime = keyCreationTime; + this.extendedInformation = extendedInformation; + } - public String getKey() { - return key; - } - - public long getKeyCreationTime() { - return keyCreationTime; - } + public String getKey() { + return key; + } + + public long getKeyCreationTime() { + return keyCreationTime; + } - public String getExtendedInformation() { - return extendedInformation; - } + public String getExtendedInformation() { + return extendedInformation; + } - public boolean equals(Object obj) { - if (obj != null && obj instanceof DefaultToken) { - DefaultToken rhs = (DefaultToken) obj; - return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation); - } - return false; - } + public boolean equals(Object obj) { + if (obj != null && obj instanceof DefaultToken) { + DefaultToken rhs = (DefaultToken) obj; + return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation); + } + return false; + } - public int hashCode() { + public int hashCode() { int code = 979; code = code * key.hashCode(); code = code * new Long(keyCreationTime).hashCode(); code = code * extendedInformation.hashCode(); return code; - } + } - public String toString() { - return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]"; - } - - + public String toString() { + return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]"; + } + + } diff --git a/core/src/main/java/org/springframework/security/token/KeyBasedPersistenceTokenService.java b/core/src/main/java/org/springframework/security/token/KeyBasedPersistenceTokenService.java index 07bff76589..b7c997446a 100644 --- a/core/src/main/java/org/springframework/security/token/KeyBasedPersistenceTokenService.java +++ b/core/src/main/java/org/springframework/security/token/KeyBasedPersistenceTokenService.java @@ -54,117 +54,117 @@ import org.springframework.util.StringUtils; * */ public class KeyBasedPersistenceTokenService implements TokenService, InitializingBean { - private int pseudoRandomNumberBits = 256; - private String serverSecret; - private Integer serverInteger; - private SecureRandom secureRandom; - - public Token allocateToken(String extendedInformation) { - Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)"); - long creationTime = new Date().getTime(); - String serverSecret = computeServerSecretApplicableAt(creationTime); - String pseudoRandomNumber = generatePseudoRandomNumber(); - String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation; + private int pseudoRandomNumberBits = 256; + private String serverSecret; + private Integer serverInteger; + private SecureRandom secureRandom; + + public Token allocateToken(String extendedInformation) { + Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)"); + long creationTime = new Date().getTime(); + String serverSecret = computeServerSecretApplicableAt(creationTime); + String pseudoRandomNumber = generatePseudoRandomNumber(); + String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation; - // Compute key - String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); - String keyPayload = content + ":" + sha512Hex; - String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload))); - - return new DefaultToken(key, creationTime, extendedInformation); - } + // Compute key + String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); + String keyPayload = content + ":" + sha512Hex; + String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload))); + + return new DefaultToken(key, creationTime, extendedInformation); + } - public Token verifyToken(String key) { - if (key == null || "".equals(key)) { - return null; - } - String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":"); - Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length); - - long creationTime; - try { - creationTime = Long.decode(tokens[0]).longValue(); - } catch (NumberFormatException nfe) { - throw new IllegalArgumentException("Expected number but found " + tokens[0]); - } - - String serverSecret = computeServerSecretApplicableAt(creationTime); - String pseudoRandomNumber = tokens[1]; - - // Permit extendedInfo to itself contain ":" characters - StringBuffer extendedInfo = new StringBuffer(); - for (int i = 2; i < tokens.length-1; i++) { - if (i > 2) { - extendedInfo.append(":"); - } - extendedInfo.append(tokens[i]); - } - - String sha1Hex = tokens[tokens.length-1]; - - // Verification - String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString(); - String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); - Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure"); - - return new DefaultToken(key, creationTime, extendedInfo.toString()); - } - - private byte[] convertToBytes(String input) { - try { - return input.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - private String convertToString(byte[] bytes) { - try { - return new String(bytes, "UTF-8"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * @return a pseduo random number (hex encoded) - */ - private String generatePseudoRandomNumber() { - byte[] randomizedBits = new byte[pseudoRandomNumberBits]; - secureRandom.nextBytes(randomizedBits); - return new String(Hex.encodeHex(randomizedBits)); - } - - private String computeServerSecretApplicableAt(long time) { - return serverSecret + ":" + new Long(time % serverInteger.intValue()).intValue(); - } + public Token verifyToken(String key) { + if (key == null || "".equals(key)) { + return null; + } + String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":"); + Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length); + + long creationTime; + try { + creationTime = Long.decode(tokens[0]).longValue(); + } catch (NumberFormatException nfe) { + throw new IllegalArgumentException("Expected number but found " + tokens[0]); + } + + String serverSecret = computeServerSecretApplicableAt(creationTime); + String pseudoRandomNumber = tokens[1]; + + // Permit extendedInfo to itself contain ":" characters + StringBuffer extendedInfo = new StringBuffer(); + for (int i = 2; i < tokens.length-1; i++) { + if (i > 2) { + extendedInfo.append(":"); + } + extendedInfo.append(tokens[i]); + } + + String sha1Hex = tokens[tokens.length-1]; + + // Verification + String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString(); + String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret); + Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure"); + + return new DefaultToken(key, creationTime, extendedInfo.toString()); + } + + private byte[] convertToBytes(String input) { + try { + return input.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + private String convertToString(byte[] bytes) { + try { + return new String(bytes, "UTF-8"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * @return a pseduo random number (hex encoded) + */ + private String generatePseudoRandomNumber() { + byte[] randomizedBits = new byte[pseudoRandomNumberBits]; + secureRandom.nextBytes(randomizedBits); + return new String(Hex.encodeHex(randomizedBits)); + } + + private String computeServerSecretApplicableAt(long time) { + return serverSecret + ":" + new Long(time % serverInteger.intValue()).intValue(); + } - /** - * @param serverSecret the new secret, which can contain a ":" if desired (never being sent to the client) - */ - public void setServerSecret(String serverSecret) { - this.serverSecret = serverSecret; - } - - public void setSecureRandom(SecureRandom secureRandom) { - this.secureRandom = secureRandom; - } - - /** - * @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256) - */ - public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) { - Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size"); - this.pseudoRandomNumberBits = pseudoRandomNumberBits; - } + /** + * @param serverSecret the new secret, which can contain a ":" if desired (never being sent to the client) + */ + public void setServerSecret(String serverSecret) { + this.serverSecret = serverSecret; + } + + public void setSecureRandom(SecureRandom secureRandom) { + this.secureRandom = secureRandom; + } + + /** + * @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256) + */ + public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) { + Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size"); + this.pseudoRandomNumberBits = pseudoRandomNumberBits; + } - public void setServerInteger(Integer serverInteger) { - this.serverInteger = serverInteger; - } + public void setServerInteger(Integer serverInteger) { + this.serverInteger = serverInteger; + } - public void afterPropertiesSet() throws Exception { - Assert.hasText(serverSecret, "Server secret required"); - Assert.notNull(serverInteger, "Server integer required"); - Assert.notNull(secureRandom, "SecureRandom instance required"); - } + public void afterPropertiesSet() throws Exception { + Assert.hasText(serverSecret, "Server secret required"); + Assert.notNull(serverInteger, "Server integer required"); + Assert.notNull(secureRandom, "SecureRandom instance required"); + } } diff --git a/core/src/main/java/org/springframework/security/token/SecureRandomFactoryBean.java b/core/src/main/java/org/springframework/security/token/SecureRandomFactoryBean.java index a7bf036832..43428698d1 100644 --- a/core/src/main/java/org/springframework/security/token/SecureRandomFactoryBean.java +++ b/core/src/main/java/org/springframework/security/token/SecureRandomFactoryBean.java @@ -10,60 +10,59 @@ import org.springframework.util.FileCopyUtils; /** * Creates a {@link SecureRandom} instance. - * + * * @author Ben Alex * @since 2.0.1 - * + * @version $Id$ */ -public class SecureRandomFactoryBean implements FactoryBean { +public class SecureRandomFactoryBean implements FactoryBean { - private String algorithm = "SHA1PRNG"; - private Resource seed; - - public Object getObject() throws Exception { - SecureRandom rnd = SecureRandom.getInstance(algorithm); - - if (seed != null) { - // Seed specified, so use it - byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream()); - rnd.setSeed(seedBytes); - } else { - // Request the next bytes, thus eagerly incurring the expense of default seeding - rnd.nextBytes(new byte[1]); - } - - return rnd; - } + private String algorithm = "SHA1PRNG"; + private Resource seed; - public Class getObjectType() { - return SecureRandom.class; - } + public SecureRandom getObject() throws Exception { + SecureRandom rnd = SecureRandom.getInstance(algorithm); - public boolean isSingleton() { - return false; - } + if (seed != null) { + // Seed specified, so use it + byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream()); + rnd.setSeed(seedBytes); + } else { + // Request the next bytes, thus eagerly incurring the expense of default seeding + rnd.nextBytes(new byte[1]); + } - /** - * Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. Defaults to - * SHA1PRNG. - * - * @param algorithm to use (mandatory) - */ - public void setAlgorithm(String algorithm) { - Assert.hasText(algorithm, "Algorithm required"); - this.algorithm = algorithm; - } + return rnd; + } - /** - * Allows the user to specify a resource which will act as a seed for the {@link SecureRandom} - * instance. Specifically, the resource will be read into an {@link InputStream} and those - * bytes presented to the {@link SecureRandom#setSeed(byte[])} method. Note that this will - * simply supplement, rather than replace, the existing seed. As such, it is always safe to - * set a seed using this method (it never reduces randomness). - * - * @param seed to use, or null if no additional seeding is needed - */ - public void setSeed(Resource seed) { - this.seed = seed; - } + public Class getObjectType() { + return SecureRandom.class; + } + + public boolean isSingleton() { + return false; + } + + /** + * Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. Defaults to "SHA1PRNG". + * + * @param algorithm to use (mandatory) + */ + public void setAlgorithm(String algorithm) { + Assert.hasText(algorithm, "Algorithm required"); + this.algorithm = algorithm; + } + + /** + * Allows the user to specify a resource which will act as a seed for the {@link SecureRandom} + * instance. Specifically, the resource will be read into an {@link InputStream} and those + * bytes presented to the {@link SecureRandom#setSeed(byte[])} method. Note that this will + * simply supplement, rather than replace, the existing seed. As such, it is always safe to + * set a seed using this method (it never reduces randomness). + * + * @param seed to use, or null if no additional seeding is needed + */ + public void setSeed(Resource seed) { + this.seed = seed; + } } diff --git a/core/src/main/java/org/springframework/security/token/Token.java b/core/src/main/java/org/springframework/security/token/Token.java index 1b09c8960e..65f8971c8d 100644 --- a/core/src/main/java/org/springframework/security/token/Token.java +++ b/core/src/main/java/org/springframework/security/token/Token.java @@ -16,30 +16,30 @@ package org.springframework.security.token; * @since 2.0.1 */ public interface Token { - - /** - * Obtains the randomised, secure key assigned to this token. Presentation of this token to - * {@link TokenService} will always return a Token that is equal to the original - * Token issued for that key. - * - * @return a key with appropriate randomness and security. - */ - String getKey(); - - /** - * The time the token key was initially created is available from this method. Note that a given - * token must never have this creation time changed. If necessary, a new token can be - * requested from the {@link TokenService} to replace the original token. - * - * @return the time this token key was created, in the same format as specified by {@link Date#getTime()). - */ - long getKeyCreationTime(); - - /** - * Obtains the extended information associated within the token, which was presented when the token - * was first created. - * - * @return the user-specified extended information, if any - */ - String getExtendedInformation(); + + /** + * Obtains the randomised, secure key assigned to this token. Presentation of this token to + * {@link TokenService} will always return a Token that is equal to the original + * Token issued for that key. + * + * @return a key with appropriate randomness and security. + */ + String getKey(); + + /** + * The time the token key was initially created is available from this method. Note that a given + * token must never have this creation time changed. If necessary, a new token can be + * requested from the {@link TokenService} to replace the original token. + * + * @return the time this token key was created, in the same format as specified by {@link Date#getTime()). + */ + long getKeyCreationTime(); + + /** + * Obtains the extended information associated within the token, which was presented when the token + * was first created. + * + * @return the user-specified extended information, if any + */ + String getExtendedInformation(); } diff --git a/core/src/main/java/org/springframework/security/token/TokenService.java b/core/src/main/java/org/springframework/security/token/TokenService.java index f193b5b7b8..660a16360a 100644 --- a/core/src/main/java/org/springframework/security/token/TokenService.java +++ b/core/src/main/java/org/springframework/security/token/TokenService.java @@ -26,21 +26,21 @@ package org.springframework.security.token; * */ public interface TokenService { - /** - * Forces the allocation of a new {@link Token}. - * - * @param the extended information desired in the token (cannot be null, but can be empty) - * @return a new token that has not been issued previously, and is guaranteed to be recognised - * by this implementation's {@link #verifyToken(String)} at any future time. - */ - Token allocateToken(String extendedInformation); - - /** - * Permits verification the <{@link Token#getKey()} was issued by this TokenService and - * reconstructs the corresponding Token. - * - * @param key as obtained from {@link Token#getKey()} and created by this implementation - * @return the token, or null if the token was not issued by this TokenService - */ - Token verifyToken(String key); + /** + * Forces the allocation of a new {@link Token}. + * + * @param the extended information desired in the token (cannot be null, but can be empty) + * @return a new token that has not been issued previously, and is guaranteed to be recognised + * by this implementation's {@link #verifyToken(String)} at any future time. + */ + Token allocateToken(String extendedInformation); + + /** + * Permits verification the <{@link Token#getKey()} was issued by this TokenService and + * reconstructs the corresponding Token. + * + * @param key as obtained from {@link Token#getKey()} and created by this implementation + * @return the token, or null if the token was not issued by this TokenService + */ + Token verifyToken(String key); } diff --git a/core/src/main/java/org/springframework/security/ui/SavedRequestAwareAuthenticationSuccessHandler.java b/core/src/main/java/org/springframework/security/ui/SavedRequestAwareAuthenticationSuccessHandler.java index 419b170cc5..bb5c10d567 100644 --- a/core/src/main/java/org/springframework/security/ui/SavedRequestAwareAuthenticationSuccessHandler.java +++ b/core/src/main/java/org/springframework/security/ui/SavedRequestAwareAuthenticationSuccessHandler.java @@ -1,8 +1,6 @@ package org.springframework.security.ui; import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; diff --git a/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilter.java b/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilter.java index caf5fd3bf6..64c1a52b71 100644 --- a/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilter.java +++ b/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilter.java @@ -174,7 +174,7 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi chain.doFilter(request, response); } - private boolean authenticationIsRequired(String username) { + private boolean authenticationIsRequired(String username) { // Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated // (see SEC-53) Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); @@ -198,12 +198,12 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi // both of which force re-authentication if the respective header is detected (and in doing so replace // any existing AnonymousAuthenticationToken). See SEC-610. if (existingAuth instanceof AnonymousAuthenticationToken) { - return true; + return true; } return false; } - + protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { } @@ -242,20 +242,20 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi } public void setRememberMeServices(RememberMeServices rememberMeServices) { - Assert.notNull(rememberMeServices, "rememberMeServices cannot be null"); + Assert.notNull(rememberMeServices, "rememberMeServices cannot be null"); this.rememberMeServices = rememberMeServices; } public void setCredentialsCharset(String credentialsCharset) { - Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty"); - this.credentialsCharset = credentialsCharset; - } + Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty"); + this.credentialsCharset = credentialsCharset; + } protected String getCredentialsCharset(HttpServletRequest httpRequest) { - return credentialsCharset; - } + return credentialsCharset; + } - public int getOrder() { + public int getOrder() { return FilterChainOrder.BASIC_PROCESSING_FILTER; } } diff --git a/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilterEntryPoint.java b/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilterEntryPoint.java index 9aecf7606e..3eac4cc6c3 100644 --- a/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilterEntryPoint.java +++ b/core/src/main/java/org/springframework/security/ui/basicauth/BasicProcessingFilterEntryPoint.java @@ -44,8 +44,8 @@ public class BasicProcessingFilterEntryPoint implements AuthenticationEntryPoint //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { - Assert.hasText(realmName, "realmName must be specified"); + public void afterPropertiesSet() throws Exception { + Assert.hasText(realmName, "realmName must be specified"); } public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) diff --git a/core/src/main/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPoint.java b/core/src/main/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPoint.java index 422f31b26f..87af141805 100644 --- a/core/src/main/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPoint.java +++ b/core/src/main/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPoint.java @@ -57,14 +57,14 @@ public class DigestProcessingFilterEntryPoint implements AuthenticationEntryPoin //~ Methods ======================================================================================================== public int getOrder() { - return order; - } + return order; + } - public void setOrder(int order) { - this.order = order; - } + public void setOrder(int order) { + this.order = order; + } - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { if ((realmName == null) || "".equals(realmName)) { throw new IllegalArgumentException("realmName must be specified"); } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilter.java b/core/src/main/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilter.java index 03517f1f76..00282b5440 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilter.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilter.java @@ -99,7 +99,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec unsuccessfulAuthentication(request, response, failed); if (!continueFilterChainOnUnsuccessfulAuthentication) { - throw failed; + throw failed; } } } @@ -158,7 +158,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec } public void setContinueFilterChainOnUnsuccessfulAuthentication(boolean shouldContinue) { - continueFilterChainOnUnsuccessfulAuthentication = shouldContinue; + continueFilterChainOnUnsuccessfulAuthentication = shouldContinue; } /** diff --git a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedCredentialsNotFoundException.java b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedCredentialsNotFoundException.java index a65b835378..ab8e8cb547 100644 --- a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedCredentialsNotFoundException.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedCredentialsNotFoundException.java @@ -4,8 +4,8 @@ import org.springframework.security.AuthenticationException; public class PreAuthenticatedCredentialsNotFoundException extends AuthenticationException { - public PreAuthenticatedCredentialsNotFoundException(String msg) { - super(msg); - } + public PreAuthenticatedCredentialsNotFoundException(String msg) { + super(msg); + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java index 355b62187f..24e8de4f31 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.java @@ -18,27 +18,27 @@ import org.springframework.security.MutableGrantedAuthoritiesContainer; * @since 2.0 */ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends WebAuthenticationDetails implements - MutableGrantedAuthoritiesContainer { - public static final long serialVersionUID = 1L; + MutableGrantedAuthoritiesContainer { + public static final long serialVersionUID = 1L; - private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl(); + private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl(); - public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) { - super(request); - } + public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) { + super(request); + } - public List getGrantedAuthorities() { - return authoritiesContainer.getGrantedAuthorities(); - } + public List getGrantedAuthorities() { + return authoritiesContainer.getGrantedAuthorities(); + } - public void setGrantedAuthorities(List authorities) { - this.authoritiesContainer.setGrantedAuthorities(authorities); - } - + public void setGrantedAuthorities(List authorities) { + this.authoritiesContainer.setGrantedAuthorities(authorities); + } + public String toString() { StringBuffer sb = new StringBuffer(); sb.append(super.toString() + "; "); sb.append(authoritiesContainer); return sb.toString(); - } + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPoint.java b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPoint.java index 0fa1bc430e..0ea401b524 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPoint.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPoint.java @@ -38,28 +38,28 @@ import org.springframework.core.Ordered; * @since 2.0 */ public class PreAuthenticatedProcessingFilterEntryPoint implements AuthenticationEntryPoint, Ordered { - private static final Log logger = LogFactory.getLog(PreAuthenticatedProcessingFilterEntryPoint.class); + private static final Log logger = LogFactory.getLog(PreAuthenticatedProcessingFilterEntryPoint.class); - private int order = Integer.MAX_VALUE; + private int order = Integer.MAX_VALUE; - /** - * Always returns a 403 error code to the client. - */ - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, - ServletException { - if (logger.isDebugEnabled()) { - logger.debug("Pre-authenticated entry point called. Rejecting access"); - } - HttpServletResponse httpResponse = (HttpServletResponse) response; - httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); - } + /** + * Always returns a 403 error code to the client. + */ + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, + ServletException { + if (logger.isDebugEnabled()) { + logger.debug("Pre-authenticated entry point called. Rejecting access"); + } + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); + } - public int getOrder() { - return order; - } + public int getOrder() { + return order; + } - public void setOrder(int i) { - order = i; - } + public void setOrder(int i) { + order = i; + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilter.java b/core/src/main/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilter.java index 65bd427583..20dc9073d7 100644 --- a/core/src/main/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilter.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilter.java @@ -27,50 +27,50 @@ import org.springframework.util.Assert; * @since 2.0 */ public class RequestHeaderPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { - private String principalRequestHeader = "SM_USER"; - private String credentialsRequestHeader; + private String principalRequestHeader = "SM_USER"; + private String credentialsRequestHeader; - /** - * Read and returns the header named by principalRequestHeader from the request. - * - * @throws PreAuthenticatedCredentialsNotFoundException if the header is missing - */ - protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { - String principal = request.getHeader(principalRequestHeader); - - if (principal == null) { - throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader - + " header not found in request."); - } + /** + * Read and returns the header named by principalRequestHeader from the request. + * + * @throws PreAuthenticatedCredentialsNotFoundException if the header is missing + */ + protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { + String principal = request.getHeader(principalRequestHeader); + + if (principal == null) { + throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader + + " header not found in request."); + } - return principal; - } - - /** - * Credentials aren't usually applicable, but if a credentialsRequestHeader is set, this - * will be read and used as the credentials value. Otherwise a dummy value will be used. - */ - protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { - if (credentialsRequestHeader != null) { - String credentials = request.getHeader(credentialsRequestHeader); - - return credentials; - } + return principal; + } + + /** + * Credentials aren't usually applicable, but if a credentialsRequestHeader is set, this + * will be read and used as the credentials value. Otherwise a dummy value will be used. + */ + protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { + if (credentialsRequestHeader != null) { + String credentials = request.getHeader(credentialsRequestHeader); + + return credentials; + } - return "N/A"; - } - - public void setPrincipalRequestHeader(String principalRequestHeader) { - Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null"); - this.principalRequestHeader = principalRequestHeader; - } + return "N/A"; + } + + public void setPrincipalRequestHeader(String principalRequestHeader) { + Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null"); + this.principalRequestHeader = principalRequestHeader; + } - public void setCredentialsRequestHeader(String credentialsRequestHeader) { - Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null"); - this.credentialsRequestHeader = credentialsRequestHeader; - } + public void setCredentialsRequestHeader(String credentialsRequestHeader) { + Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null"); + this.credentialsRequestHeader = credentialsRequestHeader; + } - public int getOrder() { - return FilterChainOrder.PRE_AUTH_FILTER; - } + public int getOrder() { + return FilterChainOrder.PRE_AUTH_FILTER; + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WASSecurityHelper.java b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WASSecurityHelper.java index 9b580af11d..343bda67f2 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WASSecurityHelper.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WASSecurityHelper.java @@ -15,10 +15,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * WebSphere Security helper class to allow retrieval of the current username and groups. + * WebSphere Security helper class to allow retrieval of the current username and groups. *

- * See Spring Security JIRA SEC-477. - * + * See Spring Security Jira SEC-477. + * * @author Ruud Senden * @author Stephane Manciot * @since 2.0 @@ -35,11 +35,11 @@ final class WASSecurityHelper { private static Method getSecurityName = null; // SEC-803 - private static Class wsCredentialClass = null; - + private static Class wsCredentialClass = null; + /** * Get the security name for the given subject. - * + * * @param subject * The subject for which to retrieve the security name * @return String the security name for the given subject @@ -64,7 +64,7 @@ final class WASSecurityHelper { /** * Get the current RunAs subject. - * + * * @return Subject the current RunAs subject */ private static final Subject getRunAsSubject() { @@ -75,7 +75,7 @@ final class WASSecurityHelper { /** * Get the WebSphere group names for the given subject. - * + * * @param subject * The subject for which to retrieve the WebSphere group names * @return the WebSphere group names for the given subject @@ -86,11 +86,12 @@ final class WASSecurityHelper { /** * Get the WebSphere group names for the given security name. - * + * * @param securityName * The securityname for which to retrieve the WebSphere group names * @return the WebSphere group names for the given security name */ + @SuppressWarnings("unchecked") private static final String[] getWebSphereGroups(final String securityName) { Context ic = null; try { @@ -129,7 +130,7 @@ final class WASSecurityHelper { public static final String getCurrentUserName() { return getSecurityName(getRunAsSubject()); } - + private static final Object invokeMethod(Method method, Object instance, Object[] args) { try { @@ -148,9 +149,9 @@ final class WASSecurityHelper { private static final Method getMethod(String className, String methodName, String[] parameterTypeNames) { try { - Class c = Class.forName(className); + Class c = Class.forName(className); final int len = parameterTypeNames.length; - Class[] parameterTypes = new Class[len]; + Class[] parameterTypes = new Class[len]; for (int i = 0; i < len; i++) { parameterTypes[i] = Class.forName(parameterTypeNames[i]); } @@ -162,7 +163,7 @@ final class WASSecurityHelper { logger.error("Required method "+methodName+" with parameter types ("+ Arrays.asList(parameterTypeNames) +") not found on class "+className); throw new RuntimeException("Required class"+className+" not found",e); } - } + } private static final Method getRunAsSubjectMethod() { if (getRunAsSubject == null) { @@ -184,22 +185,22 @@ final class WASSecurityHelper { } return getSecurityName; } - + // SEC-803 - private static final Class getWSCredentialClass() { + private static final Class getWSCredentialClass() { if (wsCredentialClass == null) { wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential"); } return wsCredentialClass; } - - private static final Class getClass(String className) { + + private static final Class getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException e) { logger.error("Required class " + className + " not found"); throw new RuntimeException("Required class " + className + " not found",e); } - } + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java index dcd9007f99..e218ae65c9 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSphere2SpringSecurityPropagationInterceptor.java @@ -19,78 +19,78 @@ import org.springframework.util.Assert; * @since 1.0 */ public class WebSphere2SpringSecurityPropagationInterceptor implements MethodInterceptor { - private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class); - private AuthenticationManager authenticationManager = null; - private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource(); - - /** - * Authenticate with Spring Security based on WebSphere credentials before proceeding with method - * invocation, and clean up the Spring Security Context after method invocation finishes. - * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) - */ - public Object invoke(MethodInvocation methodInvocation) throws Throwable { - try { - LOG.debug("Performing Spring Security authentication with WebSphere credentials"); - authenticateSpringSecurityWithWASCredentials(this); - LOG.debug("Proceeding with method invocation"); - return methodInvocation.proceed(); - } finally { - LOG.debug("Clearing Spring Security security context"); - clearSpringSecurityContext(); - } - } - - /** - * Retrieve the current WebSphere credentials and authenticate them with Spring Security - * using the pre-authenticated authentication provider. - * @param aContext The context to use for building the authentication details. - */ - private final void authenticateSpringSecurityWithWASCredentials(Object aContext) - { - Assert.notNull(authenticationManager); - Assert.notNull(authenticationDetailsSource); - - String userName = WASSecurityHelper.getCurrentUserName(); - if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); } - PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null); - authRequest.setDetails(authenticationDetailsSource.buildDetails(null)); - if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); } - Authentication authResponse = authenticationManager.authenticate(authRequest); - if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); } - SecurityContextHolder.getContext().setAuthentication(authResponse); - } - - /** - * Clear the Spring Security Context - */ - private final void clearSpringSecurityContext() - { - SecurityContextHolder.clearContext(); - } + private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class); + private AuthenticationManager authenticationManager = null; + private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource(); + + /** + * Authenticate with Spring Security based on WebSphere credentials before proceeding with method + * invocation, and clean up the Spring Security Context after method invocation finishes. + * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) + */ + public Object invoke(MethodInvocation methodInvocation) throws Throwable { + try { + LOG.debug("Performing Spring Security authentication with WebSphere credentials"); + authenticateSpringSecurityWithWASCredentials(this); + LOG.debug("Proceeding with method invocation"); + return methodInvocation.proceed(); + } finally { + LOG.debug("Clearing Spring Security security context"); + clearSpringSecurityContext(); + } + } + + /** + * Retrieve the current WebSphere credentials and authenticate them with Spring Security + * using the pre-authenticated authentication provider. + * @param aContext The context to use for building the authentication details. + */ + private final void authenticateSpringSecurityWithWASCredentials(Object aContext) + { + Assert.notNull(authenticationManager); + Assert.notNull(authenticationDetailsSource); + + String userName = WASSecurityHelper.getCurrentUserName(); + if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); } + PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null); + authRequest.setDetails(authenticationDetailsSource.buildDetails(null)); + if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); } + Authentication authResponse = authenticationManager.authenticate(authRequest); + if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); } + SecurityContextHolder.getContext().setAuthentication(authResponse); + } + + /** + * Clear the Spring Security Context + */ + private final void clearSpringSecurityContext() + { + SecurityContextHolder.clearContext(); + } - /** - * @return Returns the authenticationManager. - */ - public AuthenticationManager getAuthenticationManager() { - return authenticationManager; - } - - /** - * @param authenticationManager The authenticationManager to set. - */ - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } - /** - * @return Returns the authenticationDetailsSource. - */ - public AuthenticationDetailsSource getAuthenticationDetailsSource() { - return authenticationDetailsSource; - } - /** - * @param authenticationDetailsSource The authenticationDetailsSource to set. - */ - public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) { - this.authenticationDetailsSource = authenticationDetailsSource; - } + /** + * @return Returns the authenticationManager. + */ + public AuthenticationManager getAuthenticationManager() { + return authenticationManager; + } + + /** + * @param authenticationManager The authenticationManager to set. + */ + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + /** + * @return Returns the authenticationDetailsSource. + */ + public AuthenticationDetailsSource getAuthenticationDetailsSource() { + return authenticationDetailsSource; + } + /** + * @param authenticationDetailsSource The authenticationDetailsSource to set. + */ + public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) { + this.authenticationDetailsSource = authenticationDetailsSource; + } } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java index 1ec117a43e..57229addf1 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedAuthenticationDetailsSource.java @@ -70,8 +70,7 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen List webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser()); List userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups); if (logger.isDebugEnabled()) { - logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " - + Arrays.asList(userGas)); + logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas); } return userGas; } diff --git a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java index f093bdbcbd..8f3cd425c3 100755 --- a/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java +++ b/core/src/main/java/org/springframework/security/ui/preauth/websphere/WebSpherePreAuthenticatedWebAuthenticationDetailsSource.java @@ -13,12 +13,12 @@ import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritie * @author Ruud Senden */ public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource extends WebSpherePreAuthenticatedAuthenticationDetailsSource { - /** - * Public constructor which overrides the default AuthenticationDetails - * class to be used. - */ - public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() { - super(); - super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class); - } + /** + * Public constructor which overrides the default AuthenticationDetails + * class to be used. + */ + public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() { + super(); + super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class); + } } diff --git a/core/src/main/java/org/springframework/security/ui/rememberme/InMemoryTokenRepositoryImpl.java b/core/src/main/java/org/springframework/security/ui/rememberme/InMemoryTokenRepositoryImpl.java index 5b184d9e42..dc03299381 100644 --- a/core/src/main/java/org/springframework/security/ui/rememberme/InMemoryTokenRepositoryImpl.java +++ b/core/src/main/java/org/springframework/security/ui/rememberme/InMemoryTokenRepositoryImpl.java @@ -8,16 +8,16 @@ import java.util.Iterator; import java.util.Map; /** - * Simple PersistentTokenRepository implementation backed by a Map. Intended for testing only. + * Simple PersistentTokenRepository implementation backed by a Map. Intended for testing only. * * @author Luke Taylor * @version $Id$ */ public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository { - private Map seriesTokens = new HashMap(); + private Map seriesTokens = new HashMap(); public synchronized void createNewToken(PersistentRememberMeToken token) { - PersistentRememberMeToken current = (PersistentRememberMeToken) seriesTokens.get(token.getSeries()); + PersistentRememberMeToken current = seriesTokens.get(token.getSeries()); if (current != null) { throw new DataIntegrityViolationException("Series Id '"+ token.getSeries() +"' already exists!"); @@ -41,7 +41,7 @@ public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository { } public synchronized void removeUserTokens(String username) { - Iterator series = seriesTokens.keySet().iterator(); + Iterator series = seriesTokens.keySet().iterator(); while (series.hasNext()) { Object seriesId = series.next(); diff --git a/core/src/main/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImpl.java b/core/src/main/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImpl.java index 11b3f43b57..ce2bdd9d3d 100644 --- a/core/src/main/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImpl.java +++ b/core/src/main/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImpl.java @@ -48,10 +48,10 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL; private boolean createTableOnStartup; - protected MappingSqlQuery tokensBySeriesMapping; - protected SqlUpdate insertToken; - protected SqlUpdate updateToken; - protected SqlUpdate removeUserTokens; + private MappingSqlQuery tokensBySeriesMapping; + private SqlUpdate insertToken; + private SqlUpdate updateToken; + private SqlUpdate removeUserTokens; protected void initDao() { tokensBySeriesMapping = new TokensBySeriesMapping(getDataSource()); @@ -111,14 +111,14 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten //~ Inner Classes ================================================================================================== - protected class TokensBySeriesMapping extends MappingSqlQuery { + private class TokensBySeriesMapping extends MappingSqlQuery { protected TokensBySeriesMapping(DataSource ds) { super(ds, tokensBySeriesSql); declareParameter(new SqlParameter(Types.VARCHAR)); compile(); } - protected Object mapRow(ResultSet rs, int rowNum) throws SQLException { + protected PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) throws SQLException { PersistentRememberMeToken token = new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4)); @@ -126,7 +126,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten } } - protected class UpdateToken extends SqlUpdate { + private class UpdateToken extends SqlUpdate { public UpdateToken(DataSource ds) { super(ds, updateTokenSql); @@ -138,7 +138,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten } } - protected class InsertToken extends SqlUpdate { + private class InsertToken extends SqlUpdate { public InsertToken(DataSource ds) { super(ds, insertTokenSql); @@ -150,7 +150,7 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten } } - protected class RemoveUserTokens extends SqlUpdate { + private class RemoveUserTokens extends SqlUpdate { public RemoveUserTokens(DataSource ds) { super(ds, removeUserTokensSql); declareParameter(new SqlParameter(Types.VARCHAR)); diff --git a/core/src/main/java/org/springframework/security/ui/rememberme/RememberMeProcessingFilter.java b/core/src/main/java/org/springframework/security/ui/rememberme/RememberMeProcessingFilter.java index 5bb045acf3..3f980aa6aa 100644 --- a/core/src/main/java/org/springframework/security/ui/rememberme/RememberMeProcessingFilter.java +++ b/core/src/main/java/org/springframework/security/ui/rememberme/RememberMeProcessingFilter.java @@ -63,9 +63,9 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements //~ Methods ======================================================================================================== public void afterPropertiesSet() throws Exception { - Assert.notNull(authenticationManager, "authenticationManager must be specified"); - Assert.notNull(rememberMeServices, "rememberMeServices must be specified"); - } + Assert.notNull(authenticationManager, "authenticationManager must be specified"); + Assert.notNull(rememberMeServices, "rememberMeServices must be specified"); + } public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { @@ -76,7 +76,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements if (rememberMeAuth != null) { // Attempt authenticaton via AuthenticationManager try { - rememberMeAuth = authenticationManager.authenticate(rememberMeAuth); + rememberMeAuth = authenticationManager.authenticate(rememberMeAuth); // Store to SecurityContextHolder SecurityContextHolder.getContext().setAuthentication(rememberMeAuth); @@ -122,7 +122,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements * autoLogin method and the AuthenticationManager. */ protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, - Authentication authResult) { + Authentication authResult) { } /** @@ -131,7 +131,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements * token is present in the request and autoLogin returns null. */ protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, - AuthenticationException failed) { + AuthenticationException failed) { } public RememberMeServices getRememberMeServices() { diff --git a/core/src/main/java/org/springframework/security/ui/savedrequest/FastHttpDateFormat.java b/core/src/main/java/org/springframework/security/ui/savedrequest/FastHttpDateFormat.java index a70c2f18c2..c98b7a596f 100644 --- a/core/src/main/java/org/springframework/security/ui/savedrequest/FastHttpDateFormat.java +++ b/core/src/main/java/org/springframework/security/ui/savedrequest/FastHttpDateFormat.java @@ -26,8 +26,9 @@ import java.util.TimeZone; /** - *

Utility class to generate HTTP dates.

- *

This class is based on code in Apache Tomcat.

+ * Utility class to generate HTTP dates. + *

+ * This class is based on code in Apache Tomcat. * * @author Remy Maucherat * @author Andrey Grebnev @@ -46,7 +47,7 @@ public class FastHttpDateFormat { new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; - /** GMT timezone - all HTTP dates are on GMT */ + /** GMT time zone - all HTTP dates are on GMT */ protected static final TimeZone gmtZone = TimeZone.getTimeZone("GMT"); static { @@ -64,10 +65,10 @@ public class FastHttpDateFormat { protected static String currentDate = null; /** Formatter cache. */ - protected static final HashMap formatCache = new HashMap(); + protected static final HashMap formatCache = new HashMap(); /** Parser cache. */ - protected static final HashMap parseCache = new HashMap(); + protected static final HashMap parseCache = new HashMap(); //~ Methods ======================================================================================================== @@ -84,7 +85,7 @@ public class FastHttpDateFormat { Long longValue = new Long(value); try { - cachedDate = (String) formatCache.get(longValue); + cachedDate = formatCache.get(longValue); } catch (Exception e) {} if (cachedDate != null) { @@ -163,7 +164,7 @@ public class FastHttpDateFormat { * @param value The string to parse * @param threadLocalformats Array of formats to use for parsing. If null, HTTP formats are used. * - * @return Parsed date (or -1 if error occured) + * @return Parsed date (or -1 if error occurred) */ public static final long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = null; @@ -205,6 +206,7 @@ public class FastHttpDateFormat { * @param key Key to be updated * @param value New value */ + @SuppressWarnings("unchecked") private static void updateCache(HashMap cache, Object key, Object value) { if (value == null) { return; diff --git a/core/src/main/java/org/springframework/security/userdetails/AuthenticationUserDetailsService.java b/core/src/main/java/org/springframework/security/userdetails/AuthenticationUserDetailsService.java index b33e5e8674..93e5b6c196 100644 --- a/core/src/main/java/org/springframework/security/userdetails/AuthenticationUserDetailsService.java +++ b/core/src/main/java/org/springframework/security/userdetails/AuthenticationUserDetailsService.java @@ -12,13 +12,13 @@ import org.springframework.security.Authentication; */ public interface AuthenticationUserDetailsService { - /** - * - * @param token The pre-authenticated authentication token - * @return UserDetails for the given authentication token, never null. - * @throws UsernameNotFoundException - * if no user details can be found for the given authentication - * token - */ - UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException; + /** + * + * @param token The pre-authenticated authentication token + * @return UserDetails for the given authentication token, never null. + * @throws UsernameNotFoundException + * if no user details can be found for the given authentication + * token + */ + UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException; } diff --git a/core/src/main/java/org/springframework/security/userdetails/UserDetailsByNameServiceWrapper.java b/core/src/main/java/org/springframework/security/userdetails/UserDetailsByNameServiceWrapper.java index 0e3187231d..1c5df7c5b9 100755 --- a/core/src/main/java/org/springframework/security/userdetails/UserDetailsByNameServiceWrapper.java +++ b/core/src/main/java/org/springframework/security/userdetails/UserDetailsByNameServiceWrapper.java @@ -14,33 +14,33 @@ import org.springframework.util.Assert; * @since 2.0 */ public class UserDetailsByNameServiceWrapper implements AuthenticationUserDetailsService, InitializingBean { - private UserDetailsService userDetailsService = null; + private UserDetailsService userDetailsService = null; - /** - * Check whether all required properties have been set. - * - * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() - */ - public void afterPropertiesSet() throws Exception { - Assert.notNull(userDetailsService, "UserDetailsService must be set"); - } + /** + * Check whether all required properties have been set. + * + * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ + public void afterPropertiesSet() throws Exception { + Assert.notNull(userDetailsService, "UserDetailsService must be set"); + } - /** - * Get the UserDetails object from the wrapped UserDetailsService - * implementation - */ - public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException, - DataAccessException { - return userDetailsService.loadUserByUsername(authentication.getName()); - } + /** + * Get the UserDetails object from the wrapped UserDetailsService + * implementation + */ + public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException, + DataAccessException { + return userDetailsService.loadUserByUsername(authentication.getName()); + } - /** - * Set the wrapped UserDetailsService implementation - * - * @param aUserDetailsService - * The wrapped UserDetailsService to set - */ - public void setUserDetailsService(UserDetailsService aUserDetailsService) { - userDetailsService = aUserDetailsService; - } + /** + * Set the wrapped UserDetailsService implementation + * + * @param aUserDetailsService + * The wrapped UserDetailsService to set + */ + public void setUserDetailsService(UserDetailsService aUserDetailsService) { + userDetailsService = aUserDetailsService; + } } diff --git a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java index 7d68f6ac66..d1464ca087 100644 --- a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcDaoImpl.java @@ -186,6 +186,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { * Executes the SQL usersByUsernameQuery and returns a list of UserDetails objects. * There should normally only be one matching user. */ + @SuppressWarnings("unchecked") protected List loadUsersByUsername(String username) { return getJdbcTemplate().query(usersByUsernameQuery, new String[] {username}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { @@ -203,6 +204,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { * * @return a list of GrantedAuthority objects for the user */ + @SuppressWarnings("unchecked") protected List loadUserAuthorities(String username) { return getJdbcTemplate().query(authoritiesByUsernameQuery, new String[] {username}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { @@ -219,6 +221,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService { * * @return a list of GrantedAuthority objects for the user */ + @SuppressWarnings("unchecked") protected List loadGroupAuthorities(String username) { return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { diff --git a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManager.java b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManager.java index 979437075c..a5de681754 100644 --- a/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManager.java @@ -189,7 +189,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa String username = currentUser.getName(); - // If an authentication manager has been set, reauthenticate the user with the supplied password. + // If an authentication manager has been set, re-authenticate the user with the supplied password. if (authenticationManager != null) { logger.debug("Reauthenticating user '"+ username + "' for password change request."); @@ -200,7 +200,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa logger.debug("Changing password for user '"+ username + "'"); - getJdbcTemplate().update(changePasswordSql, new String[] {newPassword, username}); + getJdbcTemplate().update(changePasswordSql, newPassword, username); SecurityContextHolder.getContext().setAuthentication(createNewAuthentication(currentUser, newPassword)); @@ -218,7 +218,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa } public boolean userExists(String username) { - List users = getJdbcTemplate().queryForList(userExistsSql, new Object[] {username}); + List users = getJdbcTemplate().queryForList(userExistsSql, new String[] {username}, String.class); if (users.size() > 1) { throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'", 1); @@ -245,7 +245,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa logger.debug("Creating new group '" + groupName + "' with authorities " + AuthorityUtils.authorityListToSet(authorities)); - getJdbcTemplate().update(insertGroupSql, new String[] {groupName}); + getJdbcTemplate().update(insertGroupSql, new Object[] {groupName}); final int groupId = findGroupId(groupName); @@ -280,7 +280,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa Assert.hasText(oldName); Assert.hasText(newName); - getJdbcTemplate().update(renameGroupSql, new String[] {newName, oldName}); + getJdbcTemplate().update(renameGroupSql, new Object[] {newName, oldName}); } public void addUserToGroup(final String username, final String groupName) { @@ -316,6 +316,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa userCache.removeUserFromCache(username); } + @SuppressWarnings("unchecked") public List findGroupAuthorities(String groupName) { logger.debug("Loading authorities for group '" + groupName + "'"); Assert.hasText(groupName); diff --git a/core/src/main/java/org/springframework/security/userdetails/ldap/InetOrgPerson.java b/core/src/main/java/org/springframework/security/userdetails/ldap/InetOrgPerson.java index 358c5b1fd1..50a512e00d 100644 --- a/core/src/main/java/org/springframework/security/userdetails/ldap/InetOrgPerson.java +++ b/core/src/main/java/org/springframework/security/userdetails/ldap/InetOrgPerson.java @@ -29,19 +29,19 @@ import org.springframework.ldap.core.DirContextOperations; * @version $Id$ */ public class InetOrgPerson extends Person { - private String carLicense; - // Person.cn + private String carLicense; + // Person.cn private String destinationIndicator; - private String departmentNumber; - // Person.description - private String displayName; - private String employeeNumber; - private String homePhone; - private String homePostalAddress; - private String initials; - private String mail; - private String mobile; - private String o; + private String departmentNumber; + // Person.description + private String displayName; + private String employeeNumber; + private String homePhone; + private String homePostalAddress; + private String initials; + private String mail; + private String mobile; + private String o; private String ou; private String postalAddress; private String postalCode; @@ -49,7 +49,7 @@ public class InetOrgPerson extends Person { private String street; // Person.sn // Person.telephoneNumber - private String title; + private String title; private String uid; public String getUid() { @@ -65,7 +65,7 @@ public class InetOrgPerson extends Person { } public String getInitials() { - return initials; + return initials; } public String getDestinationIndicator() { @@ -73,58 +73,58 @@ public class InetOrgPerson extends Person { } public String getO() { - return o; - } + return o; + } public String getOu() { - return ou; - } + return ou; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public String getCarLicense() { - return carLicense; - } + public String getCarLicense() { + return carLicense; + } - public String getDepartmentNumber() { - return departmentNumber; - } + public String getDepartmentNumber() { + return departmentNumber; + } - public String getDisplayName() { - return displayName; - } - - public String getHomePhone() { - return homePhone; - } - - public String getRoomNumber() { - return roomNumber; - } + public String getDisplayName() { + return displayName; + } + + public String getHomePhone() { + return homePhone; + } + + public String getRoomNumber() { + return roomNumber; + } - public String getHomePostalAddress() { - return homePostalAddress; - } + public String getHomePostalAddress() { + return homePostalAddress; + } - public String getMobile() { - return mobile; - } + public String getMobile() { + return mobile; + } - public String getPostalAddress() { - return postalAddress; - } + public String getPostalAddress() { + return postalAddress; + } - public String getPostalCode() { - return postalCode; - } + public String getPostalCode() { + return postalCode; + } - public String getStreet() { - return street; - } + public String getStreet() { + return street; + } - protected void populateContext(DirContextAdapter adapter) { + protected void populateContext(DirContextAdapter adapter) { super.populateContext(adapter); adapter.setAttributeValue("carLicense", carLicense); adapter.setAttributeValue("departmentNumber", departmentNumber); @@ -172,7 +172,7 @@ public class InetOrgPerson extends Person { setUid(copyMe.getUid()); } - public Essence(DirContextOperations ctx) { + public Essence(DirContextOperations ctx) { super(ctx); setCarLicense(ctx.getStringAttribute("carLicense")); setDepartmentNumber(ctx.getStringAttribute("departmentNumber")); @@ -235,8 +235,8 @@ public class InetOrgPerson extends Person { } public void setDepartmentNumber(String departmentNumber) { - ((InetOrgPerson) instance).departmentNumber = departmentNumber; - } + ((InetOrgPerson) instance).departmentNumber = departmentNumber; + } public void setDisplayName(String displayName) { ((InetOrgPerson) instance).displayName = displayName; @@ -255,23 +255,23 @@ public class InetOrgPerson extends Person { } public void setStreet(String street) { - ((InetOrgPerson) instance).street = street; - } + ((InetOrgPerson) instance).street = street; + } public void setPostalCode(String postalCode) { - ((InetOrgPerson) instance).postalCode = postalCode; - } + ((InetOrgPerson) instance).postalCode = postalCode; + } public void setPostalAddress(String postalAddress) { - ((InetOrgPerson) instance).postalAddress = postalAddress; - } + ((InetOrgPerson) instance).postalAddress = postalAddress; + } public void setMobile(String mobile) { - ((InetOrgPerson) instance).mobile = mobile; - } + ((InetOrgPerson) instance).mobile = mobile; + } public void setHomePostalAddress(String homePostalAddress) { - ((InetOrgPerson) instance).homePostalAddress = homePostalAddress; - } + ((InetOrgPerson) instance).homePostalAddress = homePostalAddress; + } } } diff --git a/core/src/main/java/org/springframework/security/userdetails/ldap/LdapUserDetailsManager.java b/core/src/main/java/org/springframework/security/userdetails/ldap/LdapUserDetailsManager.java index 310b04233d..ad03cf0076 100644 --- a/core/src/main/java/org/springframework/security/userdetails/ldap/LdapUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/userdetails/ldap/LdapUserDetailsManager.java @@ -49,6 +49,7 @@ import javax.naming.directory.BasicAttribute; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapContext; import java.util.Arrays; import java.util.LinkedList; @@ -107,7 +108,7 @@ public class LdapUserDetailsManager implements UserDetailsManager { public Object mapFromAttributes(Attributes attributes) throws NamingException { Attribute roleAttr = attributes.get(groupRoleAttributeName); - NamingEnumeration ne = roleAttr.getAll(); + NamingEnumeration ne = roleAttr.getAll(); // assert ne.hasMore(); Object group = ne.next(); String role = group.toString(); @@ -204,9 +205,10 @@ public class LdapUserDetailsManager implements UserDetailsManager { * @param username the user whose roles are required. * @return the granted authorities returned by the group search */ + @SuppressWarnings("unchecked") List getUserAuthorities(final DistinguishedName dn, final String username) { SearchExecutor se = new SearchExecutor() { - public NamingEnumeration executeSearch(DirContext ctx) throws NamingException { + public NamingEnumeration executeSearch(DirContext ctx) throws NamingException { DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); SearchControls ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] {groupRoleAttributeName}); @@ -257,9 +259,9 @@ public class LdapUserDetailsManager implements UserDetailsManager { copyToContext(user, ctx); // Remove the objectclass attribute from the list of mods (if present). - List mods = new LinkedList(Arrays.asList(ctx.getModificationItems())); + List mods = new LinkedList(Arrays.asList(ctx.getModificationItems())); + ListIterator modIt = mods.listIterator(); - ListIterator modIt = mods.listIterator(); while(modIt.hasNext()) { ModificationItem mod = (ModificationItem) modIt.next(); Attribute a = mod.getAttribute(); @@ -268,7 +270,7 @@ public class LdapUserDetailsManager implements UserDetailsManager { } } - template.modifyAttributes(dn, (ModificationItem[]) mods.toArray(new ModificationItem[mods.size()])); + template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()])); // template.rebind(dn, ctx, null); // Remove the old authorities and replace them with the new one diff --git a/core/src/main/java/org/springframework/security/userdetails/memory/UserMap.java b/core/src/main/java/org/springframework/security/userdetails/memory/UserMap.java index e790d38ce9..2c7744e466 100644 --- a/core/src/main/java/org/springframework/security/userdetails/memory/UserMap.java +++ b/core/src/main/java/org/springframework/security/userdetails/memory/UserMap.java @@ -38,7 +38,7 @@ public class UserMap { //~ Instance fields ================================================================================================ - private Map userMap = new HashMap(); + private Map userMap = new HashMap(); //~ Methods ======================================================================================================== @@ -66,7 +66,7 @@ public class UserMap { * @throws UsernameNotFoundException if the user could not be found */ public UserDetails getUser(String username) throws UsernameNotFoundException { - UserDetails result = (UserDetails) this.userMap.get(username.toLowerCase()); + UserDetails result = this.userMap.get(username.toLowerCase()); if (result == null) { throw new UsernameNotFoundException("Could not find user: " + username, username); @@ -90,7 +90,7 @@ public class UserMap { * @param users {@link Map} <{@link String}, {@link UserDetails}> with pairs (username, userdetails) * @since 1.1 */ - public void setUsers(Map users) { + public void setUsers(Map users) { this.userMap = users; } } diff --git a/core/src/main/java/org/springframework/security/userdetails/memory/UserMapEditor.java b/core/src/main/java/org/springframework/security/userdetails/memory/UserMapEditor.java index 31d76eff8a..6d32b1cc6f 100644 --- a/core/src/main/java/org/springframework/security/userdetails/memory/UserMapEditor.java +++ b/core/src/main/java/org/springframework/security/userdetails/memory/UserMapEditor.java @@ -49,7 +49,7 @@ public class UserMapEditor extends PropertyEditorSupport { // Now we have properties, process each one individually UserAttributeEditor configAttribEd = new UserAttributeEditor(); - for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { + for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { String username = (String) iter.next(); String value = props.getProperty(username); diff --git a/core/src/main/java/org/springframework/security/util/FieldUtils.java b/core/src/main/java/org/springframework/security/util/FieldUtils.java index 81433a1040..55cf07d98d 100644 --- a/core/src/main/java/org/springframework/security/util/FieldUtils.java +++ b/core/src/main/java/org/springframework/security/util/FieldUtils.java @@ -36,7 +36,7 @@ public final class FieldUtils { //~ Methods ======================================================================================================== - public static String getAccessorName(String fieldName, Class type) { + public static String getAccessorName(String fieldName, Class type) { Assert.hasText(fieldName, "FieldName required"); Assert.notNull(type, "Type required"); @@ -57,7 +57,7 @@ public final class FieldUtils { * * @throws IllegalStateException if field could not be found */ - public static Field getField(Class clazz, String fieldName) throws IllegalStateException { + public static Field getField(Class clazz, String fieldName) throws IllegalStateException { Assert.notNull(clazz, "Class required"); Assert.hasText(fieldName, "Field name required"); @@ -72,7 +72,7 @@ public final class FieldUtils { throw new IllegalStateException("Could not locate field '" + fieldName + "' on class " + clazz); } } - + /** * Returns the value of a (nested) field on a bean. Intended for testing. * @param bean the object @@ -80,22 +80,22 @@ public final class FieldUtils { * @return the value of the nested field */ public static Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException { - Assert.notNull(bean, "Bean cannot be null"); - Assert.hasText(fieldName, "Field name required"); + Assert.notNull(bean, "Bean cannot be null"); + Assert.hasText(fieldName, "Field name required"); String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, "."); - Class componentClass = bean.getClass(); + Class componentClass = bean.getClass(); Field field = null; Object value = bean; - + for (int i=0; i < nestedFields.length; i++) { field = getField(componentClass, nestedFields[i]); field.setAccessible(true); - value = field.get(value); + value = field.get(value); componentClass = value.getClass(); } - + return value; - + } public static String getMutatorName(String fieldName) { diff --git a/core/src/main/java/org/springframework/security/util/RedirectUtils.java b/core/src/main/java/org/springframework/security/util/RedirectUtils.java index 045dfaf9fd..6a152ae9ac 100644 --- a/core/src/main/java/org/springframework/security/util/RedirectUtils.java +++ b/core/src/main/java/org/springframework/security/util/RedirectUtils.java @@ -26,7 +26,7 @@ public abstract class RedirectUtils { * @param response the response to redirect * @param url the target url to redirect to * @param useRelativeContext if true, causes any redirection URLs to be calculated minus the protocol - * and context path. + * and context path. * * @see AbstractProcessingFilter#setUseRelativeContext(boolean) */ @@ -34,29 +34,29 @@ public abstract class RedirectUtils { HttpServletResponse response, String url, boolean useRelativeContext) throws IOException { - String finalUrl; - if (!url.startsWith("http://") && !url.startsWith("https://")) { - if (useRelativeContext) { - finalUrl = url; - } - else { - finalUrl = request.getContextPath() + url; - } - } + String finalUrl; + if (!url.startsWith("http://") && !url.startsWith("https://")) { + if (useRelativeContext) { + finalUrl = url; + } + else { + finalUrl = request.getContextPath() + url; + } + } else if (useRelativeContext) { - // Calculate the relative URL from the fully qualifed URL, minus the protocol and base context. - int len = request.getContextPath().length(); - int index = url.indexOf(request.getContextPath()) + len; - finalUrl = url.substring(index); + // Calculate the relative URL from the fully qualifed URL, minus the protocol and base context. + int len = request.getContextPath().length(); + int index = url.indexOf(request.getContextPath()) + len; + finalUrl = url.substring(index); if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') { - finalUrl = finalUrl.substring(1); - } - } - else { - finalUrl = url; - } + finalUrl = finalUrl.substring(1); + } + } + else { + finalUrl = url; + } - response.sendRedirect(response.encodeRedirectURL(finalUrl)); + response.sendRedirect(response.encodeRedirectURL(finalUrl)); } } diff --git a/core/src/main/java/org/springframework/security/util/RegexUrlPathMatcher.java b/core/src/main/java/org/springframework/security/util/RegexUrlPathMatcher.java index 2825e8578d..e73bbf38dd 100644 --- a/core/src/main/java/org/springframework/security/util/RegexUrlPathMatcher.java +++ b/core/src/main/java/org/springframework/security/util/RegexUrlPathMatcher.java @@ -1,8 +1,5 @@ package org.springframework.security.util; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import java.util.regex.Pattern; /** @@ -10,8 +7,6 @@ import java.util.regex.Pattern; * @version $Id$ */ public class RegexUrlPathMatcher implements UrlMatcher { - private static final Log logger = LogFactory.getLog(RegexUrlPathMatcher.class); - private boolean requiresLowerCaseUrl = false; public Object compile(String path) { diff --git a/core/src/main/java/org/springframework/security/util/SessionUtils.java b/core/src/main/java/org/springframework/security/util/SessionUtils.java index c85be7d258..3567bcf616 100644 --- a/core/src/main/java/org/springframework/security/util/SessionUtils.java +++ b/core/src/main/java/org/springframework/security/util/SessionUtils.java @@ -2,7 +2,6 @@ package org.springframework.security.util; import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -21,28 +20,29 @@ import org.springframework.security.context.SecurityContextHolder; */ public final class SessionUtils { private final static Log logger = LogFactory.getLog(SessionUtils.class); - + SessionUtils() {} - public static void startNewSessionIfRequired(HttpServletRequest request, boolean migrateAttributes, + @SuppressWarnings("unchecked") + public static void startNewSessionIfRequired(HttpServletRequest request, boolean migrateAttributes, SessionRegistry sessionRegistry) { - + HttpSession session = request.getSession(false); if (session == null) { return; } - + String originalSessionId = session.getId(); if (logger.isDebugEnabled()) { logger.debug("Invalidating session with Id '" + originalSessionId +"' " + (migrateAttributes ? "and" : "without") + " migrating attributes."); - } + } + + HashMap attributesToMigrate = null; - HashMap attributesToMigrate = null; - if (migrateAttributes) { - attributesToMigrate = new HashMap(); + attributesToMigrate = new HashMap(); Enumeration enumer = session.getAttributeNames(); @@ -51,29 +51,26 @@ public final class SessionUtils { attributesToMigrate.put(key, session.getAttribute(key)); } } - + session.invalidate(); session = request.getSession(true); // we now have a new session if (logger.isDebugEnabled()) { logger.debug("Started new session: " + session.getId()); } - - if (attributesToMigrate != null) { - Iterator iter = attributesToMigrate.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - session.setAttribute((String) entry.getKey(), entry.getValue()); + if (attributesToMigrate != null) { + for (Map.Entry entry : attributesToMigrate.entrySet()) { + session.setAttribute(entry.getKey(), entry.getValue()); } } - + if (sessionRegistry != null) { sessionRegistry.removeSessionInformation(originalSessionId); Object principal = SessionRegistryUtils.obtainPrincipalFromAuthentication( SecurityContextHolder.getContext().getAuthentication()); - + sessionRegistry.registerNewSession(session.getId(), principal); - } + } } } diff --git a/core/src/main/java/org/springframework/security/util/ThrowableAnalyzer.java b/core/src/main/java/org/springframework/security/util/ThrowableAnalyzer.java index e6c393b542..5ea0f63680 100755 --- a/core/src/main/java/org/springframework/security/util/ThrowableAnalyzer.java +++ b/core/src/main/java/org/springframework/security/util/ThrowableAnalyzer.java @@ -127,7 +127,8 @@ public class ThrowableAnalyzer { * * @return the types for which extractors are registered */ - final Class[] getRegisteredTypes() { + @SuppressWarnings("unchecked") + final Class[] getRegisteredTypes() { Set> typeList = this.extractorMap.keySet(); return typeList.toArray(new Class[typeList.size()]); } diff --git a/core/src/main/java/org/springframework/security/wrapper/SavedRequestAwareWrapper.java b/core/src/main/java/org/springframework/security/wrapper/SavedRequestAwareWrapper.java index 2255477290..82b8543d87 100644 --- a/core/src/main/java/org/springframework/security/wrapper/SavedRequestAwareWrapper.java +++ b/core/src/main/java/org/springframework/security/wrapper/SavedRequestAwareWrapper.java @@ -168,6 +168,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW } @Override + @SuppressWarnings("unchecked") public Enumeration getHeaderNames() { if (savedRequest == null) { return super.getHeaderNames(); @@ -177,6 +178,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW } @Override + @SuppressWarnings("unchecked") public Enumeration getHeaders(String name) { if (savedRequest == null) { return super.getHeaders(name); @@ -223,6 +225,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW } @Override + @SuppressWarnings("unchecked") public Enumeration getLocales() { if (savedRequest == null) { return super.getLocales(); @@ -278,6 +281,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW } @Override + @SuppressWarnings("unchecked") public Map getParameterMap() { if (savedRequest == null) { return super.getParameterMap(); @@ -293,6 +297,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW return parameterMap; } + @SuppressWarnings("unchecked") private Set getCombinedParameterNames() { Set names = new HashSet(); names.addAll(super.getParameterMap().keySet()); @@ -305,6 +310,7 @@ public class SavedRequestAwareWrapper extends SecurityContextHolderAwareRequestW } @Override + @SuppressWarnings("unchecked") public Enumeration getParameterNames() { return new Enumerator(getCombinedParameterNames()); } diff --git a/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java b/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java index 24284faac4..6d40241cb8 100644 --- a/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java +++ b/core/src/test/java/org/springframework/security/AuthenticationTrustResolverImplTests.java @@ -20,6 +20,7 @@ import junit.framework.TestCase; import org.springframework.security.providers.TestingAuthenticationToken; import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken; import org.springframework.security.providers.rememberme.RememberMeAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** @@ -35,21 +36,17 @@ public class AuthenticationTrustResolverImplTests extends TestCase { public void testCorrectOperationIsAnonymous() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); assertTrue(trustResolver.isAnonymous( - new AnonymousAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}))); + new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")))); assertFalse(trustResolver.isAnonymous( - new TestingAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}))); + new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")))); } public void testCorrectOperationIsRememberMe() { AuthenticationTrustResolverImpl trustResolver = new AuthenticationTrustResolverImpl(); assertTrue(trustResolver.isRememberMe( - new RememberMeAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}))); + new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")))); assertFalse(trustResolver.isAnonymous( - new TestingAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}))); + new TestingAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")))); } public void testGettersSetters() { diff --git a/core/src/test/java/org/springframework/security/GrantedAuthorityImplTests.java b/core/src/test/java/org/springframework/security/GrantedAuthorityImplTests.java index b1eb9d293f..31e45f38f8 100644 --- a/core/src/test/java/org/springframework/security/GrantedAuthorityImplTests.java +++ b/core/src/test/java/org/springframework/security/GrantedAuthorityImplTests.java @@ -27,8 +27,8 @@ import org.junit.Test; * @version $Id$ */ public class GrantedAuthorityImplTests { - - @Test + + @Test public void equalsBehavesAsExpected() throws Exception { GrantedAuthorityImpl auth1 = new GrantedAuthorityImpl("TEST"); GrantedAuthorityImpl auth2 = new GrantedAuthorityImpl("TEST"); @@ -53,28 +53,28 @@ public class GrantedAuthorityImplTests { assertTrue(!auth1.equals(int1)); } - @Test + @Test public void toStringReturnsAuthorityValue() { GrantedAuthorityImpl auth = new GrantedAuthorityImpl("TEST"); assertEquals("TEST", auth.toString()); } - @Test - public void compareToGrantedAuthorityWithSameValueReturns0() { - assertEquals(0, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority("TEST"))); - } + @Test + public void compareToGrantedAuthorityWithSameValueReturns0() { + assertEquals(0, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority("TEST"))); + } - @Test - public void compareToNullReturnsNegativeOne() { - assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(null)); - } - - /* SEC-899 */ - @Test - public void compareToHandlesCustomAuthorityWhichReturnsNullFromGetAuthority() { - assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority())); - } - + @Test + public void compareToNullReturnsNegativeOne() { + assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(null)); + } + + /* SEC-899 */ + @Test + public void compareToHandlesCustomAuthorityWhichReturnsNullFromGetAuthority() { + assertEquals(-1, new GrantedAuthorityImpl("TEST").compareTo(new MockGrantedAuthority())); + } + //~ Inner Classes ================================================================================================== private class MockGrantedAuthority implements GrantedAuthority { @@ -88,8 +88,8 @@ public class GrantedAuthorityImplTests { } public int compareTo(Object o) { - throw new UnsupportedOperationException(); - } + throw new UnsupportedOperationException(); + } public String getAuthority() { return this.role; diff --git a/core/src/test/java/org/springframework/security/MockFilterChain.java b/core/src/test/java/org/springframework/security/MockFilterChain.java deleted file mode 100644 index 0644ba70f6..0000000000 --- a/core/src/test/java/org/springframework/security/MockFilterChain.java +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.security; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - - -/** - * Mocks a FilterChain but with no behaviour. - * - * @author Ben Alex - * @version $Id$ - */ -public class MockFilterChain implements FilterChain { - //~ Methods ======================================================================================================== - - public void doFilter(ServletRequest arg0, ServletResponse arg1) - throws IOException, ServletException { - throw new UnsupportedOperationException("mock method not implemented"); - } -} diff --git a/core/src/test/java/org/springframework/security/MockFilterConfig.java b/core/src/test/java/org/springframework/security/MockFilterConfig.java index 9f7cf6f3c3..fb24e3c71c 100644 --- a/core/src/test/java/org/springframework/security/MockFilterConfig.java +++ b/core/src/test/java/org/springframework/security/MockFilterConfig.java @@ -28,9 +28,9 @@ import javax.servlet.ServletContext; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class MockFilterConfig implements FilterConfig { //~ Instance fields ================================================================================================ - private Map map = new HashMap(); //~ Methods ======================================================================================================== diff --git a/core/src/test/java/org/springframework/security/MockJoinPoint.java b/core/src/test/java/org/springframework/security/MockJoinPoint.java index 3cb779dc1d..158643addd 100644 --- a/core/src/test/java/org/springframework/security/MockJoinPoint.java +++ b/core/src/test/java/org/springframework/security/MockJoinPoint.java @@ -29,6 +29,7 @@ import java.lang.reflect.Method; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class MockJoinPoint implements JoinPoint { //~ Instance fields ================================================================================================ diff --git a/core/src/test/java/org/springframework/security/SecurityConfigTests.java b/core/src/test/java/org/springframework/security/SecurityConfigTests.java index 13cf2b8204..5927a82e76 100644 --- a/core/src/test/java/org/springframework/security/SecurityConfigTests.java +++ b/core/src/test/java/org/springframework/security/SecurityConfigTests.java @@ -30,28 +30,28 @@ public class SecurityConfigTests { //~ Methods ======================================================================================================== - @Test + @Test public void testHashCode() { SecurityConfig config = new SecurityConfig("TEST"); Assert.assertEquals("TEST".hashCode(), config.hashCode()); } @Test(expected=IllegalArgumentException.class) - public void testCannotConstructWithNullAttribute() { - new SecurityConfig(null); // SEC-727 + public void testCannotConstructWithNullAttribute() { + new SecurityConfig(null); // SEC-727 } @Test(expected=IllegalArgumentException.class) - public void testCannotConstructWithEmptyAttribute() { - new SecurityConfig(""); // SEC-727 + public void testCannotConstructWithEmptyAttribute() { + new SecurityConfig(""); // SEC-727 } @Test(expected=NoSuchMethodException.class) public void testNoArgConstructorDoesntExist() throws Exception { - SecurityConfig.class.getDeclaredConstructor((Class[]) null); + SecurityConfig.class.getDeclaredConstructor((Class[]) null); } - @Test + @Test public void testObjectEquals() throws Exception { SecurityConfig security1 = new SecurityConfig("TEST"); SecurityConfig security2 = new SecurityConfig("TEST"); @@ -77,12 +77,12 @@ public class SecurityConfigTests { Assert.assertTrue(!security1.equals(int1)); } - @Test + @Test public void testToString() { SecurityConfig config = new SecurityConfig("TEST"); Assert.assertEquals("TEST", config.toString()); - } - + } + //~ Inner Classes ================================================================================================== private class MockConfigAttribute implements ConfigAttribute { diff --git a/core/src/test/java/org/springframework/security/annotation/Entity.java b/core/src/test/java/org/springframework/security/annotation/Entity.java index 4d71d0a053..02031093cd 100644 --- a/core/src/test/java/org/springframework/security/annotation/Entity.java +++ b/core/src/test/java/org/springframework/security/annotation/Entity.java @@ -7,5 +7,5 @@ package org.springframework.security.annotation; * */ public class Entity { - public Entity(String someParameter) {} + public Entity(String someParameter) {} } diff --git a/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java b/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java index dcf5933639..1f4430da33 100755 --- a/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java +++ b/core/src/test/java/org/springframework/security/authoritymapping/XmlMappableRolesRetrieverTests.java @@ -14,6 +14,7 @@ import junit.framework.TestCase; * @author TSARDD * @since 18-okt-2007 */ +@SuppressWarnings("unchecked") public class XmlMappableRolesRetrieverTests extends TestCase { private static final String DEFAULT_XML = "Role1Role2"; diff --git a/core/src/test/java/org/springframework/security/config/CustomAuthenticationProviderBeanDefinitionDecoratorTests.java b/core/src/test/java/org/springframework/security/config/CustomAuthenticationProviderBeanDefinitionDecoratorTests.java index 047e81aad6..e02aa7780f 100644 --- a/core/src/test/java/org/springframework/security/config/CustomAuthenticationProviderBeanDefinitionDecoratorTests.java +++ b/core/src/test/java/org/springframework/security/config/CustomAuthenticationProviderBeanDefinitionDecoratorTests.java @@ -23,8 +23,8 @@ public class CustomAuthenticationProviderBeanDefinitionDecoratorTests { ProviderManager authMgr = (ProviderManager) ctx.getBean(BeanIds.AUTHENTICATION_MANAGER); assertEquals(1, authMgr.getProviders().size()); } - - + + @Test public void decoratedBeanAndRegisteredProviderAreTheSameObject() { InMemoryXmlApplicationContext ctx = new InMemoryXmlApplicationContext( diff --git a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java b/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java index b20062c719..9b80ab34a6 100644 --- a/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/core/src/test/java/org/springframework/security/config/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -191,6 +191,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { // Expression configuration tests + @SuppressWarnings("unchecked") @Test public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception { setContext("" + AUTH_PROVIDER_XML); diff --git a/core/src/test/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecoratorTests.java b/core/src/test/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecoratorTests.java index 1c905e8955..d7cd60c3ab 100644 --- a/core/src/test/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecoratorTests.java +++ b/core/src/test/java/org/springframework/security/config/InterceptMethodsBeanDefinitionDecoratorTests.java @@ -1,15 +1,16 @@ package org.springframework.security.config; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.security.AccessDeniedException; +import org.springframework.security.AuthenticationCredentialsNotFoundException; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.security.AuthenticationCredentialsNotFoundException; -import org.springframework.security.AccessDeniedException; - -import static org.junit.Assert.*; -import org.junit.*; +import org.springframework.security.util.AuthorityUtils; /** * @author Luke Taylor @@ -51,7 +52,7 @@ public class InterceptMethodsBeanDefinitionDecoratorTests { @Test public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")}); + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(token); @@ -61,7 +62,7 @@ public class InterceptMethodsBeanDefinitionDecoratorTests { @Test public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")}); + AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); SecurityContextHolder.getContext().setAuthentication(token); try { diff --git a/core/src/test/java/org/springframework/security/config/Jsr250AnnotationDrivenBeanDefinitionParserTests.java b/core/src/test/java/org/springframework/security/config/Jsr250AnnotationDrivenBeanDefinitionParserTests.java index ab764bd8ca..ceb002bfe0 100644 --- a/core/src/test/java/org/springframework/security/config/Jsr250AnnotationDrivenBeanDefinitionParserTests.java +++ b/core/src/test/java/org/springframework/security/config/Jsr250AnnotationDrivenBeanDefinitionParserTests.java @@ -5,11 +5,10 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.AccessDeniedException; import org.springframework.security.AuthenticationCredentialsNotFoundException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.annotation.BusinessService; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; import org.springframework.security.util.InMemoryXmlApplicationContext; /** @@ -46,7 +45,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests { @Test public void permitAllShouldBeDefaultAttribute() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")}); + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(token); target.someOther(0); @@ -55,7 +54,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests { @Test public void targetShouldAllowProtectedMethodInvocationWithCorrectRole() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")}); + AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(token); target.someUserMethod1(); @@ -64,7 +63,7 @@ public class Jsr250AnnotationDrivenBeanDefinitionParserTests { @Test(expected=AccessDeniedException.class) public void targetShouldPreventProtectedMethodInvocationWithIncorrectRole() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_SOMEOTHERROLE")}); + AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); SecurityContextHolder.getContext().setAuthentication(token); target.someAdminMethod(); diff --git a/core/src/test/java/org/springframework/security/config/LdapUserServiceBeanDefinitionParserTests.java b/core/src/test/java/org/springframework/security/config/LdapUserServiceBeanDefinitionParserTests.java index 68134cf908..401771ca83 100644 --- a/core/src/test/java/org/springframework/security/config/LdapUserServiceBeanDefinitionParserTests.java +++ b/core/src/test/java/org/springframework/security/config/LdapUserServiceBeanDefinitionParserTests.java @@ -41,7 +41,7 @@ public class LdapUserServiceBeanDefinitionParserTests { UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetails ben = uds.loadUserByUsername("ben"); - Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); + Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); assertEquals(3, authorities.size()); assertTrue(authorities.contains("ROLE_DEVELOPERS")); } @@ -66,20 +66,20 @@ public class LdapUserServiceBeanDefinitionParserTests { " user-search-filter='(uid={0})' " + " group-search-filter='member={0}' role-prefix='PREFIX_'/>" + ""); + " user-search-filter='(uid={0})' " + + " group-search-filter='member={0}' role-prefix='none'/>"); UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetails ben = uds.loadUserByUsername("ben"); assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("PREFIX_DEVELOPERS")); - + uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix"); ben = uds.loadUserByUsername("ben"); - assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("DEVELOPERS")); + assertTrue(AuthorityUtils.authorityListToSet(ben.getAuthorities()).contains("DEVELOPERS")); } - - - + + + @Test public void differentGroupRoleAttributeWorksAsExpected() throws Exception { setContext(""); @@ -87,12 +87,12 @@ public class LdapUserServiceBeanDefinitionParserTests { UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetails ben = uds.loadUserByUsername("ben"); - Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); + Set authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); assertEquals(3, authorities.size()); assertTrue(authorities.contains(new GrantedAuthorityImpl("ROLE_DEVELOPER"))); - + } - + @Test public void isSupportedByAuthenticationProviderElement() { setContext( @@ -101,7 +101,7 @@ public class LdapUserServiceBeanDefinitionParserTests { " " + ""); } - + @Test public void personContextMapperIsSupported() { setContext( @@ -111,7 +111,7 @@ public class LdapUserServiceBeanDefinitionParserTests { UserDetails ben = uds.loadUserByUsername("ben"); assertTrue(ben instanceof Person); } - + @Test public void inetOrgContextMapperIsSupported() { setContext( @@ -121,8 +121,8 @@ public class LdapUserServiceBeanDefinitionParserTests { UserDetails ben = uds.loadUserByUsername("ben"); assertTrue(ben instanceof InetOrgPerson); } - - + + private void setContext(String context) { appCtx = new InMemoryXmlApplicationContext(context); } diff --git a/core/src/test/java/org/springframework/security/config/MockUserServiceBeanPostProcessor.java b/core/src/test/java/org/springframework/security/config/MockUserServiceBeanPostProcessor.java index ccdb78007e..4e40c15858 100644 --- a/core/src/test/java/org/springframework/security/config/MockUserServiceBeanPostProcessor.java +++ b/core/src/test/java/org/springframework/security/config/MockUserServiceBeanPostProcessor.java @@ -11,15 +11,15 @@ import org.springframework.beans.factory.config.BeanPostProcessor; */ public class MockUserServiceBeanPostProcessor implements BeanPostProcessor { - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - return bean; - } + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + return bean; + } - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof PostProcessedMockUserDetailsService) { ((PostProcessedMockUserDetailsService)bean).setPostProcessorWasHere("Hello from the post processor!"); } - - return bean; - } + + return bean; + } } diff --git a/core/src/test/java/org/springframework/security/config/PostProcessedMockUserDetailsService.java b/core/src/test/java/org/springframework/security/config/PostProcessedMockUserDetailsService.java index ead48eac09..c274a2942b 100644 --- a/core/src/test/java/org/springframework/security/config/PostProcessedMockUserDetailsService.java +++ b/core/src/test/java/org/springframework/security/config/PostProcessedMockUserDetailsService.java @@ -6,22 +6,22 @@ import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; public class PostProcessedMockUserDetailsService implements UserDetailsService { - private String postProcessorWasHere; + private String postProcessorWasHere; - public PostProcessedMockUserDetailsService() { + public PostProcessedMockUserDetailsService() { this.postProcessorWasHere = "Post processor hasn't been yet"; } public String getPostProcessorWasHere() { - return postProcessorWasHere; - } + return postProcessorWasHere; + } - public void setPostProcessorWasHere(String postProcessorWasHere) { - this.postProcessorWasHere = postProcessorWasHere; - } + public void setPostProcessorWasHere(String postProcessorWasHere) { + this.postProcessorWasHere = postProcessorWasHere; + } - public UserDetails loadUserByUsername(String username) - throws UsernameNotFoundException, DataAccessException { - throw new UnsupportedOperationException("Not for actual use"); - } + public UserDetails loadUserByUsername(String username) + throws UsernameNotFoundException, DataAccessException { + throw new UnsupportedOperationException("Not for actual use"); + } } diff --git a/core/src/test/java/org/springframework/security/context/HttpSessionContextIntegrationFilterTests.java b/core/src/test/java/org/springframework/security/context/HttpSessionContextIntegrationFilterTests.java index 93ce5b280e..948ea677f8 100644 --- a/core/src/test/java/org/springframework/security/context/HttpSessionContextIntegrationFilterTests.java +++ b/core/src/test/java/org/springframework/security/context/HttpSessionContextIntegrationFilterTests.java @@ -40,6 +40,7 @@ import javax.servlet.ServletResponse; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("deprecation") public class HttpSessionContextIntegrationFilterTests extends TestCase { // Build an Authentication object we simulate came from HttpSession private UsernamePasswordAuthenticationToken sessionPrincipal = new UsernamePasswordAuthenticationToken( diff --git a/core/src/test/java/org/springframework/security/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java b/core/src/test/java/org/springframework/security/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java index 0b7d2e2646..116b6366c1 100644 --- a/core/src/test/java/org/springframework/security/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java +++ b/core/src/test/java/org/springframework/security/context/httpinvoker/AuthenticationSimpleHttpInvokerRequestExecutorTests.java @@ -40,19 +40,9 @@ import java.util.Map; * @version $Id$ */ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCase { - //~ Constructors =================================================================================================== - - public AuthenticationSimpleHttpInvokerRequestExecutorTests() { - super(); - } - - public AuthenticationSimpleHttpInvokerRequestExecutorTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== - protected void tearDown() throws Exception { super.tearDown(); SecurityContextHolder.clearContext(); @@ -91,7 +81,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas //~ Inner Classes ================================================================================================== private class MockHttpURLConnection extends HttpURLConnection { - private Map requestProperties = new HashMap(); + private Map requestProperties = new HashMap(); public MockHttpURLConnection(URL u) { super(u); @@ -106,7 +96,7 @@ public class AuthenticationSimpleHttpInvokerRequestExecutorTests extends TestCas } public String getRequestProperty(String key) { - return (String) requestProperties.get(key); + return requestProperties.get(key); } public void setRequestProperty(String key, String value) { diff --git a/core/src/test/java/org/springframework/security/context/rmi/ContextPropagatingRemoteInvocationTests.java b/core/src/test/java/org/springframework/security/context/rmi/ContextPropagatingRemoteInvocationTests.java index d9b0fb5cfd..4501e108ac 100644 --- a/core/src/test/java/org/springframework/security/context/rmi/ContextPropagatingRemoteInvocationTests.java +++ b/core/src/test/java/org/springframework/security/context/rmi/ContextPropagatingRemoteInvocationTests.java @@ -47,7 +47,7 @@ public class ContextPropagatingRemoteInvocationTests extends TestCase { } private ContextPropagatingRemoteInvocation getRemoteInvocation() throws Exception { - Class clazz = TargetObject.class; + Class clazz = TargetObject.class; Method method = clazz.getMethod("makeLowerCase", new Class[] {String.class}); MethodInvocation mi = new SimpleMethodInvocation(new TargetObject(), method, "SOME_STRING"); diff --git a/core/src/test/java/org/springframework/security/event/authentication/AuthenticationEventTests.java b/core/src/test/java/org/springframework/security/event/authentication/AuthenticationEventTests.java index 47ed47bac9..7eb4d61564 100644 --- a/core/src/test/java/org/springframework/security/event/authentication/AuthenticationEventTests.java +++ b/core/src/test/java/org/springframework/security/event/authentication/AuthenticationEventTests.java @@ -67,7 +67,7 @@ public class AuthenticationEventTests extends TestCase { AuthenticationException exception = new DisabledException("TEST"); try { - AuthenticationFailureDisabledEvent event = new AuthenticationFailureDisabledEvent(null, exception); + new AuthenticationFailureDisabledEvent(null, exception); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); diff --git a/core/src/test/java/org/springframework/security/expression/method/ExpressionAnnotationMethodDefinitionSourceTests.java b/core/src/test/java/org/springframework/security/expression/method/ExpressionAnnotationMethodDefinitionSourceTests.java index 9888642b32..e6cf2652d4 100644 --- a/core/src/test/java/org/springframework/security/expression/method/ExpressionAnnotationMethodDefinitionSourceTests.java +++ b/core/src/test/java/org/springframework/security/expression/method/ExpressionAnnotationMethodDefinitionSourceTests.java @@ -116,40 +116,40 @@ public class ExpressionAnnotationMethodDefinitionSourceTests { //~ Inner Classes ================================================================================================== public static interface ReturnVoid { - public void doSomething(List param); + public void doSomething(List param); } public static interface ReturnAList { - public List doSomething(List param); + public List doSomething(List param); } @PreAuthorize("interfaceAuthzExpression") public static interface ReturnAnotherList { @PreAuthorize("interfaceMethodAuthzExpression") @PreFilter(filterTarget="param", value="interfacePreFilterExpression") - public List doSomething(List param); + public List doSomething(List param); } @PreAuthorize("someExpression") public static class ReturnVoidImpl1 implements ReturnVoid { - public void doSomething(List param) {} + public void doSomething(List param) {} } @PreAuthorize("someExpression") public static class ReturnVoidImpl2 implements ReturnVoid { @PreFilter(filterTarget="param", value="somePreFilterExpression") - public void doSomething(List param) {} + public void doSomething(List param) {} } public static class ReturnVoidImpl3 implements ReturnVoid { @PreFilter(filterTarget="param", value="somePreFilterExpression") - public void doSomething(List param) {} + public void doSomething(List param) {} } public static class ReturnAListImpl1 implements ReturnAList { @PostFilter("somePostFilterExpression") - public List doSomething(List param) {return param;} + public List doSomething(List param) {return param;} } public static class ReturnAListImpl2 implements ReturnAList { @@ -157,16 +157,16 @@ public class ExpressionAnnotationMethodDefinitionSourceTests { @PreFilter(filterTarget="param", value="somePreFilterExpression") @PostFilter("somePostFilterExpression") @PostAuthorize("somePostAuthorizeExpression") - public List doSomething(List param) {return param;} + public List doSomething(List param) {return param;} } public static class ReturnAnotherListImpl1 implements ReturnAnotherList { - public List doSomething(List param) {return param;} + public List doSomething(List param) {return param;} } public static class ReturnAnotherListImpl2 implements ReturnAnotherList { @PreFilter(filterTarget="param", value="classMethodPreFilterExpression") - public List doSomething(List param) {return param;} + public List doSomething(List param) {return param;} } } diff --git a/core/src/test/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditorTests.java b/core/src/test/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditorTests.java index 963264b32a..3d344a1b36 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/method/MethodDefinitionSourceEditorTests.java @@ -17,7 +17,6 @@ package org.springframework.security.intercept.method; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; -import java.util.Iterator; import java.util.List; import junit.framework.TestCase; @@ -37,16 +36,8 @@ import org.springframework.security.TargetObject; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("deprecation") public class MethodDefinitionSourceEditorTests extends TestCase { - //~ Constructors =================================================================================================== - - public MethodDefinitionSourceEditorTests() { - } - - public MethodDefinitionSourceEditorTests(String arg0) { - super(arg0); - } - //~ Methods ======================================================================================================== public final void setUp() throws Exception { @@ -59,7 +50,7 @@ public class MethodDefinitionSourceEditorTests extends TestCase { MapBasedMethodDefinitionSource map = (MapBasedMethodDefinitionSource) editor.getValue(); - Class clazz = TargetObject.class; + Class clazz = TargetObject.class; Method method = clazz.getMethod("countLength", new Class[] {String.class}); MockJoinPoint joinPoint = new MockJoinPoint(new TargetObject(), method); @@ -146,7 +137,6 @@ public class MethodDefinitionSourceEditorTests extends TestCase { "org.springframework.security.TargetObject.countLength=ROLE_ONE,ROLE_TWO,RUN_AS_ENTRY\r\norg.springframework.security.TargetObject.make*=ROLE_NINE,ROLE_SUPERVISOR"); MapBasedMethodDefinitionSource map = (MapBasedMethodDefinitionSource) editor.getValue(); - Iterator iter = map.getAllConfigAttributes().iterator(); assertEquals(5, map.getAllConfigAttributes().size()); } @@ -220,7 +210,7 @@ public class MethodDefinitionSourceEditorTests extends TestCase { private Method method; private Object targetObject; - public MockMethodInvocation(Class clazz, String methodName, Class[] parameterTypes, Object targetObject) + public MockMethodInvocation(Class clazz, String methodName, Class[] parameterTypes, Object targetObject) throws NoSuchMethodException { this.method = clazz.getMethod(methodName, parameterTypes); this.targetObject = targetObject; diff --git a/core/src/test/java/org/springframework/security/intercept/method/MockMethodDefinitionSource.java b/core/src/test/java/org/springframework/security/intercept/method/MockMethodDefinitionSource.java index 3d5bd897bf..5ee6bef7e2 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/MockMethodDefinitionSource.java +++ b/core/src/test/java/org/springframework/security/intercept/method/MockMethodDefinitionSource.java @@ -19,7 +19,6 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.Vector; import org.aopalliance.intercept.MethodInvocation; import org.aspectj.lang.JoinPoint; @@ -28,7 +27,6 @@ import org.springframework.security.SecurityConfig; /** - * * @author Ben Alex * @version $Id$ */ diff --git a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java index f6751e9c1b..e9b83636cd 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorTests.java @@ -51,6 +51,7 @@ import org.springframework.security.runas.RunAsUserToken; * @author Ben Alex * @version $Id$ */ +@SuppressWarnings("unchecked") public class MethodSecurityInterceptorTests { private Mockery jmock = new JUnit4Mockery(); private TestingAuthenticationToken token; diff --git a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java b/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java index 2e1ec4add1..2a0878650e 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java +++ b/core/src/test/java/org/springframework/security/intercept/method/aopalliance/MethodSecurityInterceptorWithAopConfigTests.java @@ -41,7 +41,7 @@ public class MethodSecurityInterceptorWithAopConfigTests { @After public void closeAppContext() { SecurityContextHolder.clearContext(); - if (appContext != null) { + if (appContext != null) { appContext.close(); appContext = null; } @@ -51,20 +51,20 @@ public class MethodSecurityInterceptorWithAopConfigTests { public void securityInterceptorIsAppliedWhenUsedWithAopConfig() { setContext( "" + - " " + - " " + - "" + - "" + - "" + - " " + + " " + + " " + + "" + + "" + + "" + + " " + " " + "org.springframework.security.TargetObject.makeLower*=ROLE_A\n" + "org.springframework.security.TargetObject.makeUpper*=ROLE_A\n" + "org.springframework.security.TargetObject.computeHashCode*=ROLE_B\n" + " " + " " + - "" + - AUTH_PROVIDER_XML + ACCESS_MANAGER_XML); + "" + + AUTH_PROVIDER_XML + ACCESS_MANAGER_XML); ITargetObject target = (ITargetObject) appContext.getBean("target"); target.makeLowerCase("TEST"); diff --git a/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java b/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java index 8ba7bac5ef..7348de548b 100644 --- a/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/method/aspectj/AspectJSecurityInterceptorTests.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.security.AccessDecisionManager; import org.springframework.security.AccessDeniedException; import org.springframework.security.AuthenticationManager; -import org.springframework.security.ITargetObject; import org.springframework.security.MockJoinPoint; import org.springframework.security.SecurityConfig; import org.springframework.security.TargetObject; @@ -77,6 +76,7 @@ public class AspectJSecurityInterceptorTests { } @Test + @SuppressWarnings("unchecked") public void callbackIsInvokedWhenPermissionGranted() throws Exception { jmock.checking(new Expectations() {{ oneOf(mds).getAttributes(with(any(JoinPoint.class))); will (returnValue(SecurityConfig.createList("ROLE_USER"))); @@ -90,6 +90,7 @@ public class AspectJSecurityInterceptorTests { jmock.assertIsSatisfied(); } + @SuppressWarnings("unchecked") @Test(expected=AccessDeniedException.class) public void callbackIsNotInvokedWhenPermissionDenied() throws Exception { jmock.checking(new Expectations() {{ diff --git a/core/src/test/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSourceTests.java b/core/src/test/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSourceTests.java index 9b5a507113..d1e7f47388 100644 --- a/core/src/test/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSourceTests.java +++ b/core/src/test/java/org/springframework/security/intercept/web/DefaultFilterInvocationDefinitionSourceTests.java @@ -24,9 +24,9 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.ConfigAttribute; -import org.springframework.security.MockFilterChain; import org.springframework.security.SecurityConfig; import org.springframework.security.util.AntUrlPathMatcher; +import org.springframework.security.util.MockFilterChain; /** * Tests parts of {@link DefaultFilterInvocationDefinitionSource} not tested by {@link @@ -137,7 +137,7 @@ public class DefaultFilterInvocationDefinitionSourceTests { List attrs = fids.getAttributes(fi); assertEquals(def, attrs); } - + @Test public void requestWithDifferentHttpMethodDoesntMatch() { createFids("/somepage**", "GET"); diff --git a/core/src/test/java/org/springframework/security/intercept/web/FilterInvocationTests.java b/core/src/test/java/org/springframework/security/intercept/web/FilterInvocationTests.java index 2a9849ef24..e58f63cb83 100644 --- a/core/src/test/java/org/springframework/security/intercept/web/FilterInvocationTests.java +++ b/core/src/test/java/org/springframework/security/intercept/web/FilterInvocationTests.java @@ -17,12 +17,11 @@ package org.springframework.security.intercept.web; import static org.junit.Assert.*; -import org.springframework.security.MockFilterChain; - import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.util.MockFilterChain; /** * Tests {@link FilterInvocation}. diff --git a/core/src/test/java/org/springframework/security/intercept/web/RequestKeyTests.java b/core/src/test/java/org/springframework/security/intercept/web/RequestKeyTests.java index a1877aacff..7c253a7ea2 100644 --- a/core/src/test/java/org/springframework/security/intercept/web/RequestKeyTests.java +++ b/core/src/test/java/org/springframework/security/intercept/web/RequestKeyTests.java @@ -11,41 +11,41 @@ import org.junit.Test; * */ public class RequestKeyTests { - - @Test - public void equalsWorksWithNullHttpMethod() { - RequestKey key1 = new RequestKey("/someurl"); - RequestKey key2 = new RequestKey("/someurl"); - - assertEquals(key1, key2); - key1 = new RequestKey("/someurl","GET"); - assertFalse(key1.equals(key2)); - assertFalse(key2.equals(key1)); - } + + @Test + public void equalsWorksWithNullHttpMethod() { + RequestKey key1 = new RequestKey("/someurl"); + RequestKey key2 = new RequestKey("/someurl"); + + assertEquals(key1, key2); + key1 = new RequestKey("/someurl","GET"); + assertFalse(key1.equals(key2)); + assertFalse(key2.equals(key1)); + } - @Test - public void keysWithSameUrlAndHttpMethodAreEqual() { - RequestKey key1 = new RequestKey("/someurl", "GET"); - RequestKey key2 = new RequestKey("/someurl", "GET"); - - assertEquals(key1, key2); - } + @Test + public void keysWithSameUrlAndHttpMethodAreEqual() { + RequestKey key1 = new RequestKey("/someurl", "GET"); + RequestKey key2 = new RequestKey("/someurl", "GET"); + + assertEquals(key1, key2); + } - @Test - public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() { - RequestKey key1 = new RequestKey("/someurl", "GET"); - RequestKey key2 = new RequestKey("/someurl", "POST"); - - assertFalse(key1.equals(key2)); - assertFalse(key2.equals(key1)); - } + @Test + public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() { + RequestKey key1 = new RequestKey("/someurl", "GET"); + RequestKey key2 = new RequestKey("/someurl", "POST"); + + assertFalse(key1.equals(key2)); + assertFalse(key2.equals(key1)); + } - @Test - public void keysWithDifferentUrlsAreNotEquals() { - RequestKey key1 = new RequestKey("/someurl", "GET"); - RequestKey key2 = new RequestKey("/anotherurl", "GET"); - - assertFalse(key1.equals(key2)); - assertFalse(key2.equals(key1)); - } + @Test + public void keysWithDifferentUrlsAreNotEquals() { + RequestKey key1 = new RequestKey("/someurl", "GET"); + RequestKey key2 = new RequestKey("/anotherurl", "GET"); + + assertFalse(key1.equals(key2)); + assertFalse(key2.equals(key1)); + } } diff --git a/core/src/test/java/org/springframework/security/intercept/web/WebInvocationPrivilegeEvaluatorTests.java b/core/src/test/java/org/springframework/security/intercept/web/WebInvocationPrivilegeEvaluatorTests.java index 22b6b5786c..4a8303cdbe 100644 --- a/core/src/test/java/org/springframework/security/intercept/web/WebInvocationPrivilegeEvaluatorTests.java +++ b/core/src/test/java/org/springframework/security/intercept/web/WebInvocationPrivilegeEvaluatorTests.java @@ -74,6 +74,7 @@ public class WebInvocationPrivilegeEvaluatorTests { SecurityContextHolder.clearContext(); } + @SuppressWarnings("unchecked") @Test public void allowsAccessIfAccessDecisionMangerDoes() throws Exception { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); @@ -92,6 +93,7 @@ public class WebInvocationPrivilegeEvaluatorTests { jmock.assertIsSatisfied(); } + @SuppressWarnings("unchecked") @Test public void deniesAccessIfAccessDecisionMangerDoes() throws Exception { Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX"); diff --git a/core/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java b/core/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java index 6abefe6f74..929f52cd78 100644 --- a/core/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java +++ b/core/src/test/java/org/springframework/security/ldap/LdapUtilsTests.java @@ -15,7 +15,10 @@ package org.springframework.security.ldap; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; import org.jmock.Expectations; import org.jmock.Mockery; @@ -24,10 +27,6 @@ import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - /** * Tests {@link LdapUtils} diff --git a/core/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java b/core/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java index 7e67818f60..44a17eaa4d 100644 --- a/core/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java +++ b/core/src/test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateTests.java @@ -15,12 +15,6 @@ package org.springframework.security.ldap; -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.ldap.core.ContextExecutor; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapEncoder; -import org.junit.Test; import static org.junit.Assert.*; import java.util.Set; @@ -29,7 +23,11 @@ import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.SearchControls; -import javax.naming.ldap.LdapName; +import javax.naming.directory.SearchResult; + +import org.junit.Test; +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.ldap.core.ContextExecutor; /** * @author Luke Taylor @@ -94,7 +92,7 @@ public class SpringSecurityLdapTemplateTests extends AbstractLdapIntegrationTest public void roleSearchReturnsCorrectNumberOfRoles() { String param = "uid=ben,ou=people,dc=springframework,dc=org"; - Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "ou"); + Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "ou"); assertEquals("Expected 3 results from search", 3, values.size()); assertTrue(values.contains("developer")); @@ -106,48 +104,48 @@ public class SpringSecurityLdapTemplateTests extends AbstractLdapIntegrationTest public void testRoleSearchForMissingAttributeFailsGracefully() { String param = "uid=ben,ou=people,dc=springframework,dc=org"; - Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "mail"); + Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "mail"); assertEquals(0, values.size()); } @Test public void roleSearchWithEscapedCharacterSucceeds() throws Exception { - String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"; - - Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "cn"); + String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"; + + Set values = template.searchForSingleAttributeValues("ou=groups", "(member={0})", new String[] {param}, "cn"); assertEquals(1, values.size()); } - + @Test public void nonSpringLdapSearchCodeTestMethod() throws Exception { - java.util.Hashtable env = new java.util.Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); - env.put(Context.PROVIDER_URL, "ldap://localhost:53389"); - env.put(Context.SECURITY_PRINCIPAL, ""); - env.put(Context.SECURITY_CREDENTIALS, ""); + java.util.Hashtable env = new java.util.Hashtable(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, "ldap://localhost:53389"); + env.put(Context.SECURITY_PRINCIPAL, ""); + env.put(Context.SECURITY_CREDENTIALS, ""); - DirContext ctx = new javax.naming.directory.InitialDirContext(env); - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.SUBTREE_SCOPE); - controls.setReturningObjFlag(true); - controls.setReturningAttributes(null); - String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"; - - javax.naming.NamingEnumeration results = - ctx.search("ou=groups,dc=springframework,dc=org", - "(member={0})", new String[] {param}, - controls); - - assertTrue("Expected a result", results.hasMore()); + DirContext ctx = new javax.naming.directory.InitialDirContext(env); + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.SUBTREE_SCOPE); + controls.setReturningObjFlag(true); + controls.setReturningAttributes(null); + String param = "cn=mouse\\, jerry,ou=people,dc=springframework,dc=org"; + + javax.naming.NamingEnumeration results = + ctx.search("ou=groups,dc=springframework,dc=org", + "(member={0})", new String[] {param}, + controls); + + assertTrue("Expected a result", results.hasMore()); } @Test public void searchForSingleEntryWithEscapedCharsInDnSucceeds() { String param = "mouse, jerry"; - DirContextOperations jerry = template.searchForSingleEntry("ou=people", "(cn={0})", new String[] {param}); + template.searchForSingleEntry("ou=people", "(cn={0})", new String[] {param}); } - + } diff --git a/core/src/test/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulatorTests.java b/core/src/test/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulatorTests.java index 3a1684e381..2a600763e3 100644 --- a/core/src/test/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulatorTests.java +++ b/core/src/test/java/org/springframework/security/ldap/populator/DefaultLdapAuthoritiesPopulatorTests.java @@ -44,7 +44,6 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio super.onSetUp(); populator = new DefaultLdapAuthoritiesPopulator(getContextSource(), "ou=groups"); - } @Test @@ -74,7 +73,7 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio assertEquals("Should have 2 roles", 2, authorities.size()); - Set roles = new HashSet(); + Set roles = new HashSet(); roles.add(authorities.get(0).toString()); roles.add(authorities.get(1).toString()); assertTrue(roles.contains("ROLE_DEVELOPER")); @@ -105,7 +104,7 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio List authorities = populator.getGrantedAuthorities(ctx, "manager"); assertEquals("Should have 2 roles", 2, authorities.size()); - Set roles = new HashSet(2); + Set roles = new HashSet(2); roles.add(authorities.get(0).getAuthority()); roles.add(authorities.get(1).getAuthority()); assertTrue(roles.contains("ROLE_MANAGER")); @@ -123,7 +122,7 @@ public class DefaultLdapAuthoritiesPopulatorTests extends AbstractLdapIntegratio List authorities = populator.getGrantedAuthorities(ctx, "manager"); assertEquals("Should have 3 roles", 3, authorities.size()); - Set roles = new HashSet(3); + Set roles = new HashSet(3); roles.add(authorities.get(0).getAuthority()); roles.add(authorities.get(1).getAuthority()); roles.add(authorities.get(2).getAuthority()); diff --git a/core/src/test/java/org/springframework/security/matcher/AuthenticationMatcher.java b/core/src/test/java/org/springframework/security/matcher/AuthenticationMatcher.java index 826aee6cac..1cf86bdd94 100644 --- a/core/src/test/java/org/springframework/security/matcher/AuthenticationMatcher.java +++ b/core/src/test/java/org/springframework/security/matcher/AuthenticationMatcher.java @@ -9,7 +9,6 @@ import org.springframework.security.Authentication; public class AuthenticationMatcher extends TypeSafeMatcher { private String username; private String password; - private String[] authorities; @Override public boolean matchesSafely(Authentication auth) { @@ -46,6 +45,4 @@ public class AuthenticationMatcher extends TypeSafeMatcher { return matcher; } - - } diff --git a/core/src/test/java/org/springframework/security/providers/AbstractAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/AbstractAuthenticationTokenTests.java index 593a109d89..583a4c30c2 100644 --- a/core/src/test/java/org/springframework/security/providers/AbstractAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/providers/AbstractAuthenticationTokenTests.java @@ -19,8 +19,6 @@ import static org.junit.Assert.*; import java.util.List; -import junit.framework.TestCase; - import org.junit.Before; import org.junit.Test; import org.springframework.security.GrantedAuthority; diff --git a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProviderTests.java index 706ba6d4fe..8f4ff70cc6 100644 --- a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationProviderTests.java @@ -23,6 +23,7 @@ import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.TestingAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** @@ -32,14 +33,6 @@ import org.springframework.security.providers.TestingAuthenticationToken; * @version $Id$ */ public class AnonymousAuthenticationProviderTests extends TestCase { - //~ Constructors =================================================================================================== - - public AnonymousAuthenticationProviderTests() { - } - - public AnonymousAuthenticationProviderTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== @@ -48,10 +41,10 @@ public class AnonymousAuthenticationProviderTests extends TestCase { aap.setKey("qwerty"); AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); try { - Authentication result = aap.authenticate(token); + aap.authenticate(token); fail("Should have thrown BadCredentialsException"); } catch (BadCredentialsException expected) { } @@ -92,7 +85,7 @@ public class AnonymousAuthenticationProviderTests extends TestCase { aap.setKey("qwerty"); AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("qwerty", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); Authentication result = aap.authenticate(token); diff --git a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java index 868611a213..4e8d664310 100644 --- a/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/providers/anonymous/AnonymousAuthenticationTokenTests.java @@ -20,7 +20,6 @@ import java.util.List; import junit.framework.TestCase; import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.util.AuthorityUtils; @@ -51,7 +50,7 @@ public class AnonymousAuthenticationTokenTests extends TestCase { } try { - new AnonymousAuthenticationToken("key", "Test", new GrantedAuthority[] {null}); + new AnonymousAuthenticationToken("key", "Test", (List)null); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } diff --git a/core/src/test/java/org/springframework/security/providers/dao/DaoAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/providers/dao/DaoAuthenticationProviderTests.java index 27a280bc22..ae142cfa6e 100644 --- a/core/src/test/java/org/springframework/security/providers/dao/DaoAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/providers/dao/DaoAuthenticationProviderTests.java @@ -15,6 +15,8 @@ package org.springframework.security.providers.dao; +import java.util.List; + import junit.framework.TestCase; import org.springframework.security.AccountExpiredException; @@ -24,7 +26,6 @@ import org.springframework.security.BadCredentialsException; import org.springframework.security.CredentialsExpiredException; import org.springframework.security.DisabledException; import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.LockedException; import org.springframework.security.providers.TestingAuthenticationToken; @@ -38,12 +39,12 @@ import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; +import org.springframework.security.util.AuthorityUtils; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataRetrievalFailureException; - /** * Tests {@link DaoAuthenticationProvider}. * @@ -51,6 +52,9 @@ import org.springframework.dao.DataRetrievalFailureException; * @version $Id$ */ public class DaoAuthenticationProviderTests extends TestCase { + private static final List ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); + + //~ Methods ======================================================================================================== public void testAuthenticateFailsForIncorrectPasswordCase() { @@ -458,8 +462,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("rod".equals(username)) { - return new User("rod", password, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("rod", password, true, true, true, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } @@ -474,8 +477,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("rod".equals(username)) { - return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("rod", "koala{SYSTEM_SALT_VALUE}", true, true, true, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } @@ -486,8 +488,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("peter".equals(username)) { - return new User("peter", "opal", false, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("peter", "opal", false, true, true, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } @@ -498,8 +499,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("peter".equals(username)) { - return new User("peter", "opal", true, false, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("peter", "opal", true, false, true, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } @@ -510,8 +510,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("peter".equals(username)) { - return new User("peter", "opal", true, true, true, false, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("peter", "opal", true, true, true, false, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } @@ -522,8 +521,7 @@ public class DaoAuthenticationProviderTests extends TestCase { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { if ("peter".equals(username)) { - return new User("peter", "opal", true, true, false, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + return new User("peter", "opal", true, true, false, true, ROLES_12); } else { throw new UsernameNotFoundException("Could not find: " + username); } diff --git a/core/src/test/java/org/springframework/security/providers/dao/MockUserCache.java b/core/src/test/java/org/springframework/security/providers/dao/MockUserCache.java index 37209234a2..bdf9a329c3 100644 --- a/core/src/test/java/org/springframework/security/providers/dao/MockUserCache.java +++ b/core/src/test/java/org/springframework/security/providers/dao/MockUserCache.java @@ -1,5 +1,5 @@ /** - * + * */ package org.springframework.security.providers.dao; @@ -10,7 +10,7 @@ import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; public class MockUserCache implements UserCache { - private Map cache = new HashMap(); + private Map cache = new HashMap(); public UserDetails getUserFromCache(String username) { return (User) cache.get(username); @@ -21,6 +21,6 @@ public class MockUserCache implements UserCache { } public void removeUserFromCache(String username) { - cache.remove(username); + cache.remove(username); } -} \ No newline at end of file +} diff --git a/core/src/test/java/org/springframework/security/providers/dao/cache/EhCacheBasedUserCacheTests.java b/core/src/test/java/org/springframework/security/providers/dao/cache/EhCacheBasedUserCacheTests.java index 33210aea30..c42823feb4 100644 --- a/core/src/test/java/org/springframework/security/providers/dao/cache/EhCacheBasedUserCacheTests.java +++ b/core/src/test/java/org/springframework/security/providers/dao/cache/EhCacheBasedUserCacheTests.java @@ -16,19 +16,16 @@ package org.springframework.security.providers.dao.cache; -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Cache; - -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; - -import org.springframework.security.userdetails.User; - -import org.junit.BeforeClass; -import org.junit.AfterClass; -import org.junit.Test; import static org.junit.Assert.*; +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.security.userdetails.User; +import org.springframework.security.util.AuthorityUtils; /** * Tests {@link EhCacheBasedUserCache}. @@ -61,7 +58,7 @@ public class EhCacheBasedUserCacheTests { private User getUser() { return new User("john", "password", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } @Test diff --git a/core/src/test/java/org/springframework/security/providers/dao/cache/NullUserCacheTests.java b/core/src/test/java/org/springframework/security/providers/dao/cache/NullUserCacheTests.java index d2c9191a82..556e93c616 100644 --- a/core/src/test/java/org/springframework/security/providers/dao/cache/NullUserCacheTests.java +++ b/core/src/test/java/org/springframework/security/providers/dao/cache/NullUserCacheTests.java @@ -17,10 +17,8 @@ package org.springframework.security.providers.dao.cache; import junit.framework.TestCase; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; - import org.springframework.security.userdetails.User; +import org.springframework.security.util.AuthorityUtils; /** @@ -30,29 +28,12 @@ import org.springframework.security.userdetails.User; * @version $Id$ */ public class NullUserCacheTests extends TestCase { - //~ Constructors =================================================================================================== - - public NullUserCacheTests() { - super(); - } - - public NullUserCacheTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== private User getUser() { return new User("john", "password", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(NullUserCacheTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } public void testCacheOperation() throws Exception { diff --git a/core/src/test/java/org/springframework/security/providers/dao/salt/ReflectionSaltSourceTests.java b/core/src/test/java/org/springframework/security/providers/dao/salt/ReflectionSaltSourceTests.java index 69d42d0e10..ca0571a99a 100644 --- a/core/src/test/java/org/springframework/security/providers/dao/salt/ReflectionSaltSourceTests.java +++ b/core/src/test/java/org/springframework/security/providers/dao/salt/ReflectionSaltSourceTests.java @@ -15,15 +15,13 @@ package org.springframework.security.providers.dao.salt; -import org.springframework.security.AuthenticationServiceException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; - -import org.springframework.security.userdetails.User; -import org.springframework.security.userdetails.UserDetails; +import static junit.framework.Assert.assertEquals; import org.junit.Test; -import static junit.framework.Assert.*; +import org.springframework.security.AuthenticationServiceException; +import org.springframework.security.userdetails.User; +import org.springframework.security.userdetails.UserDetails; +import org.springframework.security.util.AuthorityUtils; /** * Tests {@link ReflectionSaltSource}. @@ -33,7 +31,7 @@ import static junit.framework.Assert.*; */ public class ReflectionSaltSourceTests { private UserDetails user = new User("scott", "wombat", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("HOLDER")}); + AuthorityUtils.createAuthorityList("HOLDER")); //~ Methods ======================================================================================================== diff --git a/core/src/test/java/org/springframework/security/providers/encoding/Md4PasswordEncoderTests.java b/core/src/test/java/org/springframework/security/providers/encoding/Md4PasswordEncoderTests.java index e87b651435..8c47d29599 100644 --- a/core/src/test/java/org/springframework/security/providers/encoding/Md4PasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/providers/encoding/Md4PasswordEncoderTests.java @@ -18,54 +18,54 @@ import junit.framework.TestCase; public class Md4PasswordEncoderTests extends TestCase { - public void testEncodeUnsaltedPassword() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - String encodedPassword = md4.encodePassword("ww_uni123", null); - assertEquals("8zobtq72iAt0W6KNqavGwg==", encodedPassword); - } + public void testEncodeUnsaltedPassword() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + String encodedPassword = md4.encodePassword("ww_uni123", null); + assertEquals("8zobtq72iAt0W6KNqavGwg==", encodedPassword); + } - public void testEncodeSaltedPassword() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - String encodedPassword = md4.encodePassword("ww_uni123", "Alan K Stewart"); - assertEquals("ZplT6P5Kv6Rlu6W4FIoYNA==", encodedPassword); - } + public void testEncodeSaltedPassword() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + String encodedPassword = md4.encodePassword("ww_uni123", "Alan K Stewart"); + assertEquals("ZplT6P5Kv6Rlu6W4FIoYNA==", encodedPassword); + } - public void testEncodeNullPassword() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - String encodedPassword = md4.encodePassword(null, null); - assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); - } + public void testEncodeNullPassword() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + String encodedPassword = md4.encodePassword(null, null); + assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); + } - public void testEncodeEmptyPassword() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - String encodedPassword = md4.encodePassword("", null); - assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); - } - - public void testNonAsciiPasswordHasCorrectHash() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - String encodedPassword = md4.encodePassword("\u4F60\u597d", null); - assertEquals("a7f1196539fd1f85f754ffd185b16e6e", encodedPassword); - } + public void testEncodeEmptyPassword() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + String encodedPassword = md4.encodePassword("", null); + assertEquals("MdbP4NFq6TG3PFnX4MCJwA==", encodedPassword); + } + + public void testNonAsciiPasswordHasCorrectHash() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + String encodedPassword = md4.encodePassword("\u4F60\u597d", null); + assertEquals("a7f1196539fd1f85f754ffd185b16e6e", encodedPassword); + } - public void testIsHexPasswordValid() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - assertTrue(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)); - } + public void testIsHexPasswordValid() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + assertTrue(md4.isPasswordValid("31d6cfe0d16ae931b73c59d7e0c089c0", "", null)); + } - public void testIsPasswordValid() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - assertTrue(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)); - } + public void testIsPasswordValid() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + assertTrue(md4.isPasswordValid("8zobtq72iAt0W6KNqavGwg==", "ww_uni123", null)); + } - public void testIsSaltedPasswordValid() { - Md4PasswordEncoder md4 = new Md4PasswordEncoder(); - md4.setEncodeHashAsBase64(true); - assertTrue(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123", "Alan K Stewart")); - } + public void testIsSaltedPasswordValid() { + Md4PasswordEncoder md4 = new Md4PasswordEncoder(); + md4.setEncodeHashAsBase64(true); + assertTrue(md4.isPasswordValid("ZplT6P5Kv6Rlu6W4FIoYNA==", "ww_uni123", "Alan K Stewart")); + } } diff --git a/core/src/test/java/org/springframework/security/providers/encoding/Md5PasswordEncoderTests.java b/core/src/test/java/org/springframework/security/providers/encoding/Md5PasswordEncoderTests.java index 0a97374714..64af137cf7 100644 --- a/core/src/test/java/org/springframework/security/providers/encoding/Md5PasswordEncoderTests.java +++ b/core/src/test/java/org/springframework/security/providers/encoding/Md5PasswordEncoderTests.java @@ -41,11 +41,11 @@ public class Md5PasswordEncoderTests extends TestCase { assertEquals("MD5", pe.getAlgorithm()); } - public void testNonAsciiPasswordHasCorrectHash() { - Md5PasswordEncoder md5 = new Md5PasswordEncoder(); - String encodedPassword = md5.encodePassword("\u4F60\u597d", null); - assertEquals("7eca689f0d3389d9dea66ae112e5cfd7", encodedPassword); - } + public void testNonAsciiPasswordHasCorrectHash() { + Md5PasswordEncoder md5 = new Md5PasswordEncoder(); + String encodedPassword = md5.encodePassword("\u4F60\u597d", null); + assertEquals("7eca689f0d3389d9dea66ae112e5cfd7", encodedPassword); + } public void testBase64() throws Exception { Md5PasswordEncoder pe = new Md5PasswordEncoder(); diff --git a/core/src/test/java/org/springframework/security/providers/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/providers/jaas/JaasAuthenticationProviderTests.java index eb26d901ac..bb94b14326 100644 --- a/core/src/test/java/org/springframework/security/providers/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/providers/jaas/JaasAuthenticationProviderTests.java @@ -33,7 +33,7 @@ import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.LockedException; import org.springframework.security.SpringSecurityException; -import org.springframework.security.context.HttpSessionContextIntegrationFilter; +import org.springframework.security.context.HttpSessionSecurityContextRepository; import org.springframework.security.context.SecurityContextImpl; import org.springframework.security.providers.TestingAuthenticationToken; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; @@ -136,11 +136,7 @@ public class JaasAuthenticationProviderTests extends TestCase { } public void testFull() throws Exception { - GrantedAuthorityImpl role1 = new GrantedAuthorityImpl("ROLE_1"); - GrantedAuthorityImpl role2 = new GrantedAuthorityImpl("ROLE_2"); - - GrantedAuthority[] defaultAuths = new GrantedAuthority[] {role1, role2,}; - + List defaultAuths = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", defaultAuths); @@ -153,12 +149,12 @@ public class JaasAuthenticationProviderTests extends TestCase { assertNotNull(jaasProvider.getLoginConfig()); assertNotNull(jaasProvider.getLoginContextName()); - List list = auth.getAuthorities(); + List list = auth.getAuthorities(); assertTrue("GrantedAuthorities should contain ROLE_TEST1", list.contains(new GrantedAuthorityImpl("ROLE_TEST1"))); assertTrue("GrantedAuthorities should contain ROLE_TEST2", list.contains(new GrantedAuthorityImpl("ROLE_TEST2"))); - assertTrue("GrantedAuthorities should contain ROLE_1", list.contains(role1)); - assertTrue("GrantedAuthorities should contain ROLE_2", list.contains(role2)); + assertTrue("GrantedAuthorities should contain ROLE_1", list.contains(defaultAuths.get(0))); + assertTrue("GrantedAuthorities should contain ROLE_2", list.contains(defaultAuths.get(1))); boolean foundit = false; @@ -209,7 +205,7 @@ public class JaasAuthenticationProviderTests extends TestCase { context.setAuthentication(token); MockHttpSession mockSession = new MockHttpSession(); - mockSession.setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, context); + mockSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context); jaasProvider.onApplicationEvent(new HttpSessionDestroyedEvent(mockSession)); diff --git a/core/src/test/java/org/springframework/security/providers/jaas/Sec760Tests.java b/core/src/test/java/org/springframework/security/providers/jaas/Sec760Tests.java index d7901a960b..7e0acb8aad 100644 --- a/core/src/test/java/org/springframework/security/providers/jaas/Sec760Tests.java +++ b/core/src/test/java/org/springframework/security/providers/jaas/Sec760Tests.java @@ -1,64 +1,53 @@ package org.springframework.security.providers.jaas; -import java.net.URL; -import java.security.Security; - -import javax.security.auth.login.LoginContext; - import junit.framework.Assert; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.security.Authentication; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** * Tests bug reported in SEC-760. - * + * * @author Ben Alex * */ public class Sec760Tests { - public String resolveConfigFile(String filename) { + public String resolveConfigFile(String filename) { String resName = "/" + getClass().getPackage().getName().replace('.', '/') + filename; return resName; - } - - private void testConfigureJaasCase(JaasAuthenticationProvider p1, JaasAuthenticationProvider p2) throws Exception { - p1.setLoginConfig(new ClassPathResource(resolveConfigFile("/test1.conf"))); - p1.setLoginContextName("test1"); - p1.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {new TestCallbackHandler(), new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); - p1.setAuthorityGranters(new AuthorityGranter[] {new TestAuthorityGranter()}); - p1.afterPropertiesSet(); - testAuthenticate(p1); + } - p2.setLoginConfig(new ClassPathResource(resolveConfigFile("/test2.conf"))); - p2.setLoginContextName("test2"); - p2.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {new TestCallbackHandler(), new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); - p2.setAuthorityGranters(new AuthorityGranter[] {new TestAuthorityGranter()}); - p2.afterPropertiesSet(); - testAuthenticate(p2); - } - - private void testAuthenticate(JaasAuthenticationProvider p1) { - GrantedAuthorityImpl role1 = new GrantedAuthorityImpl("ROLE_1"); - GrantedAuthorityImpl role2 = new GrantedAuthorityImpl("ROLE_2"); + private void testConfigureJaasCase(JaasAuthenticationProvider p1, JaasAuthenticationProvider p2) throws Exception { + p1.setLoginConfig(new ClassPathResource(resolveConfigFile("/test1.conf"))); + p1.setLoginContextName("test1"); + p1.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {new TestCallbackHandler(), new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); + p1.setAuthorityGranters(new AuthorityGranter[] {new TestAuthorityGranter()}); + p1.afterPropertiesSet(); + testAuthenticate(p1); - GrantedAuthority[] defaultAuths = new GrantedAuthority[] {role1, role2,}; + p2.setLoginConfig(new ClassPathResource(resolveConfigFile("/test2.conf"))); + p2.setLoginContextName("test2"); + p2.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {new TestCallbackHandler(), new JaasNameCallbackHandler(), new JaasPasswordCallbackHandler()}); + p2.setAuthorityGranters(new AuthorityGranter[] {new TestAuthorityGranter()}); + p2.afterPropertiesSet(); + testAuthenticate(p2); + } + private void testAuthenticate(JaasAuthenticationProvider p1) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password", - defaultAuths); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); Authentication auth = p1.authenticate(token); - Assert.assertNotNull(auth); - } + Assert.assertNotNull(auth); + } - @Test - public void testConfigureJaas() throws Exception { - testConfigureJaasCase(new JaasAuthenticationProvider(), new JaasAuthenticationProvider()); - } + @Test + public void testConfigureJaas() throws Exception { + testConfigureJaasCase(new JaasAuthenticationProvider(), new JaasAuthenticationProvider()); + } } diff --git a/core/src/test/java/org/springframework/security/providers/jaas/SecurityContextLoginModuleTests.java b/core/src/test/java/org/springframework/security/providers/jaas/SecurityContextLoginModuleTests.java index d2d8df4a4a..a8217c9a2d 100644 --- a/core/src/test/java/org/springframework/security/providers/jaas/SecurityContextLoginModuleTests.java +++ b/core/src/test/java/org/springframework/security/providers/jaas/SecurityContextLoginModuleTests.java @@ -21,6 +21,7 @@ import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import java.security.Principal; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -38,7 +39,7 @@ public class SecurityContextLoginModuleTests extends TestCase { //~ Instance fields ================================================================================================ private SecurityContextLoginModule module = null; - private Subject subject = new Subject(false, new HashSet(), new HashSet(), new HashSet()); + private Subject subject = new Subject(false, new HashSet(), new HashSet(), new HashSet()); private UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("principal", "credentials"); @@ -87,8 +88,7 @@ public class SecurityContextLoginModuleTests extends TestCase { subject.getPrincipals().contains(auth)); } - public void testNullAuthenticationInSecurityContext() - throws Exception { + public void testNullAuthenticationInSecurityContext() throws Exception { try { SecurityContextHolder.getContext().setAuthentication(null); module.login(); @@ -96,11 +96,10 @@ public class SecurityContextLoginModuleTests extends TestCase { } catch (Exception e) {} } - public void testNullAuthenticationInSecurityContextIgnored() - throws Exception { + public void testNullAuthenticationInSecurityContextIgnored() throws Exception { module = new SecurityContextLoginModule(); - Map options = new HashMap(); + Map options = new HashMap(); options.put("ignoreMissingAuthentication", "true"); module.initialize(subject, null, null, options); diff --git a/core/src/test/java/org/springframework/security/providers/jaas/TestAuthorityGranter.java b/core/src/test/java/org/springframework/security/providers/jaas/TestAuthorityGranter.java index d96ff445a6..4ab67da87a 100644 --- a/core/src/test/java/org/springframework/security/providers/jaas/TestAuthorityGranter.java +++ b/core/src/test/java/org/springframework/security/providers/jaas/TestAuthorityGranter.java @@ -22,7 +22,6 @@ import java.util.Set; /** - * DOCUMENT ME! * * @author Ray Krueger * @version $Id$ @@ -30,8 +29,8 @@ import java.util.Set; public class TestAuthorityGranter implements AuthorityGranter { //~ Methods ======================================================================================================== - public Set grant(Principal principal) { - Set rtnSet = new HashSet(); + public Set grant(Principal principal) { + Set rtnSet = new HashSet(); if (principal.getName().equals("TEST_PRINCIPAL")) { rtnSet.add("ROLE_TEST1"); diff --git a/core/src/test/java/org/springframework/security/providers/jaas/TestLoginModule.java b/core/src/test/java/org/springframework/security/providers/jaas/TestLoginModule.java index 23e4a3c4a4..02f797fbc5 100644 --- a/core/src/test/java/org/springframework/security/providers/jaas/TestLoginModule.java +++ b/core/src/test/java/org/springframework/security/providers/jaas/TestLoginModule.java @@ -26,8 +26,6 @@ import javax.security.auth.spi.LoginModule; /** - * DOCUMENT ME! - * * @author Ray Krueger * @version $Id$ */ @@ -48,6 +46,7 @@ public class TestLoginModule implements LoginModule { return true; } + @SuppressWarnings("unchecked") public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { this.subject = subject; diff --git a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProviderTests.java index 36cae8ba9d..fa1422aba3 100755 --- a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationProviderTests.java @@ -21,7 +21,6 @@ import org.springframework.security.util.AuthorityUtils; * @since 18-okt-2007 */ public class PreAuthenticatedAuthenticationProviderTests { - private static final String SUPPORTED_USERNAME = "dummyUser"; @Test(expected = IllegalArgumentException.class) public final void afterPropertiesSet() { diff --git a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationTokenTests.java index d91cb1895b..5614dae167 100755 --- a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedAuthenticationTokenTests.java @@ -1,13 +1,12 @@ package org.springframework.security.providers.preauth; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.security.GrantedAuthority; - -import java.util.Arrays; -import java.util.Collection; +import java.util.List; import junit.framework.TestCase; +import org.springframework.security.GrantedAuthority; +import org.springframework.security.util.AuthorityUtils; + /** * * @author TSARDD @@ -40,16 +39,16 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase { public void testPreAuthenticatedAuthenticationTokenResponse() { Object principal = "dummyUser"; Object credentials = "dummyCredentials"; - GrantedAuthority[] gas = new GrantedAuthority[] { new GrantedAuthorityImpl("Role1") }; - PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials, gas); + List gas = AuthorityUtils.createAuthorityList("Role1"); + PreAuthenticatedAuthenticationToken token = + new PreAuthenticatedAuthenticationToken(principal, credentials, gas); assertEquals(principal, token.getPrincipal()); assertEquals(credentials, token.getCredentials()); assertNull(token.getDetails()); assertNotNull(token.getAuthorities()); - Collection expectedColl = Arrays.asList(gas); - Collection resultColl = token.getAuthorities(); - assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, - expectedColl.containsAll(resultColl) && resultColl.containsAll(expectedColl)); + List resultColl = token.getAuthorities(); + assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas, + gas.containsAll(resultColl) && resultColl.containsAll(gas)); } diff --git a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java index 9470c9a6c3..f3e1ea25f1 100755 --- a/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java +++ b/core/src/test/java/org/springframework/security/providers/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java @@ -1,10 +1,7 @@ package org.springframework.security.providers.preauth; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import java.util.Arrays; -import java.util.Collection; import java.util.List; import org.junit.Test; @@ -67,11 +64,8 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests { // PreAuthenticatedGrantedAuthoritiesUserDetailsService //assertEquals(ud.getPassword(),password); - Collection expectedColl = Arrays.asList(gas); - Collection resultColl = Arrays.asList(ud.getAuthorities()); - assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + expectedColl, expectedColl - .containsAll(resultColl) - && resultColl.containsAll(expectedColl)); + assertTrue("GrantedAuthority collections do not match; result: " + ud.getAuthorities() + ", expected: " + gas, + gas.containsAll(ud.getAuthorities()) && ud.getAuthorities().containsAll(gas)); } } diff --git a/core/src/test/java/org/springframework/security/providers/preauth/UserDetailsByNameServiceWrapperTests.java b/core/src/test/java/org/springframework/security/providers/preauth/UserDetailsByNameServiceWrapperTests.java index c009440b10..18a06a7198 100755 --- a/core/src/test/java/org/springframework/security/providers/preauth/UserDetailsByNameServiceWrapperTests.java +++ b/core/src/test/java/org/springframework/security/providers/preauth/UserDetailsByNameServiceWrapperTests.java @@ -1,52 +1,50 @@ package org.springframework.security.providers.preauth; -import org.springframework.security.userdetails.UserDetails; -import org.springframework.security.userdetails.UserDetailsByNameServiceWrapper; -import org.springframework.security.userdetails.UsernameNotFoundException; -import org.springframework.security.userdetails.UserDetailsService; -import org.springframework.security.userdetails.User; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.security.GrantedAuthority; - import junit.framework.TestCase; import org.springframework.dao.DataAccessException; +import org.springframework.security.userdetails.User; +import org.springframework.security.userdetails.UserDetails; +import org.springframework.security.userdetails.UserDetailsByNameServiceWrapper; +import org.springframework.security.userdetails.UserDetailsService; +import org.springframework.security.userdetails.UsernameNotFoundException; +import org.springframework.security.util.AuthorityUtils; /** - * + * * @author TSARDD * @since 18-okt-2007 */ public class UserDetailsByNameServiceWrapperTests extends TestCase { - 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"); - } - } + 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"); + } + } - public final void testGetUserDetails() throws Exception { - UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); - final User user = new User("dummy", "dummy", true, true, true, true, new GrantedAuthority[] { new GrantedAuthorityImpl("dummy") }); - svc.setUserDetailsService(new UserDetailsService() { - public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException { - if (user != null && user.getUsername().equals(name)) { - return user; - } else { - return null; - } - } - }); - svc.afterPropertiesSet(); - UserDetails result1 = svc.loadUserDetails(new PreAuthenticatedAuthenticationToken("dummy", "dummy")); - assertEquals("Result doesn't match original user", user, result1); - UserDetails result2 = svc.loadUserDetails(new PreAuthenticatedAuthenticationToken("dummy2", "dummy")); - assertNull("Result should have been null", result2); - } + public final void testGetUserDetails() throws Exception { + UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); + final User user = new User("dummy", "dummy", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); + svc.setUserDetailsService(new UserDetailsService() { + public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException { + if (user != null && user.getUsername().equals(name)) { + return user; + } else { + return null; + } + } + }); + svc.afterPropertiesSet(); + UserDetails result1 = svc.loadUserDetails(new PreAuthenticatedAuthenticationToken("dummy", "dummy")); + assertEquals("Result doesn't match original user", user, result1); + UserDetails result2 = svc.loadUserDetails(new PreAuthenticatedAuthenticationToken("dummy2", "dummy")); + assertNull("Result should have been null", result2); + } } diff --git a/core/src/test/java/org/springframework/security/providers/rcp/RemoteAuthenticationManagerImplTests.java b/core/src/test/java/org/springframework/security/providers/rcp/RemoteAuthenticationManagerImplTests.java index bb073178de..1899d255f2 100644 --- a/core/src/test/java/org/springframework/security/providers/rcp/RemoteAuthenticationManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/providers/rcp/RemoteAuthenticationManagerImplTests.java @@ -17,7 +17,6 @@ package org.springframework.security.providers.rcp; import junit.framework.TestCase; -import org.springframework.security.GrantedAuthority; import org.springframework.security.MockAuthenticationManager; @@ -30,14 +29,6 @@ import org.springframework.security.MockAuthenticationManager; public class RemoteAuthenticationManagerImplTests extends TestCase { //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(RemoteAuthenticationManagerImplTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testFailedAuthenticationReturnsRemoteAuthenticationException() { RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); manager.setAuthenticationManager(new MockAuthenticationManager(false)); @@ -75,7 +66,6 @@ public class RemoteAuthenticationManagerImplTests extends TestCase { RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); manager.setAuthenticationManager(new MockAuthenticationManager(true)); - GrantedAuthority[] result = manager.attemptAuthentication("rod", "password"); - assertTrue(true); + manager.attemptAuthentication("rod", "password"); } } diff --git a/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProviderTests.java index 814ca118bb..39ab8f2317 100644 --- a/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationProviderTests.java @@ -19,10 +19,8 @@ import junit.framework.TestCase; import org.springframework.security.Authentication; import org.springframework.security.BadCredentialsException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; - import org.springframework.security.providers.TestingAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** @@ -32,15 +30,6 @@ import org.springframework.security.providers.TestingAuthenticationToken; * @version $Id$ */ public class RememberMeAuthenticationProviderTests extends TestCase { - //~ Constructors =================================================================================================== - - public RememberMeAuthenticationProviderTests() { - } - - public RememberMeAuthenticationProviderTests(String arg0) { - super(arg0); - } - //~ Methods ======================================================================================================== public void testDetectsAnInvalidKey() throws Exception { @@ -48,10 +37,10 @@ public class RememberMeAuthenticationProviderTests extends TestCase { aap.setKey("qwerty"); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); try { - Authentication result = aap.authenticate(token); + aap.authenticate(token); fail("Should have thrown BadCredentialsException"); } catch (BadCredentialsException expected) { } @@ -91,7 +80,7 @@ public class RememberMeAuthenticationProviderTests extends TestCase { aap.setKey("qwerty"); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("qwerty", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); Authentication result = aap.authenticate(token); diff --git a/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationTokenTests.java b/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationTokenTests.java index 1cbe14ec12..c71e51a541 100644 --- a/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationTokenTests.java +++ b/core/src/test/java/org/springframework/security/providers/rememberme/RememberMeAuthenticationTokenTests.java @@ -15,12 +15,14 @@ package org.springframework.security.providers.rememberme; +import java.util.ArrayList; +import java.util.List; + import junit.framework.TestCase; import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; - +import org.springframework.security.util.AuthorityUtils; /** * Tests {@link RememberMeAuthenticationToken}. @@ -29,45 +31,29 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke * @version $Id$ */ public class RememberMeAuthenticationTokenTests extends TestCase { - //~ Constructors =================================================================================================== - - public RememberMeAuthenticationTokenTests() { - super(); - } - - public RememberMeAuthenticationTokenTests(String arg0) { - super(arg0); - } + private static final List ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(RememberMeAuthenticationTokenTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testConstructorRejectsNulls() { try { - new RememberMeAuthenticationToken(null, "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + new RememberMeAuthenticationToken(null, "Test", ROLES_12); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); } try { - new RememberMeAuthenticationToken("key", null, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + new RememberMeAuthenticationToken("key", null, ROLES_12); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); } try { - new RememberMeAuthenticationToken("key", "Test", new GrantedAuthority[] {null}); + List authsContainingNull = new ArrayList(); + authsContainingNull.add(null); + new RememberMeAuthenticationToken("key", "Test", authsContainingNull); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -75,18 +61,15 @@ public class RememberMeAuthenticationTokenTests extends TestCase { } public void testEqualsWhenEqual() { - RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); - - RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); + RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); assertEquals(token1, token2); } public void testGetters() { RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + ROLES_12); assertEquals("key".hashCode(), token.getKeyHash()); assertEquals("Test", token.getPrincipal()); @@ -97,38 +80,28 @@ public class RememberMeAuthenticationTokenTests extends TestCase { } public void testNotEqualsDueToAbstractParentEqualsCheck() { - RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); - - RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "DIFFERENT_PRINCIPAL", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test",ROLES_12); + RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("key", "DIFFERENT_PRINCIPAL",ROLES_12); assertFalse(token1.equals(token2)); } public void testNotEqualsDueToDifferentAuthenticationClass() { - RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); - - UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); + UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",ROLES_12); assertFalse(token1.equals(token2)); } public void testNotEqualsDueToKey() { - RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); - - RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("DIFFERENT_KEY", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + RememberMeAuthenticationToken token1 = new RememberMeAuthenticationToken("key", "Test", ROLES_12); + RememberMeAuthenticationToken token2 = new RememberMeAuthenticationToken("DIFFERENT_KEY", "Test", ROLES_12); assertFalse(token1.equals(token2)); } public void testSetAuthenticatedIgnored() { - RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("key", "Test", ROLES_12); assertTrue(token.isAuthenticated()); token.setAuthenticated(false); assertTrue(!token.isAuthenticated()); diff --git a/core/src/test/java/org/springframework/security/runas/RunAsManagerImplTests.java b/core/src/test/java/org/springframework/security/runas/RunAsManagerImplTests.java index 0d1fbf365c..9b38e21f90 100644 --- a/core/src/test/java/org/springframework/security/runas/RunAsManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/runas/RunAsManagerImplTests.java @@ -18,11 +18,10 @@ package org.springframework.security.runas; import junit.framework.TestCase; import org.springframework.security.Authentication; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.RunAsManager; import org.springframework.security.SecurityConfig; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** @@ -39,7 +38,7 @@ public class RunAsManagerImplTests extends TestCase { public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); @@ -50,7 +49,7 @@ public class RunAsManagerImplTests extends TestCase { public void testRespectsRolePrefix() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ONE"), new GrantedAuthorityImpl("TWO")}); + AuthorityUtils.createAuthorityList("ONE", "TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); @@ -58,10 +57,7 @@ public class RunAsManagerImplTests extends TestCase { Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); - if (!(resultingToken instanceof RunAsUserToken)) { - fail("Should have returned a RunAsUserToken"); - } - + assertTrue("Should have returned a RunAsUserToken", resultingToken instanceof RunAsUserToken); assertEquals(inputToken.getPrincipal(), resultingToken.getPrincipal()); assertEquals(inputToken.getCredentials(), resultingToken.getCredentials()); assertEquals("FOOBAR_RUN_AS_SOMETHING", resultingToken.getAuthorities().get(0).getAuthority()); @@ -74,7 +70,7 @@ public class RunAsManagerImplTests extends TestCase { public void testReturnsAdditionalGrantedAuthorities() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken("Test", "Password", - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); diff --git a/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java b/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java index d1be400bae..7054281d30 100644 --- a/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/ChannelDecisionManagerImplTests.java @@ -18,10 +18,10 @@ package org.springframework.security.securechannel; import junit.framework.TestCase; import org.springframework.security.ConfigAttribute; -import org.springframework.security.MockFilterChain; import org.springframework.security.SecurityConfig; import org.springframework.security.intercept.web.FilterInvocation; +import org.springframework.security.util.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -50,6 +50,7 @@ public class ChannelDecisionManagerImplTests extends TestCase { try { cdm.setChannelProcessors(new Vector()); + cdm.afterPropertiesSet(); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertEquals("A list of ChannelProcessors is required", expected.getMessage()); @@ -74,6 +75,7 @@ public class ChannelDecisionManagerImplTests extends TestCase { try { cdm.setChannelProcessors(null); + cdm.afterPropertiesSet(); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertEquals("A list of ChannelProcessors is required", expected.getMessage()); diff --git a/core/src/test/java/org/springframework/security/securechannel/ChannelProcessingFilterTests.java b/core/src/test/java/org/springframework/security/securechannel/ChannelProcessingFilterTests.java index 40c65fda4b..50b6d06eaa 100644 --- a/core/src/test/java/org/springframework/security/securechannel/ChannelProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/ChannelProcessingFilterTests.java @@ -19,10 +19,7 @@ import java.io.IOException; import java.util.Collection; import java.util.List; -import javax.servlet.FilterChain; import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; import junit.framework.TestCase; @@ -32,6 +29,7 @@ import org.springframework.security.ConfigAttribute; import org.springframework.security.SecurityConfig; import org.springframework.security.intercept.web.FilterInvocation; import org.springframework.security.intercept.web.FilterInvocationDefinitionSource; +import org.springframework.security.util.MockFilterChain; /** @@ -199,27 +197,6 @@ public class ChannelProcessingFilterTests extends TestCase { } } - private class MockFilterChain implements FilterChain { - private boolean expectToProceed; - - public MockFilterChain(boolean expectToProceed) { - this.expectToProceed = expectToProceed; - } - - private MockFilterChain() { - super(); - } - - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - if (expectToProceed) { - assertTrue(true); - } else { - fail("Did not expect filter chain to proceed"); - } - } - } - private class MockFilterInvocationDefinitionMap implements FilterInvocationDefinitionSource { private List toReturn; private String servletPath; diff --git a/core/src/test/java/org/springframework/security/securechannel/InsecureChannelProcessorTests.java b/core/src/test/java/org/springframework/security/securechannel/InsecureChannelProcessorTests.java index f9948fd780..e3dd36d28f 100644 --- a/core/src/test/java/org/springframework/security/securechannel/InsecureChannelProcessorTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/InsecureChannelProcessorTests.java @@ -19,9 +19,9 @@ import junit.framework.TestCase; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.MockFilterChain; import org.springframework.security.SecurityConfig; import org.springframework.security.intercept.web.FilterInvocation; +import org.springframework.security.util.MockFilterChain; /** diff --git a/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpEntryPointTests.java b/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpEntryPointTests.java index 933c40e8cf..d8e6431f28 100644 --- a/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpEntryPointTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpEntryPointTests.java @@ -139,7 +139,7 @@ public class RetryWithHttpEntryPointTests extends TestCase { MockHttpServletResponse response = new MockHttpServletResponse(); PortMapperImpl portMapper = new PortMapperImpl(); - Map map = new HashMap(); + Map map = new HashMap(); map.put("8888", "9999"); portMapper.setPortMappings(map); diff --git a/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpsEntryPointTests.java b/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpsEntryPointTests.java index 57a2538340..1063ac93bb 100644 --- a/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpsEntryPointTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/RetryWithHttpsEntryPointTests.java @@ -146,7 +146,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase { MockHttpServletResponse response = new MockHttpServletResponse(); PortMapperImpl portMapper = new PortMapperImpl(); - Map map = new HashMap(); + Map map = new HashMap(); map.put("8888", "9999"); portMapper.setPortMappings(map); diff --git a/core/src/test/java/org/springframework/security/securechannel/SecureChannelProcessorTests.java b/core/src/test/java/org/springframework/security/securechannel/SecureChannelProcessorTests.java index 9ae8fd93bd..f5f06968d3 100644 --- a/core/src/test/java/org/springframework/security/securechannel/SecureChannelProcessorTests.java +++ b/core/src/test/java/org/springframework/security/securechannel/SecureChannelProcessorTests.java @@ -19,7 +19,7 @@ import junit.framework.TestCase; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.MockFilterChain; +import org.springframework.security.util.MockFilterChain; import org.springframework.security.SecurityConfig; import org.springframework.security.intercept.web.FilterInvocation; diff --git a/core/src/test/java/org/springframework/security/token/DefaultTokenTests.java b/core/src/test/java/org/springframework/security/token/DefaultTokenTests.java index a7254e7cab..fa9388616a 100644 --- a/core/src/test/java/org/springframework/security/token/DefaultTokenTests.java +++ b/core/src/test/java/org/springframework/security/token/DefaultTokenTests.java @@ -13,31 +13,31 @@ import org.junit.Test; * */ public class DefaultTokenTests { - @Test - public void testEquality() { - String key = "key"; - long created = new Date().getTime(); - String extendedInformation = "extended"; - - DefaultToken t1 = new DefaultToken(key, created, extendedInformation); - DefaultToken t2 = new DefaultToken(key, created, extendedInformation); - Assert.assertEquals(t1, t2); - } - - @Test(expected=IllegalArgumentException.class) - public void testRejectsNullExtendedInformation() { - String key = "key"; - long created = new Date().getTime(); - new DefaultToken(key, created, null); - } + @Test + public void testEquality() { + String key = "key"; + long created = new Date().getTime(); + String extendedInformation = "extended"; + + DefaultToken t1 = new DefaultToken(key, created, extendedInformation); + DefaultToken t2 = new DefaultToken(key, created, extendedInformation); + Assert.assertEquals(t1, t2); + } + + @Test(expected=IllegalArgumentException.class) + public void testRejectsNullExtendedInformation() { + String key = "key"; + long created = new Date().getTime(); + new DefaultToken(key, created, null); + } - @Test - public void testEqualityWithDifferentExtendedInformation3() { - String key = "key"; - long created = new Date().getTime(); - - DefaultToken t1 = new DefaultToken(key, created, "length1"); - DefaultToken t2 = new DefaultToken(key, created, "longerLength2"); - Assert.assertFalse(t1.equals(t2)); - } + @Test + public void testEqualityWithDifferentExtendedInformation3() { + String key = "key"; + long created = new Date().getTime(); + + DefaultToken t1 = new DefaultToken(key, created, "length1"); + DefaultToken t2 = new DefaultToken(key, created, "longerLength2"); + Assert.assertFalse(t1.equals(t2)); + } } diff --git a/core/src/test/java/org/springframework/security/token/KeyBasedPersistenceTokenServiceTests.java b/core/src/test/java/org/springframework/security/token/KeyBasedPersistenceTokenServiceTests.java index ab0895f35d..0c5d534614 100644 --- a/core/src/test/java/org/springframework/security/token/KeyBasedPersistenceTokenServiceTests.java +++ b/core/src/test/java/org/springframework/security/token/KeyBasedPersistenceTokenServiceTests.java @@ -17,68 +17,68 @@ import org.junit.Test; */ public class KeyBasedPersistenceTokenServiceTests { - private KeyBasedPersistenceTokenService getService() { - SecureRandomFactoryBean fb = new SecureRandomFactoryBean(); - KeyBasedPersistenceTokenService service = new KeyBasedPersistenceTokenService(); - service.setServerSecret("MY:SECRET$$$#"); - service.setServerInteger(new Integer(454545)); - try { - SecureRandom rnd = (SecureRandom) fb.getObject(); - service.setSecureRandom(rnd); - service.afterPropertiesSet(); - } catch (Exception e) { - throw new RuntimeException(e); - } - return service; - } - - @Test - public void testOperationWithSimpleExtendedInformation() { - KeyBasedPersistenceTokenService service = getService(); - Token token = service.allocateToken("Hello world"); - Token result = service.verifyToken(token.getKey()); - Assert.assertEquals(token, result); - } + private KeyBasedPersistenceTokenService getService() { + SecureRandomFactoryBean fb = new SecureRandomFactoryBean(); + KeyBasedPersistenceTokenService service = new KeyBasedPersistenceTokenService(); + service.setServerSecret("MY:SECRET$$$#"); + service.setServerInteger(new Integer(454545)); + try { + SecureRandom rnd = (SecureRandom) fb.getObject(); + service.setSecureRandom(rnd); + service.afterPropertiesSet(); + } catch (Exception e) { + throw new RuntimeException(e); + } + return service; + } + + @Test + public void testOperationWithSimpleExtendedInformation() { + KeyBasedPersistenceTokenService service = getService(); + Token token = service.allocateToken("Hello world"); + Token result = service.verifyToken(token.getKey()); + Assert.assertEquals(token, result); + } - @Test - public void testOperationWithComplexExtendedInformation() { - KeyBasedPersistenceTokenService service = getService(); - Token token = service.allocateToken("Hello:world:::"); - Token result = service.verifyToken(token.getKey()); - Assert.assertEquals(token, result); - } + @Test + public void testOperationWithComplexExtendedInformation() { + KeyBasedPersistenceTokenService service = getService(); + Token token = service.allocateToken("Hello:world:::"); + Token result = service.verifyToken(token.getKey()); + Assert.assertEquals(token, result); + } - @Test - public void testOperationWithEmptyRandomNumber() { - KeyBasedPersistenceTokenService service = getService(); - service.setPseudoRandomNumberBits(0); - Token token = service.allocateToken("Hello:world:::"); - Token result = service.verifyToken(token.getKey()); - Assert.assertEquals(token, result); - } - - @Test - public void testOperationWithNoExtendedInformation() { - KeyBasedPersistenceTokenService service = getService(); - Token token = service.allocateToken(""); - Token result = service.verifyToken(token.getKey()); - Assert.assertEquals(token, result); - } - - @Test(expected=IllegalArgumentException.class) - public void testOperationWithMissingKey() { - KeyBasedPersistenceTokenService service = getService(); - Token token = new DefaultToken("", new Date().getTime(), ""); - service.verifyToken(token.getKey()); - } - - @Test(expected=IllegalArgumentException.class) - public void testOperationWithTamperedKey() { - KeyBasedPersistenceTokenService service = getService(); - Token goodToken = service.allocateToken(""); - String fake = goodToken.getKey().toUpperCase(); - Token token = new DefaultToken(fake, new Date().getTime(), ""); - service.verifyToken(token.getKey()); - } + @Test + public void testOperationWithEmptyRandomNumber() { + KeyBasedPersistenceTokenService service = getService(); + service.setPseudoRandomNumberBits(0); + Token token = service.allocateToken("Hello:world:::"); + Token result = service.verifyToken(token.getKey()); + Assert.assertEquals(token, result); + } + + @Test + public void testOperationWithNoExtendedInformation() { + KeyBasedPersistenceTokenService service = getService(); + Token token = service.allocateToken(""); + Token result = service.verifyToken(token.getKey()); + Assert.assertEquals(token, result); + } + + @Test(expected=IllegalArgumentException.class) + public void testOperationWithMissingKey() { + KeyBasedPersistenceTokenService service = getService(); + Token token = new DefaultToken("", new Date().getTime(), ""); + service.verifyToken(token.getKey()); + } + + @Test(expected=IllegalArgumentException.class) + public void testOperationWithTamperedKey() { + KeyBasedPersistenceTokenService service = getService(); + Token goodToken = service.allocateToken(""); + String fake = goodToken.getKey().toUpperCase(); + Token token = new DefaultToken(fake, new Date().getTime(), ""); + service.verifyToken(token.getKey()); + } } diff --git a/core/src/test/java/org/springframework/security/token/SecureRandomFactoryBeanTests.java b/core/src/test/java/org/springframework/security/token/SecureRandomFactoryBeanTests.java index 0d6dbdb3b0..ce17b6d164 100644 --- a/core/src/test/java/org/springframework/security/token/SecureRandomFactoryBeanTests.java +++ b/core/src/test/java/org/springframework/security/token/SecureRandomFactoryBeanTests.java @@ -15,37 +15,37 @@ import junit.framework.Assert; * */ public class SecureRandomFactoryBeanTests { - @Test - public void testObjectType() { - SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Assert.assertEquals(SecureRandom.class, factory.getObjectType()); - } - - @Test - public void testIsSingleton() { - SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Assert.assertFalse(factory.isSingleton()); - } + @Test + public void testObjectType() { + SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); + Assert.assertEquals(SecureRandom.class, factory.getObjectType()); + } + + @Test + public void testIsSingleton() { + SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); + Assert.assertFalse(factory.isSingleton()); + } - @Test - public void testCreatesUsingDefaults() throws Exception { - SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Object result = factory.getObject(); - Assert.assertTrue(result instanceof SecureRandom); - int rnd = ((SecureRandom)result).nextInt(); - Assert.assertTrue(rnd != 0); - } - - @Test - public void testCreatesUsingSeed() throws Exception { - SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); - Resource resource = new ClassPathResource("org/springframework/security/token/SecureRandomFactoryBeanTests.class"); - Assert.assertNotNull(resource); - factory.setSeed(resource); - Object result = factory.getObject(); - Assert.assertTrue(result instanceof SecureRandom); - int rnd = ((SecureRandom)result).nextInt(); - Assert.assertTrue(rnd != 0); - } - + @Test + public void testCreatesUsingDefaults() throws Exception { + SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); + Object result = factory.getObject(); + Assert.assertTrue(result instanceof SecureRandom); + int rnd = ((SecureRandom)result).nextInt(); + Assert.assertTrue(rnd != 0); + } + + @Test + public void testCreatesUsingSeed() throws Exception { + SecureRandomFactoryBean factory = new SecureRandomFactoryBean(); + Resource resource = new ClassPathResource("org/springframework/security/token/SecureRandomFactoryBeanTests.class"); + Assert.assertNotNull(resource); + factory.setSeed(resource); + Object result = factory.getObject(); + Assert.assertTrue(result instanceof SecureRandom); + int rnd = ((SecureRandom)result).nextInt(); + Assert.assertTrue(rnd != 0); + } + } diff --git a/core/src/test/java/org/springframework/security/ui/AbstractProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/AbstractProcessingFilterTests.java index ba197205ab..7ddbdedb58 100644 --- a/core/src/test/java/org/springframework/security/ui/AbstractProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/AbstractProcessingFilterTests.java @@ -88,16 +88,16 @@ public class AbstractProcessingFilterTests extends TestCase { return new SavedRequest(request, new PortResolverImpl()); } - private SavedRequest makePostSavedRequestForUrl() { - MockHttpServletRequest request = createMockRequest(); - request.setServletPath("/some_protected_file.html"); - request.setScheme("http"); - request.setServerName("www.example.com"); - request.setRequestURI("/mycontext/post/some_protected_file.html"); - request.setMethod("POST"); - - return new SavedRequest(request, new PortResolverImpl()); - } +// private SavedRequest makePostSavedRequestForUrl() { +// MockHttpServletRequest request = createMockRequest(); +// request.setServletPath("/some_protected_file.html"); +// request.setScheme("http"); +// request.setServerName("www.example.com"); +// request.setRequestURI("/mycontext/post/some_protected_file.html"); +// request.setMethod("POST"); +// +// return new SavedRequest(request, new PortResolverImpl()); +// } protected void setUp() throws Exception { super.setUp(); diff --git a/core/src/test/java/org/springframework/security/ui/ExceptionTranslationFilterTests.java b/core/src/test/java/org/springframework/security/ui/ExceptionTranslationFilterTests.java index 9d93d9e277..53e5e1d926 100644 --- a/core/src/test/java/org/springframework/security/ui/ExceptionTranslationFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/ExceptionTranslationFilterTests.java @@ -15,24 +15,6 @@ package org.springframework.security.ui; -import junit.framework.TestCase; - -import org.springframework.security.AccessDeniedException; -import org.springframework.security.BadCredentialsException; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.security.MockAuthenticationEntryPoint; -import org.springframework.security.MockPortResolver; - -import org.springframework.security.context.SecurityContextHolder; - -import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken; -import org.springframework.security.ui.savedrequest.SavedRequest; -import org.springframework.security.util.AuthorityUtils; - -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - import java.io.IOException; import javax.servlet.FilterChain; @@ -42,12 +24,24 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import junit.framework.TestCase; + +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.AccessDeniedException; +import org.springframework.security.BadCredentialsException; +import org.springframework.security.MockAuthenticationEntryPoint; +import org.springframework.security.MockPortResolver; +import org.springframework.security.context.SecurityContextHolder; +import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken; +import org.springframework.security.ui.savedrequest.SavedRequest; +import org.springframework.security.util.AuthorityUtils; + /** * Tests {@link ExceptionTranslationFilter}. * * @author Ben Alex - * @version $Id: ExceptionTranslationFilterTests.java 1496 2006-05-23 13:38:33Z - * benalex $ + * @version $Id$ */ public class ExceptionTranslationFilterTests extends TestCase { //~ Methods ======================================================================================================== diff --git a/core/src/test/java/org/springframework/security/ui/SessionFixationProtectionFilterTests.java b/core/src/test/java/org/springframework/security/ui/SessionFixationProtectionFilterTests.java index 0db018f924..f55a82aeb5 100644 --- a/core/src/test/java/org/springframework/security/ui/SessionFixationProtectionFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/SessionFixationProtectionFilterTests.java @@ -9,12 +9,12 @@ import org.junit.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.context.HttpSessionContextIntegrationFilter; +import org.springframework.security.context.HttpSessionSecurityContextRepository; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.TestingAuthenticationToken; /** - * + * * @author Luke Taylor * @version $Id$ */ @@ -24,15 +24,15 @@ public class SessionFixationProtectionFilterTests { public void clearContext() { SecurityContextHolder.clearContext(); } - + @Test public void newSessionShouldNotBeCreatedIfNoSessionExists() throws Exception { SessionFixationProtectionFilter filter = new SessionFixationProtectionFilter(); HttpServletRequest request = new MockHttpServletRequest(); authenticateUser(); - + filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); - + assertNull(request.getSession(false)); } @@ -42,22 +42,22 @@ public class SessionFixationProtectionFilterTests { HttpServletRequest request = new MockHttpServletRequest(); String sessionId = request.getSession().getId(); authenticateUser(); - + filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); - + assertFalse(sessionId.equals(request.getSession().getId())); - } + } @Test public void newSessionShouldNotBeCreatedIfSessionExistsAndUserIsNotAuthenticated() throws Exception { SessionFixationProtectionFilter filter = new SessionFixationProtectionFilter(); HttpServletRequest request = new MockHttpServletRequest(); String sessionId = request.getSession().getId(); - + filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); - + assertEquals(sessionId, request.getSession().getId()); - } + } @Test public void newSessionShouldNotBeCreatedIfUserIsAlreadyAuthenticated() throws Exception { @@ -65,13 +65,13 @@ public class SessionFixationProtectionFilterTests { HttpServletRequest request = new MockHttpServletRequest(); String sessionId = request.getSession().getId(); authenticateUser(); - request.getSession().setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, + request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext()); filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); - + assertEquals(sessionId, request.getSession().getId()); - } + } private void authenticateUser() { SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass")); diff --git a/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPointTests.java b/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPointTests.java index d7cd3f7763..dff54f8782 100644 --- a/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPointTests.java +++ b/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterEntryPointTests.java @@ -39,16 +39,6 @@ import java.util.Map; * @version $Id$ */ public class DigestProcessingFilterEntryPointTests extends TestCase { - //~ Constructors =================================================================================================== - - public DigestProcessingFilterEntryPointTests() { - super(); - } - - public DigestProcessingFilterEntryPointTests(String arg0) { - super(arg0); - } - //~ Methods ======================================================================================================== private void checkNonceValid(String nonce) { @@ -65,14 +55,6 @@ public class DigestProcessingFilterEntryPointTests extends TestCase { assertEquals(expectedNonceSignature, nonceTokens[1]); } - public static void main(String[] args) { - junit.textui.TestRunner.run(DigestProcessingFilterEntryPointTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testDetectsMissingKey() throws Exception { DigestProcessingFilterEntryPoint ep = new DigestProcessingFilterEntryPoint(); ep.setRealmName("realm"); @@ -130,7 +112,7 @@ public class DigestProcessingFilterEntryPointTests extends TestCase { // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); - Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertEquals("hello", headerMap.get("realm")); assertEquals("auth", headerMap.get("qop")); @@ -160,7 +142,7 @@ public class DigestProcessingFilterEntryPointTests extends TestCase { // Break up response header String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); - Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertEquals("hello", headerMap.get("realm")); assertEquals("auth", headerMap.get("qop")); diff --git a/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterTests.java index 95930c24ac..d39e34007a 100644 --- a/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/digestauth/DigestProcessingFilterTests.java @@ -166,7 +166,7 @@ public class DigestProcessingFilterTests { String header = response.getHeader("WWW-Authenticate").toString().substring(7); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); - Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertEquals("true", headerMap.get("stale")); } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index 761f6fd079..fb625ea058 100644 --- a/core/src/test/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -14,42 +14,42 @@ import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.util.MockFilterChain; public class AbstractPreAuthenticatedProcessingFilterTests { - private AbstractPreAuthenticatedProcessingFilter filter; - - @Before - public void createFilter() { - filter = new AbstractPreAuthenticatedProcessingFilter() { - protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { - return "n/a"; - } + private AbstractPreAuthenticatedProcessingFilter filter; + + @Before + public void createFilter() { + filter = new AbstractPreAuthenticatedProcessingFilter() { + protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { + return "n/a"; + } - protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { - return "doesntmatter"; - } + protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { + return "doesntmatter"; + } - public int getOrder() { - return 0; - } - }; - SecurityContextHolder.getContext().setAuthentication(null); - } + public int getOrder() { + return 0; + } + }; + SecurityContextHolder.getContext().setAuthentication(null); + } - @Test - public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception { - filter.setAuthenticationManager(new MockAuthenticationManager(false)); - filter.afterPropertiesSet(); - filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(true)); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - } - - /* SEC-881 */ - @Test(expected=BadCredentialsException.class) - public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception { - filter.setContinueFilterChainOnUnsuccessfulAuthentication(false); - filter.setAuthenticationManager(new MockAuthenticationManager(false)); - filter.afterPropertiesSet(); - filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(false)); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - } + @Test + public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception { + filter.setAuthenticationManager(new MockAuthenticationManager(false)); + filter.afterPropertiesSet(); + filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(true)); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + } + + /* SEC-881 */ + @Test(expected=BadCredentialsException.class) + public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception { + filter.setContinueFilterChainOnUnsuccessfulAuthentication(false); + filter.setAuthenticationManager(new MockAuthenticationManager(false)); + filter.afterPropertiesSet(); + filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain(false)); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + } } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java index bb6b31a080..e204ed20f2 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests.java @@ -3,7 +3,6 @@ package org.springframework.security.ui.preauth; import static org.junit.Assert.assertTrue; import java.util.Arrays; -import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -35,25 +34,22 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests { public void testGetSetPreAuthenticatedGrantedAuthorities() { PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( getRequest("testUser", new String[] {})); - - Collection expectedGas = Arrays.asList(gas); - details.setGrantedAuthorities(gas); - Collection returnedGas = Arrays.asList(details.getGrantedAuthorities()); - assertTrue("Collections do not contain same elements; expected: " + expectedGas + ", returned: " + returnedGas, - expectedGas.containsAll(returnedGas) && returnedGas.containsAll(expectedGas)); + List returnedGas = details.getGrantedAuthorities(); + assertTrue("Collections do not contain same elements; expected: " + gas + ", returned: " + returnedGas, + gas.containsAll(returnedGas) && returnedGas.containsAll(gas)); } @Test(expected=IllegalArgumentException.class) public void testGetWithoutSetPreAuthenticatedGrantedAuthorities() { PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails( getRequest("testUser", new String[] {})); - List gas = details.getGrantedAuthorities(); + details.getGrantedAuthorities(); } private HttpServletRequest getRequest(final String userName,final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { - private Set roles = new HashSet(Arrays.asList(aRoles)); + private Set roles = new HashSet(Arrays.asList(aRoles)); public boolean isUserInRole(String arg0) { return roles.contains(arg0); } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPointTests.java b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPointTests.java index 3d74705a88..a1bd0ac061 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPointTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterEntryPointTests.java @@ -19,24 +19,24 @@ import org.springframework.mock.web.MockHttpServletResponse; */ public class PreAuthenticatedProcessingFilterEntryPointTests extends TestCase { - public void testGetSetOrder() { - PreAuthenticatedProcessingFilterEntryPoint fep = new PreAuthenticatedProcessingFilterEntryPoint(); - fep.setOrder(333); - assertEquals(fep.getOrder(), 333); - } + public void testGetSetOrder() { + PreAuthenticatedProcessingFilterEntryPoint fep = new PreAuthenticatedProcessingFilterEntryPoint(); + fep.setOrder(333); + assertEquals(fep.getOrder(), 333); + } - public void testCommence() { - MockHttpServletRequest req = new MockHttpServletRequest(); - MockHttpServletResponse resp = new MockHttpServletResponse(); - PreAuthenticatedProcessingFilterEntryPoint fep = new PreAuthenticatedProcessingFilterEntryPoint(); - try { - fep.commence(req,resp,new AuthenticationCredentialsNotFoundException("test")); - assertEquals("Incorrect status",resp.getStatus(),HttpServletResponse.SC_FORBIDDEN); - } catch (IOException e) { - fail("Unexpected exception thrown: "+e); - } catch (ServletException e) { - fail("Unexpected exception thrown: "+e); - } + public void testCommence() { + MockHttpServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse resp = new MockHttpServletResponse(); + PreAuthenticatedProcessingFilterEntryPoint fep = new PreAuthenticatedProcessingFilterEntryPoint(); + try { + fep.commence(req,resp,new AuthenticationCredentialsNotFoundException("test")); + assertEquals("Incorrect status",resp.getStatus(),HttpServletResponse.SC_FORBIDDEN); + } catch (IOException e) { + fail("Unexpected exception thrown: "+e); + } catch (ServletException e) { + fail("Unexpected exception thrown: "+e); + } - } + } } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterTests.java index bae394069d..7fda5f62ad 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/PreAuthenticatedProcessingFilterTests.java @@ -13,50 +13,50 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; public class PreAuthenticatedProcessingFilterTests extends TestCase { - protected void setUp() throws Exception { - SecurityContextHolder.clearContext(); - } - - 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"); - } - } + protected void setUp() throws Exception { + SecurityContextHolder.clearContext(); + } + + 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"); + } + } - public final void testDoFilterAuthenticated() throws Exception { - testDoFilter(true); - } + public final void testDoFilterAuthenticated() throws Exception { + testDoFilter(true); + } - public final void testDoFilterUnauthenticated() throws Exception { - testDoFilter(false); - } - - private final void testDoFilter(boolean grantAccess) throws Exception { - MockHttpServletRequest req = new MockHttpServletRequest(); - MockHttpServletResponse res = new MockHttpServletResponse(); - getFilter(grantAccess).doFilter(req,res,new MockFilterChain()); - assertEquals(grantAccess,null!= SecurityContextHolder.getContext().getAuthentication()); - } - - private static final ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) throws Exception { - ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); - filter.setAuthenticationManager(new MockAuthenticationManager(grantAccess)); - filter.afterPropertiesSet(); - return filter; - } - - private static final class ConcretePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { - protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) { - return "testPrincipal"; - } - protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) { - return "testCredentials"; - } + public final void testDoFilterUnauthenticated() throws Exception { + testDoFilter(false); + } + + private final void testDoFilter(boolean grantAccess) throws Exception { + MockHttpServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse res = new MockHttpServletResponse(); + getFilter(grantAccess).doFilter(req,res,new MockFilterChain()); + assertEquals(grantAccess,null!= SecurityContextHolder.getContext().getAuthentication()); + } + + private static final ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) throws Exception { + ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); + filter.setAuthenticationManager(new MockAuthenticationManager(grantAccess)); + filter.afterPropertiesSet(); + return filter; + } + + private static final class ConcretePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { + protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) { + return "testPrincipal"; + } + protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) { + return "testCredentials"; + } public int getOrder() { return FilterChainOrder.PRE_AUTH_FILTER; diff --git a/core/src/test/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilterTests.java index f575a6b3ff..c5513434bb 100644 --- a/core/src/test/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/header/RequestHeaderPreAuthenticatedProcessingFilterTests.java @@ -17,67 +17,67 @@ import org.springframework.security.ui.preauth.PreAuthenticatedCredentialsNotFou * @version $Id$ */ public class RequestHeaderPreAuthenticatedProcessingFilterTests { - - @After - public void clearContext() { - SecurityContextHolder.clearContext(); - } - - @Test(expected = PreAuthenticatedCredentialsNotFoundException.class) - public void rejectsMissingHeader() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain chain = new MockFilterChain(); - RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); - filter.getOrder(); - - filter.doFilter(request, response, chain); - } - - @Test - public void defaultsToUsingSiteminderHeader() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader("SM_USER", "cat"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain chain = new MockFilterChain(); - RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); - filter.setAuthenticationManager(new MockAuthenticationManager()); - - filter.doFilter(request, response, chain); - assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - assertEquals("cat", SecurityContextHolder.getContext().getAuthentication().getName()); - assertEquals("N/A", SecurityContextHolder.getContext().getAuthentication().getCredentials()); - } + + @After + public void clearContext() { + SecurityContextHolder.clearContext(); + } + + @Test(expected = PreAuthenticatedCredentialsNotFoundException.class) + public void rejectsMissingHeader() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); + filter.getOrder(); + + filter.doFilter(request, response, chain); + } + + @Test + public void defaultsToUsingSiteminderHeader() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("SM_USER", "cat"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); + filter.setAuthenticationManager(new MockAuthenticationManager()); + + filter.doFilter(request, response, chain); + assertNotNull(SecurityContextHolder.getContext().getAuthentication()); + assertEquals("cat", SecurityContextHolder.getContext().getAuthentication().getName()); + assertEquals("N/A", SecurityContextHolder.getContext().getAuthentication().getCredentials()); + } - @Test - public void alternativeHeaderNameIsSupported() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader("myUsernameHeader", "wolfman"); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain chain = new MockFilterChain(); - RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); - filter.setAuthenticationManager(new MockAuthenticationManager()); - filter.setPrincipalRequestHeader("myUsernameHeader"); - - filter.doFilter(request, response, chain); - assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - assertEquals("wolfman", SecurityContextHolder.getContext().getAuthentication().getName()); - } - - @Test - public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockFilterChain chain = new MockFilterChain(); - RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); - filter.setAuthenticationManager(new MockAuthenticationManager()); - filter.setCredentialsRequestHeader("myCredentialsHeader"); - request.addHeader("SM_USER", "cat"); - request.addHeader("myCredentialsHeader", "catspassword"); - - filter.doFilter(request, response, chain); - assertNotNull(SecurityContextHolder.getContext().getAuthentication()); - assertEquals("catspassword", SecurityContextHolder.getContext().getAuthentication().getCredentials()); - } - + @Test + public void alternativeHeaderNameIsSupported() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("myUsernameHeader", "wolfman"); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); + filter.setAuthenticationManager(new MockAuthenticationManager()); + filter.setPrincipalRequestHeader("myUsernameHeader"); + + filter.doFilter(request, response, chain); + assertNotNull(SecurityContextHolder.getContext().getAuthentication()); + assertEquals("wolfman", SecurityContextHolder.getContext().getAuthentication().getName()); + } + + @Test + public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = new MockFilterChain(); + RequestHeaderPreAuthenticatedProcessingFilter filter = new RequestHeaderPreAuthenticatedProcessingFilter(); + filter.setAuthenticationManager(new MockAuthenticationManager()); + filter.setCredentialsRequestHeader("myCredentialsHeader"); + request.addHeader("SM_USER", "cat"); + request.addHeader("myCredentialsHeader", "catspassword"); + + filter.doFilter(request, response, chain); + assertNotNull(SecurityContextHolder.getContext().getAuthentication()); + assertEquals("catspassword", SecurityContextHolder.getContext().getAuthentication().getCredentials()); + } + } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java b/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java index c14032def4..52696a521f 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests.java @@ -96,8 +96,8 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend assertNotNull("Granted authorities should not be null", gas); assertEquals(expectedRoles.length, gas.size()); - Collection expectedRolesColl = Arrays.asList(expectedRoles); - Collection gasRolesSet = new HashSet(); + Collection expectedRolesColl = Arrays.asList(expectedRoles); + Collection gasRolesSet = new HashSet(); for (int i = 0; i < gas.size(); i++) { gasRolesSet.add(gas.get(i).getAuthority()); } @@ -138,7 +138,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend private final HttpServletRequest getRequest(final String userName,final String[] aRoles) { MockHttpServletRequest req = new MockHttpServletRequest() { - private Set roles = new HashSet(Arrays.asList(aRoles)); + private Set roles = new HashSet(Arrays.asList(aRoles)); public boolean isUserInRole(String arg0) { return roles.contains(arg0); } diff --git a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java index 0dd6070f64..d9e869a398 100755 --- a/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java @@ -12,38 +12,38 @@ import junit.framework.TestCase; import org.springframework.mock.web.MockHttpServletRequest; /** - * + * * @author TSARDD * @since 18-okt-2007 */ public class J2eePreAuthenticatedProcessingFilterTests extends TestCase { public final void testGetPreAuthenticatedPrincipal() { - String user = "testUser"; - assertEquals(user, new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal( - getRequest(user,new String[] {}))); - } + String user = "testUser"; + assertEquals(user, new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal( + getRequest(user,new String[] {}))); + } - public final void testGetPreAuthenticatedCredentials() { - assertEquals("N/A", new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials( - getRequest("testUser", new String[] {}))); - } - - private final HttpServletRequest getRequest(final String aUserName,final String[] aRoles) - { - MockHttpServletRequest req = new MockHttpServletRequest() { - private Set roles = new HashSet(Arrays.asList(aRoles)); - public boolean isUserInRole(String arg0) { - return roles.contains(arg0); - } - }; - req.setRemoteUser(aUserName); - req.setUserPrincipal(new Principal() { - public String getName() { - return aUserName; - } - }); - return req; - } + public final void testGetPreAuthenticatedCredentials() { + assertEquals("N/A", new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials( + getRequest("testUser", new String[] {}))); + } + + private final HttpServletRequest getRequest(final String aUserName,final String[] aRoles) + { + MockHttpServletRequest req = new MockHttpServletRequest() { + private Set roles = new HashSet(Arrays.asList(aRoles)); + public boolean isUserInRole(String arg0) { + return roles.contains(arg0); + } + }; + req.setRemoteUser(aUserName); + req.setUserPrincipal(new Principal() { + public String getName() { + return aUserName; + } + }); + return req; + } } diff --git a/core/src/test/java/org/springframework/security/ui/rememberme/AbstractRememberMeServicesTests.java b/core/src/test/java/org/springframework/security/ui/rememberme/AbstractRememberMeServicesTests.java index 57c8317996..8442799db9 100644 --- a/core/src/test/java/org/springframework/security/ui/rememberme/AbstractRememberMeServicesTests.java +++ b/core/src/test/java/org/springframework/security/ui/rememberme/AbstractRememberMeServicesTests.java @@ -1,30 +1,29 @@ package org.springframework.security.ui.rememberme; +import static org.junit.Assert.*; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.Authentication; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; +import org.springframework.security.util.AuthorityUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.*; -import org.junit.Test; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * @author Luke Taylor * @version $Id$ */ public class AbstractRememberMeServicesTests { - static User joe = new User("joe", "password", true, true,true,true, new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")}); + static User joe = new User("joe", "password", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_A")); @Test(expected = InvalidCookieException.class) public void nonBase64CookieShouldBeDetected() { diff --git a/core/src/test/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImplTests.java b/core/src/test/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImplTests.java index 877fc864db..c0e5ac2ce9 100644 --- a/core/src/test/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImplTests.java +++ b/core/src/test/java/org/springframework/security/ui/rememberme/JdbcTokenRepositoryImplTests.java @@ -19,6 +19,7 @@ import java.util.Map; * @author Luke Taylor * @version $Id$ */ +@SuppressWarnings("unchecked") public class JdbcTokenRepositoryImplTests { private static TestDataSource dataSource; private JdbcTokenRepositoryImpl repo; @@ -56,7 +57,7 @@ public class JdbcTokenRepositoryImplTests { PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate); repo.createNewToken(token); - Map results = template.queryForMap("select * from persistent_logins"); + Map results = template.queryForMap("select * from persistent_logins"); assertEquals(currentDate, results.get("last_used")); assertEquals("joeuser", results.get("username")); diff --git a/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java b/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java index c7e8128193..52a904f109 100644 --- a/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java +++ b/core/src/test/java/org/springframework/security/ui/switchuser/SwitchUserProcessingFilterTests.java @@ -15,9 +15,7 @@ package org.springframework.security.ui.switchuser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; @@ -36,7 +34,6 @@ import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; -import org.springframework.security.ui.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.ui.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; diff --git a/core/src/test/java/org/springframework/security/userdetails/MockUserDetailsService.java b/core/src/test/java/org/springframework/security/userdetails/MockUserDetailsService.java index 33d17d3768..5c2b1b4647 100644 --- a/core/src/test/java/org/springframework/security/userdetails/MockUserDetailsService.java +++ b/core/src/test/java/org/springframework/security/userdetails/MockUserDetailsService.java @@ -1,11 +1,12 @@ package org.springframework.security.userdetails; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; -import org.springframework.dao.DataAccessException; - -import java.util.Map; import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.dao.DataAccessException; +import org.springframework.security.GrantedAuthority; +import org.springframework.security.util.AuthorityUtils; /** * A test UserDetailsService containing a set of standard usernames corresponding to their account status: @@ -15,8 +16,8 @@ import java.util.HashMap; * @version $Id$ */ public class MockUserDetailsService implements UserDetailsService { - private Map users = new HashMap(); - private GrantedAuthority[] auths = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_USER")}; + private Map users = new HashMap(); + private List auths = AuthorityUtils.createAuthorityList("ROLE_USER"); public MockUserDetailsService() { users.put("valid", new User("valid", "",true,true,true,true,auths)); @@ -31,6 +32,6 @@ public class MockUserDetailsService implements UserDetailsService { throw new UsernameNotFoundException("User not found: " + username); } - return (UserDetails) users.get(username); + return users.get(username); } } diff --git a/core/src/test/java/org/springframework/security/userdetails/UserTests.java b/core/src/test/java/org/springframework/security/userdetails/UserTests.java index 6aa006ca22..6ce847b0ec 100644 --- a/core/src/test/java/org/springframework/security/userdetails/UserTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/UserTests.java @@ -15,6 +15,8 @@ package org.springframework.security.userdetails; +import java.util.List; + import junit.framework.TestCase; import org.springframework.security.GrantedAuthority; @@ -22,6 +24,7 @@ import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; +import org.springframework.security.util.AuthorityUtils; /** @@ -31,134 +34,75 @@ import org.springframework.security.userdetails.UserDetails; * @version $Id$ */ public class UserTests extends TestCase { - //~ Constructors =================================================================================================== - - public UserTests() { - super(); - } - - public UserTests(String arg0) { - super(arg0); - } - + private static final List ROLE_12 = AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"); //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(UserTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testEquals() { - User user1 = new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + User user1 = new User("rod", "koala", true, true, true, true,ROLE_12); assertFalse(user1.equals(null)); assertFalse(user1.equals("A STRING")); - assertTrue(user1.equals(user1)); - - assertTrue(user1.equals( - new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - + assertTrue(user1.equals(new User("rod", "koala", true, true, true, true,ROLE_12))); // Equal as the new User will internally sort the GrantedAuthorities in the correct order, before running equals() - assertTrue(user1.equals( - new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TWO"), new GrantedAuthorityImpl("ROLE_ONE")}))); - - assertFalse(user1.equals( - new User("DIFFERENT_USERNAME", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "DIFFERENT_PASSWORD", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "koala", false, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "koala", true, false, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "koala", true, true, false, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "koala", true, true, true, false, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}))); - - assertFalse(user1.equals( - new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE")}))); + assertTrue(user1.equals(new User("rod", "koala", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_TWO","ROLE_ONE")))); + assertFalse(user1.equals(new User("DIFFERENT_USERNAME", "koala", true, true, true, true, ROLE_12))); + assertFalse(user1.equals(new User("rod", "DIFFERENT_PASSWORD", true, true, true, true, ROLE_12))); + assertFalse(user1.equals(new User("rod", "koala", false, true, true, true, ROLE_12))); + assertFalse(user1.equals(new User("rod", "koala", true, false, true, true, ROLE_12))); + assertFalse(user1.equals(new User("rod", "koala", true, true, false, true, ROLE_12))); + assertFalse(user1.equals(new User("rod", "koala", true, true, true, false, ROLE_12))); + assertFalse(user1.equals(new User("rod", "koala", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_ONE")))); } public void testNoArgConstructorDoesntExist() { - Class clazz = User.class; + Class clazz = User.class; try { clazz.getDeclaredConstructor((Class[]) null); fail("Should have thrown NoSuchMethodException"); } catch (NoSuchMethodException expected) { - assertTrue(true); } } public void testNullValuesRejected() throws Exception { try { - UserDetails user = new User(null, "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + new User(null, "koala", true, true, true, true,ROLE_12); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); } try { - UserDetails user = new User("rod", null, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + new User("rod", null, true, true, true, true, ROLE_12); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); } -// try { -// UserDetails user = new User("rod", "koala", true, true, true, true, null); -// fail("Should have thrown IllegalArgumentException"); -// } catch (IllegalArgumentException expected) { -// assertTrue(true); -// } - try { - UserDetails user = new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), null}); + List 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) { - assertTrue(true); } } - public void testNullWithinGrantedAuthorityElementIsRejected() - throws Exception { + public void testNullWithinGrantedAuthorityElementIsRejected() throws Exception { try { - UserDetails user = new User(null, "koala", true, true, true, true, - new GrantedAuthority[] { - new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"), null, - new GrantedAuthorityImpl("ROLE_THREE") - }); + List auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); + auths.add(null); + auths.add(new GrantedAuthorityImpl("ROLE_THREE")); + new User(null, "koala", true, true, true, true, auths); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { - assertTrue(true); } } public void testUserGettersSetter() throws Exception { UserDetails user = new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TWO"), new GrantedAuthorityImpl("ROLE_ONE")}); + AuthorityUtils.createAuthorityList("ROLE_TWO","ROLE_ONE")); assertEquals("rod", user.getUsername()); assertEquals("koala", user.getPassword()); assertTrue(user.isEnabled()); @@ -168,8 +112,7 @@ public class UserTests extends TestCase { } public void testUserIsEnabled() throws Exception { - UserDetails user = new User("rod", "koala", false, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + UserDetails user = new User("rod", "koala", false, true, true, true, ROLE_12); assertTrue(!user.isEnabled()); } } diff --git a/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsServiceWrapperTests.java b/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsServiceWrapperTests.java index 53b14585b4..22eb468f93 100755 --- a/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsServiceWrapperTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsServiceWrapperTests.java @@ -9,16 +9,16 @@ import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.security.util.AuthorityUtils; @RunWith(JMock.class) +@SuppressWarnings("deprecation") public class UserDetailsServiceWrapperTests { private UserDetailsService wrappedUserDetailsService = null; @@ -29,8 +29,8 @@ public class UserDetailsServiceWrapperTests { public void setUp() throws Exception { RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); roleHierarchy.setHierarchy("ROLE_A > ROLE_B"); - GrantedAuthority[] authorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") }; - final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true, authorities); + final UserDetails user = new User("EXISTING_USER", "PASSWORD", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_A")); final UserDetailsService wrappedUserDetailsService = jmockContext.mock(UserDetailsService.class); jmockContext.checking( new Expectations() {{ @@ -46,8 +46,8 @@ public class UserDetailsServiceWrapperTests { @Test public void testLoadUserByUsername() { - GrantedAuthority[] authorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B") }; - UserDetails expectedUserDetails = new User("EXISTING_USER", "PASSWORD", true, true, true, true, authorities); + UserDetails expectedUserDetails = new User("EXISTING_USER", "PASSWORD", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); UserDetails userDetails = userDetailsServiceWrapper.loadUserByUsername("EXISTING_USER"); assertEquals(expectedUserDetails.getPassword(), userDetails.getPassword()); assertEquals(expectedUserDetails.getUsername(), userDetails.getUsername()); diff --git a/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsWrapperTests.java b/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsWrapperTests.java index 07c1c19cd7..371ddf4ea1 100755 --- a/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsWrapperTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/hierarchicalroles/UserDetailsWrapperTests.java @@ -5,7 +5,6 @@ import java.util.List; import junit.framework.TestCase; import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.util.AuthorityUtils; @@ -15,9 +14,10 @@ import org.springframework.security.util.AuthorityUtils; * * @author Michael Mayr */ +@SuppressWarnings("deprecation") public class UserDetailsWrapperTests extends TestCase { - private GrantedAuthority[] authorities = null; + private List authorities = null; private UserDetails userDetails1 = null; private UserDetails userDetails2 = null; private UserDetailsWrapper userDetailsWrapper1 = null; @@ -33,7 +33,7 @@ public class UserDetailsWrapperTests extends TestCase { protected void setUp() throws Exception { RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl(); roleHierarchy.setHierarchy("ROLE_A > ROLE_B"); - authorities = new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_A") }; + authorities = AuthorityUtils.createAuthorityList("ROLE_A"); userDetails1 = new User("TestUser1", "TestPassword1", true, true, true, true, authorities); userDetails2 = new User("TestUser2", "TestPassword2", false, false, false, false, authorities); userDetailsWrapper1 = new UserDetailsWrapper(userDetails1, roleHierarchy); diff --git a/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcDaoImplTests.java b/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcDaoImplTests.java index 938c522f5c..60dc36bf23 100644 --- a/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcDaoImplTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcDaoImplTests.java @@ -15,20 +15,14 @@ package org.springframework.security.userdetails.jdbc; +import java.util.HashSet; + import junit.framework.TestCase; import org.springframework.security.PopulatedDatabase; - import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UsernameNotFoundException; -import org.springframework.jdbc.object.MappingSqlQuery; - -import java.sql.ResultSet; -import java.sql.SQLException; - -import java.util.HashSet; - /** * Tests {@link JdbcDaoImpl}. @@ -64,7 +58,7 @@ public class JdbcDaoImplTests extends TestCase { assertEquals("koala", user.getPassword()); assertTrue(user.isEnabled()); - HashSet authorities = new HashSet(2); + HashSet authorities = new HashSet(2); authorities.add(user.getAuthorities().get(0).getAuthority()); authorities.add(user.getAuthorities().get(1).getAuthority()); assertTrue(authorities.contains("ROLE_TELLER")); @@ -129,7 +123,7 @@ public class JdbcDaoImplTests extends TestCase { assertEquals("rod", user.getUsername()); assertEquals(2, user.getAuthorities().size()); - HashSet authorities = new HashSet(2); + HashSet authorities = new HashSet(2); authorities.add(user.getAuthorities().get(0).getAuthority()); authorities.add(user.getAuthorities().get(1).getAuthority()); assertTrue(authorities.contains("ARBITRARY_PREFIX_ROLE_TELLER")); diff --git a/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManagerTests.java b/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManagerTests.java index 5f9f6b6571..6af44467c6 100644 --- a/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManagerTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/jdbc/JdbcUserDetailsManagerTests.java @@ -213,6 +213,7 @@ public class JdbcUserDetailsManagerTests { } @Test + @SuppressWarnings("unchecked") public void createGroupInsertsCorrectData() { manager.createGroup("TEST_GROUP", AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y")); diff --git a/core/src/test/java/org/springframework/security/userdetails/ldap/InetOrgPersonTests.java b/core/src/test/java/org/springframework/security/userdetails/ldap/InetOrgPersonTests.java index 6bf192e044..8de992f802 100644 --- a/core/src/test/java/org/springframework/security/userdetails/ldap/InetOrgPersonTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/ldap/InetOrgPersonTests.java @@ -58,26 +58,26 @@ public class InetOrgPersonTests extends TestCase { } public void testMappingBackToContextMatchesOriginalData() { - DirContextAdapter ctx1 = createUserContext(); - DirContextAdapter ctx2 = new DirContextAdapter(); - ctx1.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson", "inetOrgPerson"}); - ctx2.setDn(new DistinguishedName("ignored=ignored")); - InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); - p.populateContext(ctx2); - - assertEquals(ctx1, ctx2); + DirContextAdapter ctx1 = createUserContext(); + DirContextAdapter ctx2 = new DirContextAdapter(); + ctx1.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson", "inetOrgPerson"}); + ctx2.setDn(new DistinguishedName("ignored=ignored")); + InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); + p.populateContext(ctx2); + + assertEquals(ctx1, ctx2); } public void testCopyMatchesOriginalData() { - DirContextAdapter ctx1 = createUserContext(); - DirContextAdapter ctx2 = new DirContextAdapter(); - ctx2.setDn(new DistinguishedName("ignored=ignored")); - ctx1.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson", "inetOrgPerson"}); - InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); - InetOrgPerson p2 = (InetOrgPerson) new InetOrgPerson.Essence(p).createUserDetails(); - p2.populateContext(ctx2); + DirContextAdapter ctx1 = createUserContext(); + DirContextAdapter ctx2 = new DirContextAdapter(); + ctx2.setDn(new DistinguishedName("ignored=ignored")); + ctx1.setAttributeValues("objectclass", new String[] {"top", "person", "organizationalPerson", "inetOrgPerson"}); + InetOrgPerson p = (InetOrgPerson) (new InetOrgPerson.Essence(ctx1)).createUserDetails(); + InetOrgPerson p2 = (InetOrgPerson) new InetOrgPerson.Essence(p).createUserDetails(); + p2.populateContext(ctx2); - assertEquals(ctx1, ctx2); + assertEquals(ctx1, ctx2); } private DirContextAdapter createUserContext() { diff --git a/core/src/test/java/org/springframework/security/userdetails/ldap/LdapUserDetailsServiceTests.java b/core/src/test/java/org/springframework/security/userdetails/ldap/LdapUserDetailsServiceTests.java index ee253f2db5..11f69aa04a 100644 --- a/core/src/test/java/org/springframework/security/userdetails/ldap/LdapUserDetailsServiceTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/ldap/LdapUserDetailsServiceTests.java @@ -44,7 +44,7 @@ public class LdapUserDetailsServiceTests { UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); - Set authorities = AuthorityUtils.authorityListToSet(user.getAuthorities()); + Set authorities = AuthorityUtils.authorityListToSet(user.getAuthorities()); assertEquals(1, authorities.size()); assertTrue(authorities.contains("ROLE_FROM_POPULATOR")); } diff --git a/core/src/test/java/org/springframework/security/userdetails/memory/UserMapTests.java b/core/src/test/java/org/springframework/security/userdetails/memory/UserMapTests.java index 8611576383..906511bcf3 100644 --- a/core/src/test/java/org/springframework/security/userdetails/memory/UserMapTests.java +++ b/core/src/test/java/org/springframework/security/userdetails/memory/UserMapTests.java @@ -17,13 +17,10 @@ package org.springframework.security.userdetails.memory; import junit.framework.TestCase; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; - import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UsernameNotFoundException; -import org.springframework.security.userdetails.memory.UserMap; +import org.springframework.security.util.AuthorityUtils; /** @@ -33,33 +30,15 @@ import org.springframework.security.userdetails.memory.UserMap; * @version $Id$ */ public class UserMapTests extends TestCase { - //~ Constructors =================================================================================================== - - public UserMapTests() { - super(); - } - - public UserMapTests(String arg0) { - super(arg0); - } //~ Methods ======================================================================================================== - - public static void main(String[] args) { - junit.textui.TestRunner.run(UserMapTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testAddAndRetrieveUser() { UserDetails rod = new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO")); UserDetails scott = new User("scott", "wombat", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_THREE")}); + AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_THREE")); UserDetails peter = new User("peter", "opal", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_FOUR")}); + AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_FOUR")); UserMap map = new UserMap(); map.addUser(rod); map.addUser(scott); @@ -85,7 +64,7 @@ public class UserMapTests extends TestCase { public void testUnknownUserIsNotRetrieved() { UserDetails rod = new User("rod", "koala", true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}); + AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO")); UserMap map = new UserMap(); assertEquals(0, map.getUserCount()); map.addUser(rod); diff --git a/core/src/test/java/org/springframework/security/util/FilterChainProxyTests.java b/core/src/test/java/org/springframework/security/util/FilterChainProxyTests.java index be9ffe01dd..c53e12793b 100644 --- a/core/src/test/java/org/springframework/security/util/FilterChainProxyTests.java +++ b/core/src/test/java/org/springframework/security/util/FilterChainProxyTests.java @@ -29,7 +29,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.MockFilterConfig; -import org.springframework.security.context.HttpSessionContextIntegrationFilter; +import org.springframework.security.context.SecurityContextPersistenceFilter; import org.springframework.security.ui.webapp.AuthenticationProcessingFilter; /** @@ -131,7 +131,7 @@ public class FilterChainProxyTests { filters = filterChainProxy.getFilters("/some/other/path/blah"); assertNotNull(filters); assertEquals(3, filters.size()); - assertTrue(filters.get(0) instanceof HttpSessionContextIntegrationFilter); + assertTrue(filters.get(0) instanceof SecurityContextPersistenceFilter); assertTrue(filters.get(1) instanceof MockFilter); assertTrue(filters.get(2) instanceof MockFilter); @@ -140,7 +140,7 @@ public class FilterChainProxyTests { filters = filterChainProxy.getFilters("/another/nonspecificmatch"); assertEquals(3, filters.size()); - assertTrue(filters.get(0) instanceof HttpSessionContextIntegrationFilter); + assertTrue(filters.get(0) instanceof SecurityContextPersistenceFilter); assertTrue(filters.get(1) instanceof AuthenticationProcessingFilter); assertTrue(filters.get(2) instanceof MockFilter); } diff --git a/core/src/test/java/org/springframework/security/util/MockFilterChain.java b/core/src/test/java/org/springframework/security/util/MockFilterChain.java index 8554a98d39..af385802c2 100644 --- a/core/src/test/java/org/springframework/security/util/MockFilterChain.java +++ b/core/src/test/java/org/springframework/security/util/MockFilterChain.java @@ -15,8 +15,6 @@ package org.springframework.security.util; -import junit.framework.TestCase; - import java.io.IOException; import javax.servlet.FilterChain; @@ -24,6 +22,8 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; +import org.junit.Assert; + /** * A mock FilterChain. @@ -38,18 +38,19 @@ public class MockFilterChain implements FilterChain { //~ Constructors =================================================================================================== + public MockFilterChain() { + this(true); + } + public MockFilterChain(boolean expectToProceed) { this.expectToProceed = expectToProceed; } //~ Methods ======================================================================================================== - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - if (expectToProceed) { - TestCase.assertTrue(true); - } else { - TestCase.fail("Did not expect filter chain to proceed"); + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + if (!expectToProceed) { + Assert.fail("Did not expect filter chain to proceed"); } } } diff --git a/core/src/test/java/org/springframework/security/util/PortMapperImplTests.java b/core/src/test/java/org/springframework/security/util/PortMapperImplTests.java index 8581fc9e85..26d9e275fd 100644 --- a/core/src/test/java/org/springframework/security/util/PortMapperImplTests.java +++ b/core/src/test/java/org/springframework/security/util/PortMapperImplTests.java @@ -28,26 +28,8 @@ import java.util.Map; * @version $Id$ */ public class PortMapperImplTests extends TestCase { - //~ Constructors =================================================================================================== - - public PortMapperImplTests() { - super(); - } - - public PortMapperImplTests(String arg0) { - super(arg0); - } - //~ Methods ======================================================================================================== - public static void main(String[] args) { - junit.textui.TestRunner.run(PortMapperImplTests.class); - } - - public final void setUp() throws Exception { - super.setUp(); - } - public void testDefaultMappingsAreKnown() throws Exception { PortMapperImpl portMapper = new PortMapperImpl(); assertEquals(new Integer(80), portMapper.lookupHttpPort(new Integer(443))); @@ -60,7 +42,7 @@ public class PortMapperImplTests extends TestCase { PortMapperImpl portMapper = new PortMapperImpl(); try { - portMapper.setPortMappings(new HashMap()); + portMapper.setPortMappings(new HashMap()); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { assertTrue(true); @@ -85,7 +67,7 @@ public class PortMapperImplTests extends TestCase { public void testRejectsOutOfRangeMappings() { PortMapperImpl portMapper = new PortMapperImpl(); - Map map = new HashMap(); + Map map = new HashMap(); map.put("79", "80559"); try { @@ -103,7 +85,7 @@ public class PortMapperImplTests extends TestCase { public void testSupportsCustomMappings() { PortMapperImpl portMapper = new PortMapperImpl(); - Map map = new HashMap(); + Map map = new HashMap(); map.put("79", "442"); portMapper.setPortMappings(map); diff --git a/core/src/test/java/org/springframework/security/util/StringSplitUtilsTests.java b/core/src/test/java/org/springframework/security/util/StringSplitUtilsTests.java index ea06be21e7..c0f23957c7 100644 --- a/core/src/test/java/org/springframework/security/util/StringSplitUtilsTests.java +++ b/core/src/test/java/org/springframework/security/util/StringSplitUtilsTests.java @@ -31,29 +31,13 @@ import java.util.Map; public class StringSplitUtilsTests extends TestCase { //~ Constructors =================================================================================================== - // =========================================================== - - public StringSplitUtilsTests() { - super(); - } - - public StringSplitUtilsTests(String arg0) { - super(arg0); - } - //~ Methods ======================================================================================================== - // ================================================================ - - public static void main(String[] args) { - junit.textui.TestRunner.run(StringSplitUtilsTests.class); - } - public void testSplitEachArrayElementAndCreateMapNormalOperation() { // note it ignores malformed entries (ie those without an equals sign) String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); - Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); + Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); assertEquals("rod", headerMap.get("username")); assertEquals("Contacts Realm", headerMap.get("realm")); @@ -70,7 +54,7 @@ public class StringSplitUtilsTests extends TestCase { public void testSplitEachArrayElementAndCreateMapRespectsInstructionNotToRemoveCharacters() { String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); - Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null); + Map headerMap = StringSplitUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null); assertEquals("\"rod\"", headerMap.get("username")); assertEquals("\"Contacts Realm\"", headerMap.get("realm")); diff --git a/core/src/test/java/org/springframework/security/vote/AuthenticatedVoterTests.java b/core/src/test/java/org/springframework/security/vote/AuthenticatedVoterTests.java index 5581f697c4..3754c43519 100644 --- a/core/src/test/java/org/springframework/security/vote/AuthenticatedVoterTests.java +++ b/core/src/test/java/org/springframework/security/vote/AuthenticatedVoterTests.java @@ -21,12 +21,11 @@ import junit.framework.TestCase; import org.springframework.security.Authentication; import org.springframework.security.ConfigAttribute; -import org.springframework.security.GrantedAuthority; -import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.SecurityConfig; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken; import org.springframework.security.providers.rememberme.RememberMeAuthenticationToken; +import org.springframework.security.util.AuthorityUtils; /** @@ -38,18 +37,15 @@ import org.springframework.security.providers.rememberme.RememberMeAuthenticatio public class AuthenticatedVoterTests extends TestCase { private Authentication createAnonymous() { - return new AnonymousAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}); + return new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")); } private Authentication createFullyAuthenticated() { - return new UsernamePasswordAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}); + return new UsernamePasswordAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")); } private Authentication createRememberMe() { - return new RememberMeAuthenticationToken("ignored", "ignored", - new GrantedAuthority[] {new GrantedAuthorityImpl("ignored")}); + return new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("ignored")); } public void testAnonymousWorks() { diff --git a/core/src/test/java/org/springframework/security/vote/ConsensusBasedTests.java b/core/src/test/java/org/springframework/security/vote/ConsensusBasedTests.java index bd96f667e4..bfc70bbf33 100644 --- a/core/src/test/java/org/springframework/security/vote/ConsensusBasedTests.java +++ b/core/src/test/java/org/springframework/security/vote/ConsensusBasedTests.java @@ -113,7 +113,7 @@ public class ConsensusBasedTests { RoleVoter roleVoter = new RoleVoter(); DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); - List voters = new Vector(); + List voters = new Vector(); voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); diff --git a/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java b/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java index 983a7e9dc4..186f4885fe 100644 --- a/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java +++ b/core/src/test/java/org/springframework/security/vote/DenyAgainVoter.java @@ -26,10 +26,8 @@ import java.util.List; *

* If the {@link ConfigAttribute#getAttribute()} has a value of * DENY_AGAIN_FOR_SURE, the voter will vote to deny access. - *

*

* All comparisons are case sensitive. - *

* * @author Ben Alex * @version $Id$ @@ -52,10 +50,10 @@ public class DenyAgainVoter implements AccessDecisionVoter { } public int vote(Authentication authentication, Object object, List attributes) { - Iterator iter = attributes.iterator(); + Iterator iter = attributes.iterator(); while (iter.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) iter.next(); + ConfigAttribute attribute = iter.next(); if (this.supports(attribute)) { return ACCESS_DENIED; diff --git a/core/src/test/java/org/springframework/security/vote/DenyVoter.java b/core/src/test/java/org/springframework/security/vote/DenyVoter.java index 18886cc4cc..d3152b353c 100644 --- a/core/src/test/java/org/springframework/security/vote/DenyVoter.java +++ b/core/src/test/java/org/springframework/security/vote/DenyVoter.java @@ -46,10 +46,10 @@ public class DenyVoter implements AccessDecisionVoter { } public int vote(Authentication authentication, Object object, List attributes) { - Iterator iter = attributes.iterator(); + Iterator iter = attributes.iterator(); while (iter.hasNext()) { - ConfigAttribute attribute = (ConfigAttribute) iter.next(); + ConfigAttribute attribute = iter.next(); if (this.supports(attribute)) { return ACCESS_DENIED; diff --git a/core/src/test/java/org/springframework/security/vote/LabelBasedAclVoterTests.java b/core/src/test/java/org/springframework/security/vote/LabelBasedAclVoterTests.java index c55b421bcc..9c017f0a96 100644 --- a/core/src/test/java/org/springframework/security/vote/LabelBasedAclVoterTests.java +++ b/core/src/test/java/org/springframework/security/vote/LabelBasedAclVoterTests.java @@ -62,7 +62,7 @@ public class LabelBasedAclVoterTests extends AbstractDependencyInjectionSpringCo public void testDoingSomethingForBlueUser() { setupContext("blueuser", "password"); - List dataList = sampleService.getTheSampleData(); + List dataList = sampleService.getTheSampleData(); assertNotNull(dataList); SampleBlockOfData block1 = (SampleBlockOfData) dataList.get(0); @@ -101,7 +101,7 @@ public class LabelBasedAclVoterTests extends AbstractDependencyInjectionSpringCo public void testDoingSomethingForMultiUser() { setupContext("multiuser", "password4"); - List dataList = sampleService.getTheSampleData(); + List dataList = sampleService.getTheSampleData(); assertNotNull(dataList); SampleBlockOfData block1 = (SampleBlockOfData) dataList.get(0); @@ -118,7 +118,7 @@ public class LabelBasedAclVoterTests extends AbstractDependencyInjectionSpringCo public void testDoingSomethingForOrangeUser() { setupContext("orangeuser", "password3"); - List dataList = sampleService.getTheSampleData(); + List dataList = sampleService.getTheSampleData(); assertNotNull(dataList); SampleBlockOfData block1 = (SampleBlockOfData) dataList.get(0); @@ -157,7 +157,7 @@ public class LabelBasedAclVoterTests extends AbstractDependencyInjectionSpringCo public void testDoingSomethingForSuperUser() { setupContext("superuser", "password2"); - List dataList = sampleService.getTheSampleData(); + List dataList = sampleService.getTheSampleData(); assertNotNull(dataList); SampleBlockOfData block1 = (SampleBlockOfData) dataList.get(0); diff --git a/core/src/test/java/org/springframework/security/vote/SampleService.java b/core/src/test/java/org/springframework/security/vote/SampleService.java index bab6a40bf6..841a7b91e3 100644 --- a/core/src/test/java/org/springframework/security/vote/SampleService.java +++ b/core/src/test/java/org/springframework/security/vote/SampleService.java @@ -27,5 +27,5 @@ public interface SampleService { public void doSomethingOnThis(SampleBlockOfData block1, SampleBlockOfData block2); - public List getTheSampleData(); + public List getTheSampleData(); } diff --git a/core/src/test/java/org/springframework/security/vote/SampleServiceImpl.java b/core/src/test/java/org/springframework/security/vote/SampleServiceImpl.java index 01a946b9aa..1d62307c29 100644 --- a/core/src/test/java/org/springframework/security/vote/SampleServiceImpl.java +++ b/core/src/test/java/org/springframework/security/vote/SampleServiceImpl.java @@ -49,13 +49,13 @@ public class SampleServiceImpl implements SampleService { } } - public List getTheSampleData() { + public List getTheSampleData() { if (logger.isDebugEnabled()) { logger.debug(SecurityContextHolder.getContext().getAuthentication().getName() + " is requesting some sample data."); } - List dataList = new Vector(); + List dataList = new Vector(); SampleBlockOfData block; block = new SampleBlockOfData(); diff --git a/core/src/test/java/org/springframework/security/vote/UnanimousBasedTests.java b/core/src/test/java/org/springframework/security/vote/UnanimousBasedTests.java index a5be59c0c3..be6ee55b6c 100644 --- a/core/src/test/java/org/springframework/security/vote/UnanimousBasedTests.java +++ b/core/src/test/java/org/springframework/security/vote/UnanimousBasedTests.java @@ -41,7 +41,7 @@ public class UnanimousBasedTests extends TestCase { RoleVoter roleVoter = new RoleVoter(); DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); - List voters = new Vector(); + List voters = new Vector(); voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); @@ -57,7 +57,7 @@ public class UnanimousBasedTests extends TestCase { DenyVoter denyForSureVoter = new DenyVoter(); DenyAgainVoter denyAgainForSureVoter = new DenyAgainVoter(); - List voters = new Vector(); + List voters = new Vector(); voters.add(roleVoter); voters.add(denyForSureVoter); voters.add(denyAgainForSureVoter); diff --git a/core/src/test/java/org/springframework/security/wrapper/SavedRequestAwareWrapperTests.java b/core/src/test/java/org/springframework/security/wrapper/SavedRequestAwareWrapperTests.java index 63384fe762..00b5fd0a03 100644 --- a/core/src/test/java/org/springframework/security/wrapper/SavedRequestAwareWrapperTests.java +++ b/core/src/test/java/org/springframework/security/wrapper/SavedRequestAwareWrapperTests.java @@ -44,6 +44,7 @@ public class SavedRequestAwareWrapperTests { } @Test + @SuppressWarnings("unchecked") public void savedRequesthHeaderIsReturnedIfSavedRequestIsSet() throws Exception { MockHttpServletRequest savedRequest = new MockHttpServletRequest(); savedRequest.addHeader("header", "savedheader"); @@ -63,6 +64,7 @@ public class SavedRequestAwareWrapperTests { } @Test + @SuppressWarnings("unchecked") public void wrappedRequestHeaderIsReturnedIfSavedRequestIsNotSet() throws Exception { MockHttpServletRequest wrappedRequest = new MockHttpServletRequest(); wrappedRequest.addHeader("header", "wrappedheader"); diff --git a/core/src/test/resources/org/springframework/security/util/filtertest-valid.xml b/core/src/test/resources/org/springframework/security/util/filtertest-valid.xml index 71c3e6b1a8..f7ab8a0f05 100644 --- a/core/src/test/resources/org/springframework/security/util/filtertest-valid.xml +++ b/core/src/test/resources/org/springframework/security/util/filtertest-valid.xml @@ -29,7 +29,7 @@ http://www.springframework.org/schema/security http://www.springframework.org/sc - + diff --git a/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java b/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java index d98cb3bd37..779a3d34c3 100755 --- a/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java +++ b/itest/context/src/main/java/org/springframework/security/integration/UserDetailsServiceImpl.java @@ -7,15 +7,15 @@ import org.springframework.transaction.annotation.Transactional; public class UserDetailsServiceImpl implements UserDetailsService{ - private UserRepository userRepository; - - @Transactional(readOnly=true) - public UserDetails loadUserByUsername(String username) { - return null; - } + private UserRepository userRepository; - @Required - public void setUserRepository(UserRepository userRepository) { - this.userRepository = userRepository; - } -} \ No newline at end of file + @Transactional(readOnly=true) + public UserDetails loadUserByUsername(String username) { + return null; + } + + @Required + public void setUserRepository(UserRepository userRepository) { + this.userRepository = userRepository; + } +} diff --git a/itest/context/src/main/java/org/springframework/security/integration/UserRepository.java b/itest/context/src/main/java/org/springframework/security/integration/UserRepository.java index 81909816e3..f873447da6 100755 --- a/itest/context/src/main/java/org/springframework/security/integration/UserRepository.java +++ b/itest/context/src/main/java/org/springframework/security/integration/UserRepository.java @@ -2,6 +2,6 @@ package org.springframework.security.integration; public interface UserRepository { - public void doSomething(); - + public void doSomething(); + } diff --git a/itest/context/src/test/java/org/springframework/security/integration/SEC933ApplicationContextTests.java b/itest/context/src/test/java/org/springframework/security/integration/SEC933ApplicationContextTests.java index 6eedfa36ae..68c3ab456f 100644 --- a/itest/context/src/test/java/org/springframework/security/integration/SEC933ApplicationContextTests.java +++ b/itest/context/src/test/java/org/springframework/security/integration/SEC933ApplicationContextTests.java @@ -13,11 +13,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) public class SEC933ApplicationContextTests { - @Autowired - private UserDetailsService userDetailsService; - - @Test - public void testSimpleApplicationContextBootstrap() throws Exception { - assertNotNull(userDetailsService); - } + @Autowired + private UserDetailsService userDetailsService; + + @Test + public void testSimpleApplicationContextBootstrap() throws Exception { + assertNotNull(userDetailsService); + } } diff --git a/itest/context/src/test/java/org/springframework/security/integration/StubUserRepository.java b/itest/context/src/test/java/org/springframework/security/integration/StubUserRepository.java index 908e970078..a5f2c8babf 100644 --- a/itest/context/src/test/java/org/springframework/security/integration/StubUserRepository.java +++ b/itest/context/src/test/java/org/springframework/security/integration/StubUserRepository.java @@ -2,6 +2,6 @@ package org.springframework.security.integration; public class StubUserRepository implements UserRepository { - public void doSomething() { - } + public void doSomething() { + } } \ No newline at end of file diff --git a/itest/web/src/test/java/org/springframework/security/integration/AbstractWebServerIntegrationTests.java b/itest/web/src/test/java/org/springframework/security/integration/AbstractWebServerIntegrationTests.java index acea68194b..93ef62c3a1 100644 --- a/itest/web/src/test/java/org/springframework/security/integration/AbstractWebServerIntegrationTests.java +++ b/itest/web/src/test/java/org/springframework/security/integration/AbstractWebServerIntegrationTests.java @@ -26,9 +26,9 @@ public abstract class AbstractWebServerIntegrationTests { protected final WebTester tester = new WebTester(); /** - * Override to set the application context files that should be loaded or return null - * to use web.xml. - */ + * Override to set the application context files that should be loaded or return null + * to use web.xml. + */ protected abstract String getContextConfigLocations(); protected String getContextPath() { @@ -37,43 +37,43 @@ public abstract class AbstractWebServerIntegrationTests { @BeforeClass public void startServer() throws Exception { - synchronized(SERVER_LOCK) { - if (server == null) { - //System.setProperty("DEBUG", "true"); - //System.setProperty("VERBOSE", "true"); - //System.setProperty("IGNORED", "true"); - server = new Server(0); - server.addHandler(createWebContext()); - server.start(); - tester.getTestContext().setBaseUrl(getBaseUrl()); - } - } + synchronized(SERVER_LOCK) { + if (server == null) { + //System.setProperty("DEBUG", "true"); + //System.setProperty("VERBOSE", "true"); + //System.setProperty("IGNORED", "true"); + server = new Server(0); + server.addHandler(createWebContext()); + server.start(); + tester.getTestContext().setBaseUrl(getBaseUrl()); + } + } } protected WebAppContext createWebContext() { WebAppContext webCtx = new WebAppContext("src/main/webapp", getContextPath()); - - if (StringUtils.hasText(getContextConfigLocations())) { - webCtx.addEventListener(new ContextLoaderListener()); - webCtx.getInitParams().put("contextConfigLocation", getContextConfigLocations()); - } - - return webCtx; + + if (StringUtils.hasText(getContextConfigLocations())) { + webCtx.addEventListener(new ContextLoaderListener()); + webCtx.getInitParams().put("contextConfigLocation", getContextConfigLocations()); + } + + return webCtx; } @AfterClass public void stopServer() throws Exception { - synchronized(SERVER_LOCK) { - if (server != null) { - server.stop(); - } - server = null; - } + synchronized(SERVER_LOCK) { + if (server != null) { + server.stop(); + } + server = null; + } } @AfterMethod public void resetWebConversation() { - tester.getTestContext().setWebClient(new WebConversation()); + tester.getTestContext().setWebClient(new WebConversation()); } private final String getBaseUrl() { @@ -93,7 +93,7 @@ public abstract class AbstractWebServerIntegrationTests { } // protected final HttpUnitDialog getDialog() { -// return tester.getDialog(); +// return tester.getDialog(); // } protected final void submit() { @@ -120,10 +120,10 @@ public abstract class AbstractWebServerIntegrationTests { // Security-specific utility methods - protected void login(String username, String password) { - assertFormPresent(); - setFormElement("j_username", username); - setFormElement("j_password", password); - submit(); - } + protected void login(String username, String password) { + assertFormPresent(); + setFormElement("j_username", username); + setFormElement("j_password", password); + submit(); + } } diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBaseException.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBaseException.java index da91b33e6a..d7d30effeb 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBaseException.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBaseException.java @@ -27,8 +27,8 @@ import org.springframework.security.AuthenticationException; */ public abstract class NtlmBaseException extends AuthenticationException { - public NtlmBaseException(final String msg) { - super(msg); - } + public NtlmBaseException(final String msg) { + super(msg); + } } diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBeginHandshakeException.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBeginHandshakeException.java index 4ebd67570d..9d22d7a7da 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBeginHandshakeException.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmBeginHandshakeException.java @@ -22,8 +22,8 @@ package org.springframework.security.ui.ntlm; */ public class NtlmBeginHandshakeException extends NtlmBaseException { - public NtlmBeginHandshakeException() { - super("NTLM"); - } + public NtlmBeginHandshakeException() { + super("NTLM"); + } } diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilter.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilter.java index 230459ee71..1cd2408f46 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilter.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilter.java @@ -84,10 +84,10 @@ import java.util.Properties; public class NtlmProcessingFilter extends SpringSecurityFilter implements InitializingBean { //~ Static fields/initializers ===================================================================================== - private static Log logger = LogFactory.getLog(NtlmProcessingFilter.class); + private static Log logger = LogFactory.getLog(NtlmProcessingFilter.class); - private static final String STATE_ATTR = "SpringSecurityNtlm"; - private static final String CHALLENGE_ATTR = "NtlmChal"; + private static final String STATE_ATTR = "SpringSecurityNtlm"; + private static final String CHALLENGE_ATTR = "NtlmChal"; private static final Integer BEGIN = new Integer(0); private static final Integer NEGOTIATE = new Integer(1); private static final Integer COMPLETE = new Integer(2); @@ -96,21 +96,21 @@ public class NtlmProcessingFilter extends SpringSecurityFilter implements Initia //~ Instance fields ================================================================================================ /** Should the filter load balance among multiple domain controllers, default false */ - private boolean loadBalance; + private boolean loadBalance; /** Should the domain name be stripped from the username, default true */ private boolean stripDomain = true; - /** Should the filter initiate NTLM negotiations, default true */ + /** Should the filter initiate NTLM negotiations, default true */ private boolean forceIdentification = true; /** Should the filter retry NTLM on authorization failure, default false */ private boolean retryOnAuthFailure; - private String soTimeout; - private String cachePolicy; - private String defaultDomain; - private String domainController; + private String soTimeout; + private String cachePolicy; + private String defaultDomain; + private String domainController; private AuthenticationManager authenticationManager; private AuthenticationDetailsSource authenticationDetailsSource = new WebAuthenticationDetailsSource(); diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilterEntryPoint.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilterEntryPoint.java index 9298efc3fd..2d04108f74 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilterEntryPoint.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmProcessingFilterEntryPoint.java @@ -72,8 +72,8 @@ public class NtlmProcessingFilterEntryPoint implements AuthenticationEntryPoint * @param request The {@link HttpServletRequest} object. * @param response Then {@link HttpServletResponse} object. * @param authException Either {@link NtlmBeginHandshakeException}, - * {@link NtlmType2MessageException}, or - * {@link AuthenticationException} + * {@link NtlmType2MessageException}, or + * {@link AuthenticationException} */ public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException { final HttpServletResponse resp = (HttpServletResponse) response; diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmType2MessageException.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmType2MessageException.java index a3cf285940..5b56a04038 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmType2MessageException.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmType2MessageException.java @@ -26,22 +26,22 @@ import org.springframework.security.context.SecurityContextHolder; */ public class NtlmType2MessageException extends NtlmBaseException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private final Authentication auth; + private final Authentication auth; - public NtlmType2MessageException(final String type2Msg) { - super("NTLM " + type2Msg); - auth = SecurityContextHolder.getContext().getAuthentication(); - } + public NtlmType2MessageException(final String type2Msg) { + super("NTLM " + type2Msg); + auth = SecurityContextHolder.getContext().getAuthentication(); + } - /** - * Preserve the existing Authentication object each time - * Internet Explorer does a POST. - */ - public void preserveAuthentication() { - if (auth != null) { - SecurityContextHolder.getContext().setAuthentication(auth); + /** + * Preserve the existing Authentication object each time + * Internet Explorer does a POST. + */ + public void preserveAuthentication() { + if (auth != null) { + SecurityContextHolder.getContext().setAuthentication(auth); } } diff --git a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmUsernamePasswordAuthenticationToken.java b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmUsernamePasswordAuthenticationToken.java index d0b0affc37..1886871664 100755 --- a/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmUsernamePasswordAuthenticationToken.java +++ b/ntlm/src/main/java/org/springframework/security/ui/ntlm/NtlmUsernamePasswordAuthenticationToken.java @@ -49,9 +49,9 @@ public class NtlmUsernamePasswordAuthenticationToken extends UsernamePasswordAut * Create an NTLM {@link UsernamePasswordAuthenticationToken} using the * JCIFS {@link NtlmPasswordAuthentication} object. * - * @param ntlmAuth The {@link NtlmPasswordAuthentication} object. - * @param stripDomain Uses just the username if true, - * otherwise use the username and domain name. + * @param ntlmAuth The {@link NtlmPasswordAuthentication} object. + * @param stripDomain Uses just the username if true, + * otherwise use the username and domain name. */ public NtlmUsernamePasswordAuthenticationToken(NtlmPasswordAuthentication ntlmAuth, boolean stripDomain) { super((stripDomain) ? ntlmAuth.getUsername() : ntlmAuth.getName(), DEFAULT_PASSWORD, NTLM_AUTHENTICATED); diff --git a/portlet/src/main/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptor.java b/portlet/src/main/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptor.java index 1ddec5c293..15008a1e11 100644 --- a/portlet/src/main/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptor.java +++ b/portlet/src/main/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptor.java @@ -95,343 +95,343 @@ import org.springframework.web.portlet.ModelAndView; * @version $Id$ */ public class PortletSessionContextIntegrationInterceptor - implements InitializingBean, HandlerInterceptor { + implements InitializingBean, HandlerInterceptor { - //~ Static fields/initializers ===================================================================================== + //~ Static fields/initializers ===================================================================================== - protected static final Log logger = LogFactory.getLog(PortletSessionContextIntegrationInterceptor.class); + protected static final Log logger = LogFactory.getLog(PortletSessionContextIntegrationInterceptor.class); - public static final String SPRING_SECURITY_CONTEXT_KEY = HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY; + public static final String SPRING_SECURITY_CONTEXT_KEY = HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY; - private static final String SESSION_EXISTED = PortletSessionContextIntegrationInterceptor.class.getName() + ".SESSION_EXISTED"; - private static final String CONTEXT_HASHCODE = PortletSessionContextIntegrationInterceptor.class.getName() + ".CONTEXT_HASHCODE"; + private static final String SESSION_EXISTED = PortletSessionContextIntegrationInterceptor.class.getName() + ".SESSION_EXISTED"; + private static final String CONTEXT_HASHCODE = PortletSessionContextIntegrationInterceptor.class.getName() + ".CONTEXT_HASHCODE"; - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - private Class context = SecurityContextImpl.class; + private Class context = SecurityContextImpl.class; - private Object contextObject; + private Object contextObject; - /** - * Indicates if this interceptor can create a PortletSession if - * needed (sessions are always created sparingly, but setting this value to - * false will prohibit sessions from ever being created). - * Defaults to true. Do not set to false if - * you are have set {@link #forceEagerSessionCreation} to true, - * as the properties would be in conflict. - */ - private boolean allowSessionCreation = true; + /** + * Indicates if this interceptor can create a PortletSession if + * needed (sessions are always created sparingly, but setting this value to + * false will prohibit sessions from ever being created). + * Defaults to true. Do not set to false if + * you are have set {@link #forceEagerSessionCreation} to true, + * as the properties would be in conflict. + */ + private boolean allowSessionCreation = true; - /** - * Indicates if this interceptor is required to create a PortletSession - * for every request before proceeding through the request process, even if the - * PortletSession would not ordinarily have been created. By - * default this is false, which is entirely appropriate for - * most circumstances as you do not want a PortletSession - * created unless the interceptor actually needs one. It is envisaged the main - * situation in which this property would be set to true is - * if using other interceptors that depend on a PortletSession - * already existing. This is only required in specialized cases, so leave it set to - * false unless you have an actual requirement and aware of the - * session creation overhead. - */ - private boolean forceEagerSessionCreation = false; + /** + * Indicates if this interceptor is required to create a PortletSession + * for every request before proceeding through the request process, even if the + * PortletSession would not ordinarily have been created. By + * default this is false, which is entirely appropriate for + * most circumstances as you do not want a PortletSession + * created unless the interceptor actually needs one. It is envisaged the main + * situation in which this property would be set to true is + * if using other interceptors that depend on a PortletSession + * already existing. This is only required in specialized cases, so leave it set to + * false unless you have an actual requirement and aware of the + * session creation overhead. + */ + private boolean forceEagerSessionCreation = false; - /** - * Indicates whether the SecurityContext will be cloned from - * the PortletSession. The default is to simply reference - * (the default is false). The default may cause issues if - * concurrent threads need to have a different security identity from other - * threads being concurrently processed that share the same - * PortletSession. In most normal environments this does not - * represent an issue, as changes to the security identity in one thread is - * allowed to affect the security identity in other threads associated with - * the same PortletSession. For unusual cases where this is not - * permitted, change this value to true and ensure the - * {@link #context} is set to a SecurityContext that - * implements {@link Cloneable} and overrides the clone() - * method. - */ - private boolean cloneFromPortletSession = false; + /** + * Indicates whether the SecurityContext will be cloned from + * the PortletSession. The default is to simply reference + * (the default is false). The default may cause issues if + * concurrent threads need to have a different security identity from other + * threads being concurrently processed that share the same + * PortletSession. In most normal environments this does not + * represent an issue, as changes to the security identity in one thread is + * allowed to affect the security identity in other threads associated with + * the same PortletSession. For unusual cases where this is not + * permitted, change this value to true and ensure the + * {@link #context} is set to a SecurityContext that + * implements {@link Cloneable} and overrides the clone() + * method. + */ + private boolean cloneFromPortletSession = false; - /** - * Indicates wether the APPLICATION_SCOPE mode of the - * PortletSession should be used for storing the - * SecurityContext. The default is true. - * This allows it to be shared between the portlets in the webapp and - * potentially with servlets in the webapp as well. If this is set to - * false, then the PORTLET_SCOPE will be used - * instead. - */ - private boolean useApplicationScopePortletSession = true; + /** + * Indicates wether the APPLICATION_SCOPE mode of the + * PortletSession should be used for storing the + * SecurityContext. The default is true. + * This allows it to be shared between the portlets in the webapp and + * potentially with servlets in the webapp as well. If this is set to + * false, then the PORTLET_SCOPE will be used + * instead. + */ + private boolean useApplicationScopePortletSession = true; - //~ Constructors =================================================================================================== + //~ Constructors =================================================================================================== - public PortletSessionContextIntegrationInterceptor() throws PortletException { - this.contextObject = generateNewContext(); - } + public PortletSessionContextIntegrationInterceptor() throws PortletException { + this.contextObject = generateNewContext(); + } - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() throws Exception { - // check that the value of context is legal - if ((this.context == null) || (!SecurityContext.class.isAssignableFrom(this.context))) { - throw new IllegalArgumentException("context must be defined and implement SecurityContext " - + "(typically use org.springframework.security.context.SecurityContextImpl; existing class is " - + this.context + ")"); - } + // check that the value of context is legal + if ((this.context == null) || (!SecurityContext.class.isAssignableFrom(this.context))) { + throw new IllegalArgumentException("context must be defined and implement SecurityContext " + + "(typically use org.springframework.security.context.SecurityContextImpl; existing class is " + + this.context + ")"); + } - // check that session creation options make sense - if ((forceEagerSessionCreation == true) && (allowSessionCreation == false)) { - throw new IllegalArgumentException( - "If using forceEagerSessionCreation, you must set allowSessionCreation to also be true"); - } - } + // check that session creation options make sense + if ((forceEagerSessionCreation == true) && (allowSessionCreation == false)) { + throw new IllegalArgumentException( + "If using forceEagerSessionCreation, you must set allowSessionCreation to also be true"); + } + } - public boolean preHandleAction(ActionRequest request, ActionResponse response, - Object handler) throws Exception { - // call to common preHandle method - return preHandle(request, response, handler); - } + public boolean preHandleAction(ActionRequest request, ActionResponse response, + Object handler) throws Exception { + // call to common preHandle method + return preHandle(request, response, handler); + } - public boolean preHandleRender(RenderRequest request, RenderResponse response, - Object handler) throws Exception { - // call to common preHandle method - return preHandle(request, response, handler); - } + public boolean preHandleRender(RenderRequest request, RenderResponse response, + Object handler) throws Exception { + // call to common preHandle method + return preHandle(request, response, handler); + } - public void postHandleRender(RenderRequest request, RenderResponse response, - Object handler, ModelAndView modelAndView) throws Exception { - // no-op - } + public void postHandleRender(RenderRequest request, RenderResponse response, + Object handler, ModelAndView modelAndView) throws Exception { + // no-op + } - public void afterActionCompletion(ActionRequest request, ActionResponse response, - Object handler, Exception ex) throws Exception { - // call to common afterCompletion method - afterCompletion(request, response, handler, ex); - } + public void afterActionCompletion(ActionRequest request, ActionResponse response, + Object handler, Exception ex) throws Exception { + // call to common afterCompletion method + afterCompletion(request, response, handler, ex); + } - public void afterRenderCompletion(RenderRequest request, RenderResponse response, - Object handler, Exception ex) throws Exception { - // call to common afterCompletion method - afterCompletion(request, response, handler, ex); - } + public void afterRenderCompletion(RenderRequest request, RenderResponse response, + Object handler, Exception ex) throws Exception { + // call to common afterCompletion method + afterCompletion(request, response, handler, ex); + } - private boolean preHandle(PortletRequest request, PortletResponse response, - Object handler) throws Exception { + private boolean preHandle(PortletRequest request, PortletResponse response, + Object handler) throws Exception { - PortletSession portletSession = null; - boolean portletSessionExistedAtStartOfRequest = false; + PortletSession portletSession = null; + boolean portletSessionExistedAtStartOfRequest = false; - // see if the portlet session already exists (or should be eagerly created) - try { - portletSession = request.getPortletSession(forceEagerSessionCreation); - } catch (IllegalStateException ignored) {} + // see if the portlet session already exists (or should be eagerly created) + try { + portletSession = request.getPortletSession(forceEagerSessionCreation); + } catch (IllegalStateException ignored) {} - // if there is a session, then see if there is a context to bring in - if (portletSession != null) { + // if there is a session, then see if there is a context to bring in + if (portletSession != null) { - // remember that the session already existed - portletSessionExistedAtStartOfRequest = true; + // remember that the session already existed + portletSessionExistedAtStartOfRequest = true; - // attempt to retrieve the context from the session - Object contextFromSessionObject = portletSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY, portletSessionScope()); + // attempt to retrieve the context from the session + Object contextFromSessionObject = portletSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY, portletSessionScope()); - // if we got a context then place it into the holder - if (contextFromSessionObject != null) { + // if we got a context then place it into the holder + if (contextFromSessionObject != null) { - // if we are supposed to clone it, then do so - if (cloneFromPortletSession) { - Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, - "Context must implement Clonable and provide a Object.clone() method"); - try { - Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); - if (!m.isAccessible()) { - m.setAccessible(true); - } - contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); - } - catch (Exception ex) { - ReflectionUtils.handleReflectionException(ex); - } - } + // if we are supposed to clone it, then do so + if (cloneFromPortletSession) { + Assert.isInstanceOf(Cloneable.class, contextFromSessionObject, + "Context must implement Clonable and provide a Object.clone() method"); + try { + Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {}); + if (!m.isAccessible()) { + m.setAccessible(true); + } + contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {}); + } + catch (Exception ex) { + ReflectionUtils.handleReflectionException(ex); + } + } - // if what we got is a valid context then place it into the holder, otherwise create a new one - if (contextFromSessionObject instanceof SecurityContext) { - if (logger.isDebugEnabled()) - logger.debug("Obtained from SPRING_SECURITY_CONTEXT a valid SecurityContext and " - + "set to SecurityContextHolder: '" + contextFromSessionObject + "'"); - SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject); - } else { - if (logger.isWarnEnabled()) - logger.warn("SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '" - + contextFromSessionObject - + "'; are you improperly modifying the PortletSession directly " - + "(you should always use SecurityContextHolder) or using the PortletSession attribute " - + "reserved for this class? - new SecurityContext instance associated with " - + "SecurityContextHolder"); - SecurityContextHolder.setContext(generateNewContext()); - } + // if what we got is a valid context then place it into the holder, otherwise create a new one + if (contextFromSessionObject instanceof SecurityContext) { + if (logger.isDebugEnabled()) + logger.debug("Obtained from SPRING_SECURITY_CONTEXT a valid SecurityContext and " + + "set to SecurityContextHolder: '" + contextFromSessionObject + "'"); + SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject); + } else { + if (logger.isWarnEnabled()) + logger.warn("SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '" + + contextFromSessionObject + + "'; are you improperly modifying the PortletSession directly " + + "(you should always use SecurityContextHolder) or using the PortletSession attribute " + + "reserved for this class? - new SecurityContext instance associated with " + + "SecurityContextHolder"); + SecurityContextHolder.setContext(generateNewContext()); + } - } else { + } else { - // there was no context in the session, so create a new context and put it in the holder - if (logger.isDebugEnabled()) - logger.debug("PortletSession returned null object for SPRING_SECURITY_CONTEXT - new " - + "SecurityContext instance associated with SecurityContextHolder"); - SecurityContextHolder.setContext(generateNewContext()); - } + // there was no context in the session, so create a new context and put it in the holder + if (logger.isDebugEnabled()) + logger.debug("PortletSession returned null object for SPRING_SECURITY_CONTEXT - new " + + "SecurityContext instance associated with SecurityContextHolder"); + SecurityContextHolder.setContext(generateNewContext()); + } - } else { + } else { - // there was no session, so create a new context and place it in the holder - if (logger.isDebugEnabled()) - logger.debug("No PortletSession currently exists - new SecurityContext instance " - + "associated with SecurityContextHolder"); - SecurityContextHolder.setContext(generateNewContext()); + // there was no session, so create a new context and place it in the holder + if (logger.isDebugEnabled()) + logger.debug("No PortletSession currently exists - new SecurityContext instance " + + "associated with SecurityContextHolder"); + SecurityContextHolder.setContext(generateNewContext()); - } + } - // place attributes onto the request to remember if the session existed and the hashcode of the context - request.setAttribute(SESSION_EXISTED, new Boolean(portletSessionExistedAtStartOfRequest)); - request.setAttribute(CONTEXT_HASHCODE, new Integer(SecurityContextHolder.getContext().hashCode())); + // place attributes onto the request to remember if the session existed and the hashcode of the context + request.setAttribute(SESSION_EXISTED, new Boolean(portletSessionExistedAtStartOfRequest)); + request.setAttribute(CONTEXT_HASHCODE, new Integer(SecurityContextHolder.getContext().hashCode())); - return true; - } + return true; + } - private void afterCompletion(PortletRequest request, PortletResponse response, - Object handler, Exception ex) throws Exception { + private void afterCompletion(PortletRequest request, PortletResponse response, + Object handler, Exception ex) throws Exception { - PortletSession portletSession = null; + PortletSession portletSession = null; - // retrieve the attributes that remember if the session existed and the hashcode of the context - boolean portletSessionExistedAtStartOfRequest = ((Boolean)request.getAttribute(SESSION_EXISTED)).booleanValue(); - int oldContextHashCode = ((Integer)request.getAttribute(CONTEXT_HASHCODE)).intValue(); + // retrieve the attributes that remember if the session existed and the hashcode of the context + boolean portletSessionExistedAtStartOfRequest = ((Boolean)request.getAttribute(SESSION_EXISTED)).booleanValue(); + int oldContextHashCode = ((Integer)request.getAttribute(CONTEXT_HASHCODE)).intValue(); - // try to retrieve an existing portlet session - try { - portletSession = request.getPortletSession(false); - } catch (IllegalStateException ignored) {} + // try to retrieve an existing portlet session + try { + portletSession = request.getPortletSession(false); + } catch (IllegalStateException ignored) {} - // if there is now no session but there was one at the beginning then it must have been invalidated - if ((portletSession == null) && portletSessionExistedAtStartOfRequest) { - if (logger.isDebugEnabled()) - logger.debug("PortletSession is now null, but was not null at start of request; " - + "session was invalidated, so do not create a new session"); - } + // if there is now no session but there was one at the beginning then it must have been invalidated + if ((portletSession == null) && portletSessionExistedAtStartOfRequest) { + if (logger.isDebugEnabled()) + logger.debug("PortletSession is now null, but was not null at start of request; " + + "session was invalidated, so do not create a new session"); + } - // create a new portlet session if we need to - if ((portletSession == null) && !portletSessionExistedAtStartOfRequest) { + // create a new portlet session if we need to + if ((portletSession == null) && !portletSessionExistedAtStartOfRequest) { - // if we're not allowed to create a new session, then report that - if (!allowSessionCreation) { - if (logger.isDebugEnabled()) - logger.debug("The PortletSession is currently null, and the " - + "PortletSessionContextIntegrationInterceptor is prohibited from creating a PortletSession " - + "(because the allowSessionCreation property is false) - SecurityContext thus not " - + "stored for next request"); - } - // if the context was changed during the request, then go ahead and create a session - else if (!contextObject.equals(SecurityContextHolder.getContext())) { - if (logger.isDebugEnabled()) - logger.debug("PortletSession being created as SecurityContextHolder contents are non-default"); - try { - portletSession = request.getPortletSession(true); - } catch (IllegalStateException ignored) {} - } - // if nothing in the context changed, then don't bother to create a session - else { - if (logger.isDebugEnabled()) - logger.debug("PortletSession is null, but SecurityContextHolder has not changed from default: ' " - + SecurityContextHolder.getContext() - + "'; not creating PortletSession or storing SecurityContextHolder contents"); - } - } + // if we're not allowed to create a new session, then report that + if (!allowSessionCreation) { + if (logger.isDebugEnabled()) + logger.debug("The PortletSession is currently null, and the " + + "PortletSessionContextIntegrationInterceptor is prohibited from creating a PortletSession " + + "(because the allowSessionCreation property is false) - SecurityContext thus not " + + "stored for next request"); + } + // if the context was changed during the request, then go ahead and create a session + else if (!contextObject.equals(SecurityContextHolder.getContext())) { + if (logger.isDebugEnabled()) + logger.debug("PortletSession being created as SecurityContextHolder contents are non-default"); + try { + portletSession = request.getPortletSession(true); + } catch (IllegalStateException ignored) {} + } + // if nothing in the context changed, then don't bother to create a session + else { + if (logger.isDebugEnabled()) + logger.debug("PortletSession is null, but SecurityContextHolder has not changed from default: ' " + + SecurityContextHolder.getContext() + + "'; not creating PortletSession or storing SecurityContextHolder contents"); + } + } - // if the session exists and the context has changes, then store the context back into the session - if ((portletSession != null) - && (SecurityContextHolder.getContext().hashCode() != oldContextHashCode)) { - portletSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext(), portletSessionScope()); - if (logger.isDebugEnabled()) - logger.debug("SecurityContext stored to PortletSession: '" - + SecurityContextHolder.getContext() + "'"); - } + // if the session exists and the context has changes, then store the context back into the session + if ((portletSession != null) + && (SecurityContextHolder.getContext().hashCode() != oldContextHashCode)) { + portletSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext(), portletSessionScope()); + if (logger.isDebugEnabled()) + logger.debug("SecurityContext stored to PortletSession: '" + + SecurityContextHolder.getContext() + "'"); + } - // remove the contents of the holder - SecurityContextHolder.clearContext(); - if (logger.isDebugEnabled()) - logger.debug("SecurityContextHolder set to new context, as request processing completed"); + // remove the contents of the holder + SecurityContextHolder.clearContext(); + if (logger.isDebugEnabled()) + logger.debug("SecurityContextHolder set to new context, as request processing completed"); - } + } - /** - * Creates a new SecurityContext object. The specific class is - * determined by the setting of the {@link #context} property. - * @return the new SecurityContext - * @throws PortletException if the creation throws an InstantiationException or - * an IllegalAccessException, then this method will wrap them in a - * PortletException - */ - public SecurityContext generateNewContext() throws PortletException { - try { - return (SecurityContext) this.context.newInstance(); - } catch (InstantiationException ie) { - throw new PortletException(ie); - } catch (IllegalAccessException iae) { - throw new PortletException(iae); - } - } + /** + * Creates a new SecurityContext object. The specific class is + * determined by the setting of the {@link #context} property. + * @return the new SecurityContext + * @throws PortletException if the creation throws an InstantiationException or + * an IllegalAccessException, then this method will wrap them in a + * PortletException + */ + public SecurityContext generateNewContext() throws PortletException { + try { + return (SecurityContext) this.context.newInstance(); + } catch (InstantiationException ie) { + throw new PortletException(ie); + } catch (IllegalAccessException iae) { + throw new PortletException(iae); + } + } - private int portletSessionScope() { - // return the appropriate scope setting based on our property value - return (this.useApplicationScopePortletSession ? - PortletSession.APPLICATION_SCOPE : PortletSession.PORTLET_SCOPE); - } + private int portletSessionScope() { + // return the appropriate scope setting based on our property value + return (this.useApplicationScopePortletSession ? + PortletSession.APPLICATION_SCOPE : PortletSession.PORTLET_SCOPE); + } - public Class getContext() { - return context; - } + public Class getContext() { + return context; + } - public void setContext(Class secureContext) { - this.context = secureContext; - } + public void setContext(Class secureContext) { + this.context = secureContext; + } - public boolean isAllowSessionCreation() { - return allowSessionCreation; - } + public boolean isAllowSessionCreation() { + return allowSessionCreation; + } - public void setAllowSessionCreation(boolean allowSessionCreation) { - this.allowSessionCreation = allowSessionCreation; - } + public void setAllowSessionCreation(boolean allowSessionCreation) { + this.allowSessionCreation = allowSessionCreation; + } - public boolean isForceEagerSessionCreation() { - return forceEagerSessionCreation; - } + public boolean isForceEagerSessionCreation() { + return forceEagerSessionCreation; + } - public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) { - this.forceEagerSessionCreation = forceEagerSessionCreation; - } + public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) { + this.forceEagerSessionCreation = forceEagerSessionCreation; + } - public boolean isCloneFromPortletSession() { - return cloneFromPortletSession; - } + public boolean isCloneFromPortletSession() { + return cloneFromPortletSession; + } - public void setCloneFromPortletSession(boolean cloneFromPortletSession) { - this.cloneFromPortletSession = cloneFromPortletSession; - } + public void setCloneFromPortletSession(boolean cloneFromPortletSession) { + this.cloneFromPortletSession = cloneFromPortletSession; + } - public boolean isUseApplicationScopePortletSession() { - return useApplicationScopePortletSession; - } + public boolean isUseApplicationScopePortletSession() { + return useApplicationScopePortletSession; + } - public void setUseApplicationScopePortletSession( - boolean useApplicationScopePortletSession) { - this.useApplicationScopePortletSession = useApplicationScopePortletSession; - } + public void setUseApplicationScopePortletSession( + boolean useApplicationScopePortletSession) { + this.useApplicationScopePortletSession = useApplicationScopePortletSession; + } } diff --git a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletAuthenticationDetails.java b/portlet/src/main/java/org/springframework/security/ui/portlet/PortletAuthenticationDetails.java index dbe2870ed3..a02bb1116c 100644 --- a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletAuthenticationDetails.java +++ b/portlet/src/main/java/org/springframework/security/ui/portlet/PortletAuthenticationDetails.java @@ -28,6 +28,6 @@ public class PortletAuthenticationDetails implements Serializable { } public String toString() { - return "User info: " + userInfo; + return "User info: " + userInfo; } } diff --git a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletProcessingInterceptor.java b/portlet/src/main/java/org/springframework/security/ui/portlet/PortletProcessingInterceptor.java index 06307c1009..1e61522ab5 100644 --- a/portlet/src/main/java/org/springframework/security/ui/portlet/PortletProcessingInterceptor.java +++ b/portlet/src/main/java/org/springframework/security/ui/portlet/PortletProcessingInterceptor.java @@ -83,228 +83,228 @@ import org.springframework.web.portlet.ModelAndView; */ public class PortletProcessingInterceptor implements HandlerInterceptor, InitializingBean { - //~ Static fields/initializers ===================================================================================== + //~ Static fields/initializers ===================================================================================== - private static final Log logger = LogFactory.getLog(PortletProcessingInterceptor.class); + private static final Log logger = LogFactory.getLog(PortletProcessingInterceptor.class); - //~ Instance fields ================================================================================================ + //~ Instance fields ================================================================================================ - private AuthenticationManager authenticationManager; + private AuthenticationManager authenticationManager; - private List userNameAttributes; - - private AuthenticationDetailsSource authenticationDetailsSource; - - private boolean useAuthTypeAsCredentials = false; + private List userNameAttributes; - public PortletProcessingInterceptor() { - authenticationDetailsSource = new AuthenticationDetailsSourceImpl(); - ((AuthenticationDetailsSourceImpl)authenticationDetailsSource).setClazz(PortletAuthenticationDetails.class); + private AuthenticationDetailsSource authenticationDetailsSource; + + private boolean useAuthTypeAsCredentials = false; + + public PortletProcessingInterceptor() { + authenticationDetailsSource = new AuthenticationDetailsSourceImpl(); + ((AuthenticationDetailsSourceImpl)authenticationDetailsSource).setClazz(PortletAuthenticationDetails.class); } - //~ Methods ======================================================================================================== + //~ Methods ======================================================================================================== - public void afterPropertiesSet() throws Exception { - Assert.notNull(authenticationManager, "An AuthenticationManager must be set"); - } + public void afterPropertiesSet() throws Exception { + Assert.notNull(authenticationManager, "An AuthenticationManager must be set"); + } - public boolean preHandleAction(ActionRequest request, ActionResponse response, - Object handler) throws Exception { - return preHandle(request, response, handler); - } + public boolean preHandleAction(ActionRequest request, ActionResponse response, + Object handler) throws Exception { + return preHandle(request, response, handler); + } - public boolean preHandleRender(RenderRequest request, - RenderResponse response, Object handler) throws Exception { - return preHandle(request, response, handler); - } + public boolean preHandleRender(RenderRequest request, + RenderResponse response, Object handler) throws Exception { + return preHandle(request, response, handler); + } - public void postHandleRender(RenderRequest request, RenderResponse response, - Object handler, ModelAndView modelAndView) throws Exception { - } + public void postHandleRender(RenderRequest request, RenderResponse response, + Object handler, ModelAndView modelAndView) throws Exception { + } - public void afterActionCompletion(ActionRequest request, ActionResponse response, - Object handler, Exception ex) throws Exception { - } + public void afterActionCompletion(ActionRequest request, ActionResponse response, + Object handler, Exception ex) throws Exception { + } - public void afterRenderCompletion(RenderRequest request, RenderResponse response, - Object handler, Exception ex) throws Exception { - } + public void afterRenderCompletion(RenderRequest request, RenderResponse response, + Object handler, Exception ex) throws Exception { + } - /** - * Common preHandle method for both the action and render phases of the interceptor. - */ - private boolean preHandle(PortletRequest request, PortletResponse response, - Object handler) throws Exception { + /** + * Common preHandle method for both the action and render phases of the interceptor. + */ + private boolean preHandle(PortletRequest request, PortletResponse response, + Object handler) throws Exception { - // get the SecurityContext - SecurityContext ctx = SecurityContextHolder.getContext(); + // get the SecurityContext + SecurityContext ctx = SecurityContextHolder.getContext(); - if (logger.isDebugEnabled()) - logger.debug("Checking secure context token: " + ctx.getAuthentication()); + if (logger.isDebugEnabled()) + logger.debug("Checking secure context token: " + ctx.getAuthentication()); - // if there is no existing Authentication object, then lets create one - if (ctx.getAuthentication() == null) { + // if there is no existing Authentication object, then lets create one + if (ctx.getAuthentication() == null) { - try { + try { - // build the authentication request from the PortletRequest - PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken( - getPrincipalFromRequest(request), - getCredentialsFromRequest(request)); + // build the authentication request from the PortletRequest + PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken( + getPrincipalFromRequest(request), + getCredentialsFromRequest(request)); - // put the PortletRequest into the authentication request as the "details" - authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); + // put the PortletRequest into the authentication request as the "details" + authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); - if (logger.isDebugEnabled()) - logger.debug("Beginning authentication request for user '" + authRequest.getName() + "'"); + if (logger.isDebugEnabled()) + logger.debug("Beginning authentication request for user '" + authRequest.getName() + "'"); - onPreAuthentication(request, response); + onPreAuthentication(request, response); - // ask the authentication manager to authenticate the request - // it will throw an AuthenticationException if it fails, otherwise it succeeded - Authentication authResult = authenticationManager.authenticate(authRequest); + // ask the authentication manager to authenticate the request + // it will throw an AuthenticationException if it fails, otherwise it succeeded + Authentication authResult = authenticationManager.authenticate(authRequest); - // process a successful authentication - if (logger.isDebugEnabled()) { - logger.debug("Authentication success: " + authResult); - } - - ctx.setAuthentication(authResult); - onSuccessfulAuthentication(request, response, authResult); + // process a successful authentication + if (logger.isDebugEnabled()) { + logger.debug("Authentication success: " + authResult); + } - } catch (AuthenticationException failed) { - // process an unsuccessful authentication - if (logger.isDebugEnabled()) { - logger.debug("Authentication failed - updating ContextHolder to contain null Authentication", failed); - } - ctx.setAuthentication(null); - request.getPortletSession().setAttribute( - AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, - failed, PortletSession.APPLICATION_SCOPE); - onUnsuccessfulAuthentication(request, response, failed); - } - } + ctx.setAuthentication(authResult); + onSuccessfulAuthentication(request, response, authResult); - return true; - } + } catch (AuthenticationException failed) { + // process an unsuccessful authentication + if (logger.isDebugEnabled()) { + logger.debug("Authentication failed - updating ContextHolder to contain null Authentication", failed); + } + ctx.setAuthentication(null); + request.getPortletSession().setAttribute( + AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, + failed, PortletSession.APPLICATION_SCOPE); + onUnsuccessfulAuthentication(request, response, failed); + } + } - /** - * This method attempts to extract a principal from the portlet request. - * According to the JSR 168 spec, the PortletRequest should return the name - * of the user in the getRemoteUser() method. It should also provide a - * java.security.Principal object from the getUserPrincipal() - * method. We will first try these to come up with a valid username. - *

Unfortunately, some portals do not properly return these values for authenticated - * users. So, if neither of those succeeds and if the userNameAttributes - * property has been populated, then we will search through the USER_INFO - * map from the request to see if we can find a valid username. - *

This method can be overridden by subclasses to provide special handling - * for portals with weak support for the JSR 168 spec.

- * @param request the portlet request object - * @return the determined principal object, or null if none found - */ - protected Object getPrincipalFromRequest(PortletRequest request) { + return true; + } - // first try getRemoteUser() - String remoteUser = request.getRemoteUser(); - if (remoteUser != null) { - return remoteUser; - } + /** + * This method attempts to extract a principal from the portlet request. + * According to the JSR 168 spec, the PortletRequest should return the name + * of the user in the getRemoteUser() method. It should also provide a + * java.security.Principal object from the getUserPrincipal() + * method. We will first try these to come up with a valid username. + *

Unfortunately, some portals do not properly return these values for authenticated + * users. So, if neither of those succeeds and if the userNameAttributes + * property has been populated, then we will search through the USER_INFO + * map from the request to see if we can find a valid username. + *

This method can be overridden by subclasses to provide special handling + * for portals with weak support for the JSR 168 spec.

+ * @param request the portlet request object + * @return the determined principal object, or null if none found + */ + protected Object getPrincipalFromRequest(PortletRequest request) { - // next try getUserPrincipal() - Principal userPrincipal = request.getUserPrincipal(); - if (userPrincipal != null) { - String userPrincipalName = userPrincipal.getName(); - if (userPrincipalName != null) { - return userPrincipalName; - } - } + // first try getRemoteUser() + String remoteUser = request.getRemoteUser(); + if (remoteUser != null) { + return remoteUser; + } - // last try entries in USER_INFO if any attributes were defined - if (this.userNameAttributes != null) { - Map userInfo = null; - try { - userInfo = (Map)request.getAttribute(PortletRequest.USER_INFO); - } catch (Exception e) { - logger.warn("unable to retrieve USER_INFO map from portlet request", e); - } - if (userInfo != null) { - Iterator i = this.userNameAttributes.iterator(); - while(i.hasNext()) { - Object principal = (String)userInfo.get(i.next()); - if (principal != null) { - return principal; - } - } - } - } + // next try getUserPrincipal() + Principal userPrincipal = request.getUserPrincipal(); + if (userPrincipal != null) { + String userPrincipalName = userPrincipal.getName(); + if (userPrincipalName != null) { + return userPrincipalName; + } + } - // none found so return null - return null; - } + // last try entries in USER_INFO if any attributes were defined + if (this.userNameAttributes != null) { + Map userInfo = null; + try { + userInfo = (Map)request.getAttribute(PortletRequest.USER_INFO); + } catch (Exception e) { + logger.warn("unable to retrieve USER_INFO map from portlet request", e); + } + if (userInfo != null) { + Iterator i = this.userNameAttributes.iterator(); + while(i.hasNext()) { + Object principal = (String)userInfo.get(i.next()); + if (principal != null) { + return principal; + } + } + } + } - /** - * This method attempts to extract a credentials from the portlet request. - * We are trusting the portal framework to authenticate the user, so all - * we are really doing is trying to put something intelligent in here to - * indicate the user is authenticated. According to the JSR 168 spec, - * PortletRequest.getAuthType() should return a non-null value if the - * user is authenticated and should be null if not authenticated. So we - * will use this as the credentials and the token will be trusted as - * authenticated if the credentials are not null. - *

This method can be overridden by subclasses to provide special handling - * for portals with weak support for the JSR 168 spec. If that is done, - * be sure the value is non-null for authenticated users and null for - * non-authenticated users.

- * @param request the portlet request object - * @return the determined credentials object, or null if none found - */ - protected Object getCredentialsFromRequest(PortletRequest request) { - if (useAuthTypeAsCredentials) { - return request.getAuthType(); - } - - return "dummy"; - } + // none found so return null + return null; + } - /** - * Callback for custom processing prior to the authentication attempt. - * @param request the portlet request to be authenticated - * @param response the portlet response to be authenticated - * @throws AuthenticationException to indicate that authentication attempt is not valid and should be terminated - * @throws IOException - */ - protected void onPreAuthentication(PortletRequest request, PortletResponse response) - throws AuthenticationException, IOException {} + /** + * This method attempts to extract a credentials from the portlet request. + * We are trusting the portal framework to authenticate the user, so all + * we are really doing is trying to put something intelligent in here to + * indicate the user is authenticated. According to the JSR 168 spec, + * PortletRequest.getAuthType() should return a non-null value if the + * user is authenticated and should be null if not authenticated. So we + * will use this as the credentials and the token will be trusted as + * authenticated if the credentials are not null. + *

This method can be overridden by subclasses to provide special handling + * for portals with weak support for the JSR 168 spec. If that is done, + * be sure the value is non-null for authenticated users and null for + * non-authenticated users.

+ * @param request the portlet request object + * @return the determined credentials object, or null if none found + */ + protected Object getCredentialsFromRequest(PortletRequest request) { + if (useAuthTypeAsCredentials) { + return request.getAuthType(); + } - /** - * Callback for custom processing after a successful authentication attempt. - * @param request the portlet request that was authenticated - * @param response the portlet response that was authenticated - * @param authResult the resulting Authentication object - * @throws IOException - */ - protected void onSuccessfulAuthentication(PortletRequest request, PortletResponse response, Authentication authResult) - throws IOException {} + return "dummy"; + } - /** - * Callback for custom processing after an unsuccessful authentication attempt. - * @param request the portlet request that failed authentication - * @param response the portlet response that failed authentication - * @param failed the AuthenticationException that occurred - * @throws IOException - */ - protected void onUnsuccessfulAuthentication(PortletRequest request, PortletResponse response, AuthenticationException failed) - throws IOException {} + /** + * Callback for custom processing prior to the authentication attempt. + * @param request the portlet request to be authenticated + * @param response the portlet response to be authenticated + * @throws AuthenticationException to indicate that authentication attempt is not valid and should be terminated + * @throws IOException + */ + protected void onPreAuthentication(PortletRequest request, PortletResponse response) + throws AuthenticationException, IOException {} + + /** + * Callback for custom processing after a successful authentication attempt. + * @param request the portlet request that was authenticated + * @param response the portlet response that was authenticated + * @param authResult the resulting Authentication object + * @throws IOException + */ + protected void onSuccessfulAuthentication(PortletRequest request, PortletResponse response, Authentication authResult) + throws IOException {} + + /** + * Callback for custom processing after an unsuccessful authentication attempt. + * @param request the portlet request that failed authentication + * @param response the portlet response that failed authentication + * @param failed the AuthenticationException that occurred + * @throws IOException + */ + protected void onUnsuccessfulAuthentication(PortletRequest request, PortletResponse response, AuthenticationException failed) + throws IOException {} - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } - public void setUserNameAttributes(List userNameAttributes) { - this.userNameAttributes = userNameAttributes; - } + public void setUserNameAttributes(List userNameAttributes) { + this.userNameAttributes = userNameAttributes; + } public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) { this.authenticationDetailsSource = authenticationDetailsSource; @@ -313,10 +313,10 @@ public class PortletProcessingInterceptor implements HandlerInterceptor, Initial /** * It true, the "authType" proerty of the PortletRequest will be used as the credentials. * Defaults to false. - * + * * @param useAuthTypeAsCredentials */ - public void setUseAuthTypeAsCredentials(boolean useAuthTypeAsCredentials) { - this.useAuthTypeAsCredentials = useAuthTypeAsCredentials; - } + public void setUseAuthTypeAsCredentials(boolean useAuthTypeAsCredentials) { + this.useAuthTypeAsCredentials = useAuthTypeAsCredentials; + } } diff --git a/portlet/src/test/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptorTests.java b/portlet/src/test/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptorTests.java index 9a6619ad94..e3a3f736c4 100644 --- a/portlet/src/test/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptorTests.java +++ b/portlet/src/test/java/org/springframework/security/context/PortletSessionContextIntegrationInterceptorTests.java @@ -39,334 +39,324 @@ import org.springframework.mock.web.portlet.MockRenderResponse; */ public class PortletSessionContextIntegrationInterceptorTests extends TestCase { - //~ Constructors =================================================================================================== - - public PortletSessionContextIntegrationInterceptorTests() { - super(); - } - - public PortletSessionContextIntegrationInterceptorTests(String arg0) { - super(arg0); - } - - //~ Methods ======================================================================================================== - - public void setUp() throws Exception { - super.setUp(); - SecurityContextHolder.clearContext(); - } - - public void tearDown() throws Exception { - super.tearDown(); - SecurityContextHolder.clearContext(); - } - - public void testDetectsIncompatibleSessionProperties() throws Exception { - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - try { - interceptor.setAllowSessionCreation(false); - interceptor.setForceEagerSessionCreation(true); - interceptor.afterPropertiesSet(); - fail("Shown have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // ignore - } - interceptor.setAllowSessionCreation(true); - interceptor.afterPropertiesSet(); - } - - public void testDetectsMissingOrInvalidContext() throws Exception { - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - try { - interceptor.setContext(null); - interceptor.afterPropertiesSet(); - fail("Shown have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // ignore - } - try { - interceptor.setContext(Integer.class); - assertEquals(Integer.class, interceptor.getContext()); - interceptor.afterPropertiesSet(); - fail("Shown have thrown IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // ignore - } - } - - public void testNormalRenderRequestProcessing() throws Exception { - - // Build an Authentication object we simulate came from PortletSession - PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); - PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); - - // Build a Context to store in PortletSession (simulating prior request) - SecurityContext sc = new SecurityContextImpl(); - sc.setAuthentication(sessionPrincipal); - - // Build mock request and response - MockRenderRequest request = PortletTestUtils.createRenderRequest(); - MockRenderResponse response = PortletTestUtils.createRenderResponse(); - request.getPortletSession().setAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - sc, PortletSession.APPLICATION_SCOPE); - - // Prepare interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Verify the SecurityContextHolder starts empty - assertNull(SecurityContextHolder.getContext().getAuthentication()); - - // Run preHandleRender phase and verify SecurityContextHolder contains our Authentication - interceptor.preHandleRender(request, response, null); - assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); - - // Run postHandleRender phase and verify the SecurityContextHolder still contains our Authentication - interceptor.postHandleRender(request, response, null, null); - assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); - - // Run afterRenderCompletion phase and verify the SecurityContextHolder is empty - interceptor.afterRenderCompletion(request, response, null, null); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - } - - public void testNormalActionRequestProcessing() throws Exception { - - // Build an Authentication object we simulate came from PortletSession - PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); - PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); - - // Build a Context to store in PortletSession (simulating prior request) - SecurityContext sc = new SecurityContextImpl(); - sc.setAuthentication(sessionPrincipal); - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - request.getPortletSession().setAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - sc, PortletSession.APPLICATION_SCOPE); - - // Prepare interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Verify the SecurityContextHolder starts empty - assertNull(SecurityContextHolder.getContext().getAuthentication()); - - // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication - interceptor.preHandleAction(request, response, null); - assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); - - // Run afterActionCompletion phase and verify the SecurityContextHolder is empty - interceptor.afterActionCompletion(request, response, null, null); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - } - - public void testUpdatesCopiedBackIntoSession() throws Exception { - - // Build an Authentication object we simulate came from PortletSession - PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); - PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); - - // Build a Context to store in PortletSession (simulating prior request) - SecurityContext sc = new SecurityContextImpl(); - sc.setAuthentication(sessionPrincipal); - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - request.getPortletSession().setAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - sc, PortletSession.APPLICATION_SCOPE); - - // Prepare interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Verify the SecurityContextHolder starts empty - assertNull(SecurityContextHolder.getContext().getAuthentication()); - - // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication - interceptor.preHandleAction(request, response, null); - assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); - - // Perform updates to principal - sessionPrincipal = PortletTestUtils.createAuthenticatedToken( - new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); - baselinePrincipal = PortletTestUtils.createAuthenticatedToken( - new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); - - // Store updated principal into SecurityContextHolder - SecurityContextHolder.getContext().setAuthentication(sessionPrincipal); - - // Run afterActionCompletion phase and verify the SecurityContextHolder is empty - interceptor.afterActionCompletion(request, response, null, null); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - - // Verify the new principal is stored in the session - sc = (SecurityContext)request.getPortletSession().getAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - PortletSession.APPLICATION_SCOPE); - assertEquals(baselinePrincipal, sc.getAuthentication()); - } - - public void testPortletSessionCreatedWhenContextHolderChanges() throws Exception { - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - - // Prepare the interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Execute the interceptor - interceptor.preHandleAction(request, response, null); - PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); - SecurityContextHolder.getContext().setAuthentication(principal); - interceptor.afterActionCompletion(request, response, null, null); - - // Verify Authentication is in the PortletSession - SecurityContext sc = (SecurityContext)request.getPortletSession(false). - getAttribute(PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, PortletSession.APPLICATION_SCOPE); - assertEquals(principal, ((SecurityContext)sc).getAuthentication()); - } - - public void testPortletSessionEagerlyCreatedWhenDirected() throws Exception { - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - - // Prepare the interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.setForceEagerSessionCreation(true); // non-default - interceptor.afterPropertiesSet(); - - // Execute the interceptor - interceptor.preHandleAction(request, response, null); - interceptor.afterActionCompletion(request, response, null, null); - - // Check the session is not null - assertNotNull(request.getPortletSession(false)); - } - - public void testPortletSessionNotCreatedUnlessContextHolderChanges() throws Exception { - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - - // Prepare the interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Execute the interceptor - interceptor.preHandleAction(request, response, null); - interceptor.afterActionCompletion(request, response, null, null); - - // Check the session is null - assertNull(request.getPortletSession(false)); - } - - public void testPortletSessionWithNonContextInWellKnownLocationIsOverwritten() - throws Exception { - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - request.getPortletSession().setAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - "NOT_A_CONTEXT_OBJECT", PortletSession.APPLICATION_SCOPE); - - // Prepare the interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.afterPropertiesSet(); - - // Execute the interceptor - interceptor.preHandleAction(request, response, null); - PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); - SecurityContextHolder.getContext().setAuthentication(principal); - interceptor.afterActionCompletion(request, response, null, null); - - // Verify Authentication is in the PortletSession - SecurityContext sc = (SecurityContext)request.getPortletSession(false). - getAttribute(PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, PortletSession.APPLICATION_SCOPE); - assertEquals(principal, ((SecurityContext)sc).getAuthentication()); - } - - public void testPortletSessionCreationNotAllowed() throws Exception { - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - - // Prepare the interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.setAllowSessionCreation(false); // non-default - interceptor.afterPropertiesSet(); - - // Execute the interceptor - interceptor.preHandleAction(request, response, null); - PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); - SecurityContextHolder.getContext().setAuthentication(principal); - interceptor.afterActionCompletion(request, response, null, null); - - // Check the session is null - assertNull(request.getPortletSession(false)); - } - - public void testUsePortletScopeSession() throws Exception { - - // Build an Authentication object we simulate came from PortletSession - PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); - PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); - - // Build a Context to store in PortletSession (simulating prior request) - SecurityContext sc = new SecurityContextImpl(); - sc.setAuthentication(sessionPrincipal); - - // Build mock request and response - MockActionRequest request = PortletTestUtils.createActionRequest(); - MockActionResponse response = PortletTestUtils.createActionResponse(); - request.getPortletSession().setAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - sc, PortletSession.PORTLET_SCOPE); - - // Prepare interceptor - PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); - interceptor.setUseApplicationScopePortletSession(false); // non-default - interceptor.afterPropertiesSet(); - - // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication - interceptor.preHandleAction(request, response, null); - assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); - - // Perform updates to principal - sessionPrincipal = PortletTestUtils.createAuthenticatedToken( - new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); - baselinePrincipal = PortletTestUtils.createAuthenticatedToken( - new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, - new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); - - // Store updated principal into SecurityContextHolder - SecurityContextHolder.getContext().setAuthentication(sessionPrincipal); - - // Run afterActionCompletion phase and verify the SecurityContextHolder is empty - interceptor.afterActionCompletion(request, response, null, null); - assertNull(SecurityContextHolder.getContext().getAuthentication()); - - // Verify the new principal is stored in the session - sc = (SecurityContext)request.getPortletSession().getAttribute( - PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, - PortletSession.PORTLET_SCOPE); - assertEquals(baselinePrincipal, sc.getAuthentication()); - } + //~ Methods ======================================================================================================== + + public void setUp() throws Exception { + super.setUp(); + SecurityContextHolder.clearContext(); + } + + public void tearDown() throws Exception { + super.tearDown(); + SecurityContextHolder.clearContext(); + } + + public void testDetectsIncompatibleSessionProperties() throws Exception { + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + try { + interceptor.setAllowSessionCreation(false); + interceptor.setForceEagerSessionCreation(true); + interceptor.afterPropertiesSet(); + fail("Shown have thrown IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + // ignore + } + interceptor.setAllowSessionCreation(true); + interceptor.afterPropertiesSet(); + } + + public void testDetectsMissingOrInvalidContext() throws Exception { + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + try { + interceptor.setContext(null); + interceptor.afterPropertiesSet(); + fail("Shown have thrown IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + // ignore + } + try { + interceptor.setContext(Integer.class); + assertEquals(Integer.class, interceptor.getContext()); + interceptor.afterPropertiesSet(); + fail("Shown have thrown IllegalArgumentException"); + } catch (IllegalArgumentException expected) { + // ignore + } + } + + public void testNormalRenderRequestProcessing() throws Exception { + + // Build an Authentication object we simulate came from PortletSession + PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); + PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); + + // Build a Context to store in PortletSession (simulating prior request) + SecurityContext sc = new SecurityContextImpl(); + sc.setAuthentication(sessionPrincipal); + + // Build mock request and response + MockRenderRequest request = PortletTestUtils.createRenderRequest(); + MockRenderResponse response = PortletTestUtils.createRenderResponse(); + request.getPortletSession().setAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + sc, PortletSession.APPLICATION_SCOPE); + + // Prepare interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Verify the SecurityContextHolder starts empty + assertNull(SecurityContextHolder.getContext().getAuthentication()); + + // Run preHandleRender phase and verify SecurityContextHolder contains our Authentication + interceptor.preHandleRender(request, response, null); + assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); + + // Run postHandleRender phase and verify the SecurityContextHolder still contains our Authentication + interceptor.postHandleRender(request, response, null, null); + assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); + + // Run afterRenderCompletion phase and verify the SecurityContextHolder is empty + interceptor.afterRenderCompletion(request, response, null, null); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + } + + public void testNormalActionRequestProcessing() throws Exception { + + // Build an Authentication object we simulate came from PortletSession + PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); + PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); + + // Build a Context to store in PortletSession (simulating prior request) + SecurityContext sc = new SecurityContextImpl(); + sc.setAuthentication(sessionPrincipal); + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + request.getPortletSession().setAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + sc, PortletSession.APPLICATION_SCOPE); + + // Prepare interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Verify the SecurityContextHolder starts empty + assertNull(SecurityContextHolder.getContext().getAuthentication()); + + // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication + interceptor.preHandleAction(request, response, null); + assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); + + // Run afterActionCompletion phase and verify the SecurityContextHolder is empty + interceptor.afterActionCompletion(request, response, null, null); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + } + + public void testUpdatesCopiedBackIntoSession() throws Exception { + + // Build an Authentication object we simulate came from PortletSession + PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); + PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); + + // Build a Context to store in PortletSession (simulating prior request) + SecurityContext sc = new SecurityContextImpl(); + sc.setAuthentication(sessionPrincipal); + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + request.getPortletSession().setAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + sc, PortletSession.APPLICATION_SCOPE); + + // Prepare interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Verify the SecurityContextHolder starts empty + assertNull(SecurityContextHolder.getContext().getAuthentication()); + + // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication + interceptor.preHandleAction(request, response, null); + assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); + + // Perform updates to principal + sessionPrincipal = PortletTestUtils.createAuthenticatedToken( + new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, + new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); + baselinePrincipal = PortletTestUtils.createAuthenticatedToken( + new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, + new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); + + // Store updated principal into SecurityContextHolder + SecurityContextHolder.getContext().setAuthentication(sessionPrincipal); + + // Run afterActionCompletion phase and verify the SecurityContextHolder is empty + interceptor.afterActionCompletion(request, response, null, null); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + + // Verify the new principal is stored in the session + sc = (SecurityContext)request.getPortletSession().getAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + PortletSession.APPLICATION_SCOPE); + assertEquals(baselinePrincipal, sc.getAuthentication()); + } + + public void testPortletSessionCreatedWhenContextHolderChanges() throws Exception { + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + + // Prepare the interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Execute the interceptor + interceptor.preHandleAction(request, response, null); + PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); + SecurityContextHolder.getContext().setAuthentication(principal); + interceptor.afterActionCompletion(request, response, null, null); + + // Verify Authentication is in the PortletSession + SecurityContext sc = (SecurityContext)request.getPortletSession(false). + getAttribute(PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, PortletSession.APPLICATION_SCOPE); + assertEquals(principal, ((SecurityContext)sc).getAuthentication()); + } + + public void testPortletSessionEagerlyCreatedWhenDirected() throws Exception { + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + + // Prepare the interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.setForceEagerSessionCreation(true); // non-default + interceptor.afterPropertiesSet(); + + // Execute the interceptor + interceptor.preHandleAction(request, response, null); + interceptor.afterActionCompletion(request, response, null, null); + + // Check the session is not null + assertNotNull(request.getPortletSession(false)); + } + + public void testPortletSessionNotCreatedUnlessContextHolderChanges() throws Exception { + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + + // Prepare the interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Execute the interceptor + interceptor.preHandleAction(request, response, null); + interceptor.afterActionCompletion(request, response, null, null); + + // Check the session is null + assertNull(request.getPortletSession(false)); + } + + public void testPortletSessionWithNonContextInWellKnownLocationIsOverwritten() + throws Exception { + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + request.getPortletSession().setAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + "NOT_A_CONTEXT_OBJECT", PortletSession.APPLICATION_SCOPE); + + // Prepare the interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.afterPropertiesSet(); + + // Execute the interceptor + interceptor.preHandleAction(request, response, null); + PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); + SecurityContextHolder.getContext().setAuthentication(principal); + interceptor.afterActionCompletion(request, response, null, null); + + // Verify Authentication is in the PortletSession + SecurityContext sc = (SecurityContext)request.getPortletSession(false). + getAttribute(PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, PortletSession.APPLICATION_SCOPE); + assertEquals(principal, ((SecurityContext)sc).getAuthentication()); + } + + public void testPortletSessionCreationNotAllowed() throws Exception { + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + + // Prepare the interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.setAllowSessionCreation(false); // non-default + interceptor.afterPropertiesSet(); + + // Execute the interceptor + interceptor.preHandleAction(request, response, null); + PreAuthenticatedAuthenticationToken principal = PortletTestUtils.createAuthenticatedToken(); + SecurityContextHolder.getContext().setAuthentication(principal); + interceptor.afterActionCompletion(request, response, null, null); + + // Check the session is null + assertNull(request.getPortletSession(false)); + } + + public void testUsePortletScopeSession() throws Exception { + + // Build an Authentication object we simulate came from PortletSession + PreAuthenticatedAuthenticationToken sessionPrincipal = PortletTestUtils.createAuthenticatedToken(); + PreAuthenticatedAuthenticationToken baselinePrincipal = PortletTestUtils.createAuthenticatedToken(); + + // Build a Context to store in PortletSession (simulating prior request) + SecurityContext sc = new SecurityContextImpl(); + sc.setAuthentication(sessionPrincipal); + + // Build mock request and response + MockActionRequest request = PortletTestUtils.createActionRequest(); + MockActionResponse response = PortletTestUtils.createActionResponse(); + request.getPortletSession().setAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + sc, PortletSession.PORTLET_SCOPE); + + // Prepare interceptor + PortletSessionContextIntegrationInterceptor interceptor = new PortletSessionContextIntegrationInterceptor(); + interceptor.setUseApplicationScopePortletSession(false); // non-default + interceptor.afterPropertiesSet(); + + // Run preHandleAction phase and verify SecurityContextHolder contains our Authentication + interceptor.preHandleAction(request, response, null); + assertEquals(baselinePrincipal, SecurityContextHolder.getContext().getAuthentication()); + + // Perform updates to principal + sessionPrincipal = PortletTestUtils.createAuthenticatedToken( + new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, + new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); + baselinePrincipal = PortletTestUtils.createAuthenticatedToken( + new User(PortletTestUtils.TESTUSER, PortletTestUtils.TESTCRED, true, true, true, true, + new GrantedAuthority[] {new GrantedAuthorityImpl("UPDATEDROLE1")})); + + // Store updated principal into SecurityContextHolder + SecurityContextHolder.getContext().setAuthentication(sessionPrincipal); + + // Run afterActionCompletion phase and verify the SecurityContextHolder is empty + interceptor.afterActionCompletion(request, response, null, null); + assertNull(SecurityContextHolder.getContext().getAuthentication()); + + // Verify the new principal is stored in the session + sc = (SecurityContext)request.getPortletSession().getAttribute( + PortletSessionContextIntegrationInterceptor.SPRING_SECURITY_CONTEXT_KEY, + PortletSession.PORTLET_SCOPE); + assertEquals(baselinePrincipal, sc.getAuthentication()); + } } diff --git a/portlet/src/test/java/org/springframework/security/providers/portlet/PortletTestUtils.java b/portlet/src/test/java/org/springframework/security/providers/portlet/PortletTestUtils.java index 78d60235e8..82518278ab 100644 --- a/portlet/src/test/java/org/springframework/security/providers/portlet/PortletTestUtils.java +++ b/portlet/src/test/java/org/springframework/security/providers/portlet/PortletTestUtils.java @@ -62,7 +62,7 @@ public class PortletTestUtils { request.setUserPrincipal(new TestingAuthenticationToken(TESTUSER, TESTCRED)); request.addUserRole(PORTALROLE1); request.addUserRole(PORTALROLE2); -// request.setAuthType(PortletRequest.FORM_AUTH); +// request.setAuthType(PortletRequest.FORM_AUTH); } public static MockRenderRequest createRenderRequest() { diff --git a/portlet/src/test/java/org/springframework/security/ui/portlet/PortletProcessingInterceptorTests.java b/portlet/src/test/java/org/springframework/security/ui/portlet/PortletProcessingInterceptorTests.java index 2943ce9f9f..b2f77fb2fa 100644 --- a/portlet/src/test/java/org/springframework/security/ui/portlet/PortletProcessingInterceptorTests.java +++ b/portlet/src/test/java/org/springframework/security/ui/portlet/PortletProcessingInterceptorTests.java @@ -250,9 +250,9 @@ public class PortletProcessingInterceptorTests { } // Make sure the token details are the PortletRequest -// if (!(token.getDetails() instanceof PortletRequest)) { -// TestCase.fail("Expected Authentication.getDetails to be a PortletRequest object -- got: " + token.getDetails()); -// } +// if (!(token.getDetails() instanceof PortletRequest)) { +// TestCase.fail("Expected Authentication.getDetails to be a PortletRequest object -- got: " + token.getDetails()); +// } // Make sure it's got a principal if (token.getPrincipal() == null) { diff --git a/samples/dms/src/test/java/DmsIntegrationTests.java b/samples/dms/src/test/java/DmsIntegrationTests.java index 51625cb9ea..0fa68d6553 100755 --- a/samples/dms/src/test/java/DmsIntegrationTests.java +++ b/samples/dms/src/test/java/DmsIntegrationTests.java @@ -20,9 +20,9 @@ public class DmsIntegrationTests extends AbstractTransactionalDataSourceSpringCo return new String[] {"classpath:applicationContext-dms-shared.xml", "classpath:applicationContext-dms-insecure.xml"}; } - protected void onTearDown() throws Exception { + protected void onTearDown() throws Exception { SecurityContextHolder.clearContext(); - } + } public void setDocumentDao(DocumentDao documentDao) { this.documentDao = documentDao; diff --git a/samples/portlet/src/main/java/org/springframework/web/portlet/sample/SecurityContextPortlet.java b/samples/portlet/src/main/java/org/springframework/web/portlet/sample/SecurityContextPortlet.java index ca37c3d213..8f387cbec8 100644 --- a/samples/portlet/src/main/java/org/springframework/web/portlet/sample/SecurityContextPortlet.java +++ b/samples/portlet/src/main/java/org/springframework/web/portlet/sample/SecurityContextPortlet.java @@ -30,12 +30,12 @@ public class SecurityContextPortlet extends GenericPortlet { out.println("

Current Session " + request.getPortletSession().getId() + "

"); out.println("

"); out.println("

The security context contains: " + - SecurityContextHolder.getContext().getAuthentication() + - "

"); + SecurityContextHolder.getContext().getAuthentication() + + "

"); Object lastException = request.getPortletSession().getAttribute(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, PortletSession.APPLICATION_SCOPE); if (lastException != null) { - out.println("Last Exception: " + lastException); + out.println("Last Exception: " + lastException); } } } diff --git a/samples/tutorial/src/main/java/bigbank/BankDao.java b/samples/tutorial/src/main/java/bigbank/BankDao.java index 67806a7e76..6c22619305 100644 --- a/samples/tutorial/src/main/java/bigbank/BankDao.java +++ b/samples/tutorial/src/main/java/bigbank/BankDao.java @@ -1,7 +1,7 @@ package bigbank; public interface BankDao { - public Account readAccount(Long id); - public void createOrUpdateAccount(Account account); - public Account[] findAccounts(); + public Account readAccount(Long id); + public void createOrUpdateAccount(Account account); + public Account[] findAccounts(); } diff --git a/samples/tutorial/src/main/java/bigbank/BankDaoStub.java b/samples/tutorial/src/main/java/bigbank/BankDaoStub.java index de46d38af9..c675f95895 100644 --- a/samples/tutorial/src/main/java/bigbank/BankDaoStub.java +++ b/samples/tutorial/src/main/java/bigbank/BankDaoStub.java @@ -4,29 +4,29 @@ import java.util.HashMap; import java.util.Map; public class BankDaoStub implements BankDao { - private long id = 0; - private Map accounts = new HashMap(); - - public void createOrUpdateAccount(Account account) { - if (account.getId() == -1) { - id++; - account.setId(id); - } - accounts.put(new Long(account.getId()), account); - System.out.println("SAVE: " + account); - } + private long id = 0; + private Map accounts = new HashMap(); + + public void createOrUpdateAccount(Account account) { + if (account.getId() == -1) { + id++; + account.setId(id); + } + accounts.put(new Long(account.getId()), account); + System.out.println("SAVE: " + account); + } - public Account[] findAccounts() { - Account[] a = (Account[]) accounts.values().toArray(new Account[] {}); - System.out.println("Returning " + a.length + " account(s):"); - for (int i = 0; i < a.length; i++) { - System.out.println(" > " + a[i]); - } - return a; - } + public Account[] findAccounts() { + Account[] a = (Account[]) accounts.values().toArray(new Account[] {}); + System.out.println("Returning " + a.length + " account(s):"); + for (int i = 0; i < a.length; i++) { + System.out.println(" > " + a[i]); + } + return a; + } - public Account readAccount(Long id) { - return (Account) accounts.get(id); - } + public Account readAccount(Long id) { + return (Account) accounts.get(id); + } } diff --git a/samples/tutorial/src/main/java/bigbank/SeedData.java b/samples/tutorial/src/main/java/bigbank/SeedData.java index 5bf0774448..182ac392b4 100644 --- a/samples/tutorial/src/main/java/bigbank/SeedData.java +++ b/samples/tutorial/src/main/java/bigbank/SeedData.java @@ -4,18 +4,18 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class SeedData implements InitializingBean{ - private BankDao bankDao; + private BankDao bankDao; - public void afterPropertiesSet() throws Exception { - Assert.notNull(bankDao); - bankDao.createOrUpdateAccount(new Account("rod")); - bankDao.createOrUpdateAccount(new Account("dianne")); - bankDao.createOrUpdateAccount(new Account("scott")); - bankDao.createOrUpdateAccount(new Account("peter")); - } - - public void setBankDao(BankDao bankDao) { - this.bankDao = bankDao; - } - + public void afterPropertiesSet() throws Exception { + Assert.notNull(bankDao); + bankDao.createOrUpdateAccount(new Account("rod")); + bankDao.createOrUpdateAccount(new Account("dianne")); + bankDao.createOrUpdateAccount(new Account("scott")); + bankDao.createOrUpdateAccount(new Account("peter")); + } + + public void setBankDao(BankDao bankDao) { + this.bankDao = bankDao; + } + } diff --git a/samples/tutorial/src/main/java/bigbank/web/ListAccounts.java b/samples/tutorial/src/main/java/bigbank/web/ListAccounts.java index d0ea3ed67b..8fa08cad4e 100644 --- a/samples/tutorial/src/main/java/bigbank/web/ListAccounts.java +++ b/samples/tutorial/src/main/java/bigbank/web/ListAccounts.java @@ -12,23 +12,23 @@ import bigbank.BankService; public class ListAccounts implements Controller { - private BankService bankService; - - public ListAccounts(BankService bankService) { - Assert.notNull(bankService); - this.bankService = bankService; - } + private BankService bankService; + + public ListAccounts(BankService bankService) { + Assert.notNull(bankService); + this.bankService = bankService; + } - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - // Security check (this is unnecessary if Spring Security is performing the authorization) -// if (request.getUserPrincipal() == null) { -// throw new AuthenticationCredentialsNotFoundException("You must login to view the account list (Spring Security message)"); // only for Spring Security managed authentication -// } - - // Actual business logic - ModelAndView mav = new ModelAndView("listAccounts"); - mav.addObject("accounts", bankService.findAccounts()); - return mav; - } + public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { + // Security check (this is unnecessary if Spring Security is performing the authorization) +// if (request.getUserPrincipal() == null) { +// throw new AuthenticationCredentialsNotFoundException("You must login to view the account list (Spring Security message)"); // only for Spring Security managed authentication +// } + + // Actual business logic + ModelAndView mav = new ModelAndView("listAccounts"); + mav.addObject("accounts", bankService.findAccounts()); + return mav; + } } diff --git a/samples/tutorial/src/main/java/bigbank/web/PostAccounts.java b/samples/tutorial/src/main/java/bigbank/web/PostAccounts.java index e5967b52e3..24abea31f1 100644 --- a/samples/tutorial/src/main/java/bigbank/web/PostAccounts.java +++ b/samples/tutorial/src/main/java/bigbank/web/PostAccounts.java @@ -14,26 +14,26 @@ import bigbank.BankService; public class PostAccounts implements Controller { - private BankService bankService; - - public PostAccounts(BankService bankService) { - Assert.notNull(bankService); - this.bankService = bankService; - } + private BankService bankService; + + public PostAccounts(BankService bankService) { + Assert.notNull(bankService); + this.bankService = bankService; + } - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - // Security check (this is unnecessary if Spring Security is performing the authorization) -// if (!request.isUserInRole("ROLE_TELLER")) { -// throw new AccessDeniedException("You must be a teller to post transactions (Spring Security message)"); // only for Spring Security managed authentication -// } - - // Actual business logic - Long id = ServletRequestUtils.getRequiredLongParameter(request, "id"); - Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount"); - Account a = bankService.readAccount(id); - bankService.post(a, amount); - - return new ModelAndView("redirect:listAccounts.html"); - } + public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { + // Security check (this is unnecessary if Spring Security is performing the authorization) +// if (!request.isUserInRole("ROLE_TELLER")) { +// throw new AccessDeniedException("You must be a teller to post transactions (Spring Security message)"); // only for Spring Security managed authentication +// } + + // Actual business logic + Long id = ServletRequestUtils.getRequiredLongParameter(request, "id"); + Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount"); + Account a = bankService.readAccount(id); + bankService.post(a, amount); + + return new ModelAndView("redirect:listAccounts.html"); + } } diff --git a/sandbox/heavyduty/src/main/java/bigbank/Account.java b/sandbox/heavyduty/src/main/java/bigbank/Account.java index 1fdc1044e5..90b64a1e24 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/Account.java +++ b/sandbox/heavyduty/src/main/java/bigbank/Account.java @@ -10,42 +10,42 @@ package bigbank; * @version $Id$ */ public class Account { - private long id = -1; - private String holder; - private double balance; - - public Account(String holder) { - super(); - this.holder = holder; - } + private long id = -1; + private String holder; + private double balance; + + public Account(String holder) { + super(); + this.holder = holder; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getHolder() { - return holder; - } + public String getHolder() { + return holder; + } - public void setHolder(String holder) { - this.holder = holder; - } + public void setHolder(String holder) { + this.holder = holder; + } - public double getBalance() { - return balance; - } + public double getBalance() { + return balance; + } - public void setBalance(double balance) { - this.balance = balance; - } + public void setBalance(double balance) { + this.balance = balance; + } - public String toString() { - return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]"; - } + public String toString() { + return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]"; + } - + } diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankDao.java b/sandbox/heavyduty/src/main/java/bigbank/BankDao.java index 67806a7e76..6c22619305 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/BankDao.java +++ b/sandbox/heavyduty/src/main/java/bigbank/BankDao.java @@ -1,7 +1,7 @@ package bigbank; public interface BankDao { - public Account readAccount(Long id); - public void createOrUpdateAccount(Account account); - public Account[] findAccounts(); + public Account readAccount(Long id); + public void createOrUpdateAccount(Account account); + public Account[] findAccounts(); } diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java b/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java index de46d38af9..c675f95895 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java +++ b/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java @@ -4,29 +4,29 @@ import java.util.HashMap; import java.util.Map; public class BankDaoStub implements BankDao { - private long id = 0; - private Map accounts = new HashMap(); - - public void createOrUpdateAccount(Account account) { - if (account.getId() == -1) { - id++; - account.setId(id); - } - accounts.put(new Long(account.getId()), account); - System.out.println("SAVE: " + account); - } + private long id = 0; + private Map accounts = new HashMap(); + + public void createOrUpdateAccount(Account account) { + if (account.getId() == -1) { + id++; + account.setId(id); + } + accounts.put(new Long(account.getId()), account); + System.out.println("SAVE: " + account); + } - public Account[] findAccounts() { - Account[] a = (Account[]) accounts.values().toArray(new Account[] {}); - System.out.println("Returning " + a.length + " account(s):"); - for (int i = 0; i < a.length; i++) { - System.out.println(" > " + a[i]); - } - return a; - } + public Account[] findAccounts() { + Account[] a = (Account[]) accounts.values().toArray(new Account[] {}); + System.out.println("Returning " + a.length + " account(s):"); + for (int i = 0; i < a.length; i++) { + System.out.println(" > " + a[i]); + } + return a; + } - public Account readAccount(Long id) { - return (Account) accounts.get(id); - } + public Account readAccount(Long id) { + return (Account) accounts.get(id); + } } diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankService.java b/sandbox/heavyduty/src/main/java/bigbank/BankService.java index 90c21ccde5..15c5879ba6 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/BankService.java +++ b/sandbox/heavyduty/src/main/java/bigbank/BankService.java @@ -3,13 +3,13 @@ package bigbank; import org.springframework.security.annotation.Secured; public interface BankService { - - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - public Account readAccount(Long id); - - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - public Account[] findAccounts(); - - @Secured("ROLE_TELLER") - public Account post(Account account, double amount); + + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + public Account readAccount(Long id); + + @Secured("IS_AUTHENTICATED_ANONYMOUSLY") + public Account[] findAccounts(); + + @Secured("ROLE_TELLER") + public Account post(Account account, double amount); } diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java b/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java index e461e132d0..c4c5a985bb 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java +++ b/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java @@ -4,37 +4,37 @@ import org.aspectj.lang.annotation.Pointcut; import org.springframework.util.Assert; public class BankServiceImpl implements BankService { - private BankDao bankDao; + private BankDao bankDao; - // Not used unless you declare a - @Pointcut("execution(* bigbank.BankServiceImpl.*(..))") - public void myPointcut() {} + // Not used unless you declare a + @Pointcut("execution(* bigbank.BankServiceImpl.*(..))") + public void myPointcut() {} - public BankServiceImpl(BankDao bankDao) { - Assert.notNull(bankDao); - this.bankDao = bankDao; - } + public BankServiceImpl(BankDao bankDao) { + Assert.notNull(bankDao); + this.bankDao = bankDao; + } - public Account[] findAccounts() { - return this.bankDao.findAccounts(); - } + public Account[] findAccounts() { + return this.bankDao.findAccounts(); + } - public Account post(Account account, double amount) { - Assert.notNull(account); - Assert.notNull(account.getId()); - - // We read account bank from DAO so it reflects the latest balance - Account a = bankDao.readAccount(account.getId()); - if (account == null) { - throw new IllegalArgumentException("Couldn't find requested account"); - } - - a.setBalance(a.getBalance() + amount); - bankDao.createOrUpdateAccount(a); - return a; - } + public Account post(Account account, double amount) { + Assert.notNull(account); + Assert.notNull(account.getId()); + + // We read account bank from DAO so it reflects the latest balance + Account a = bankDao.readAccount(account.getId()); + if (account == null) { + throw new IllegalArgumentException("Couldn't find requested account"); + } + + a.setBalance(a.getBalance() + amount); + bankDao.createOrUpdateAccount(a); + return a; + } - public Account readAccount(Long id) { - return bankDao.readAccount(id); - } + public Account readAccount(Long id) { + return bankDao.readAccount(id); + } } diff --git a/sandbox/heavyduty/src/main/java/bigbank/SeedData.java b/sandbox/heavyduty/src/main/java/bigbank/SeedData.java index 5bf0774448..182ac392b4 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/SeedData.java +++ b/sandbox/heavyduty/src/main/java/bigbank/SeedData.java @@ -4,18 +4,18 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class SeedData implements InitializingBean{ - private BankDao bankDao; + private BankDao bankDao; - public void afterPropertiesSet() throws Exception { - Assert.notNull(bankDao); - bankDao.createOrUpdateAccount(new Account("rod")); - bankDao.createOrUpdateAccount(new Account("dianne")); - bankDao.createOrUpdateAccount(new Account("scott")); - bankDao.createOrUpdateAccount(new Account("peter")); - } - - public void setBankDao(BankDao bankDao) { - this.bankDao = bankDao; - } - + public void afterPropertiesSet() throws Exception { + Assert.notNull(bankDao); + bankDao.createOrUpdateAccount(new Account("rod")); + bankDao.createOrUpdateAccount(new Account("dianne")); + bankDao.createOrUpdateAccount(new Account("scott")); + bankDao.createOrUpdateAccount(new Account("peter")); + } + + public void setBankDao(BankDao bankDao) { + this.bankDao = bankDao; + } + } diff --git a/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java b/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java index c33225ef37..de6b12c42c 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java +++ b/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java @@ -11,18 +11,18 @@ import bigbank.BankService; public class ListAccounts implements Controller { - private BankService bankService; - - public ListAccounts(BankService bankService) { - Assert.notNull(bankService); - this.bankService = bankService; - } + private BankService bankService; + + public ListAccounts(BankService bankService) { + Assert.notNull(bankService); + this.bankService = bankService; + } - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - // Actual business logic - ModelAndView mav = new ModelAndView("listAccounts"); - mav.addObject("accounts", bankService.findAccounts()); - return mav; - } + public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { + // Actual business logic + ModelAndView mav = new ModelAndView("listAccounts"); + mav.addObject("accounts", bankService.findAccounts()); + return mav; + } } diff --git a/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java b/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java index 63c6bdf94f..2465392ace 100755 --- a/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java +++ b/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java @@ -13,26 +13,26 @@ import bigbank.BankService; public class PostAccounts implements Controller { - private BankService bankService; - - public PostAccounts(BankService bankService) { - Assert.notNull(bankService); - this.bankService = bankService; - } + private BankService bankService; + + public PostAccounts(BankService bankService) { + Assert.notNull(bankService); + this.bankService = bankService; + } - public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { - // Security check (this is unnecessary if Spring Security is performing the authorization) -// if (!request.isUserInRole("ROLE_TELLER")) { -// throw new AccessDeniedException("You must be a teller to post transactions (Spring Security message)"); // only for Spring Security managed authentication -// } - - // Actual business logic - Long id = ServletRequestUtils.getRequiredLongParameter(request, "id"); - Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount"); - Account a = bankService.readAccount(id); - bankService.post(a, amount); - - return new ModelAndView("redirect:listAccounts.html"); - } + public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { + // Security check (this is unnecessary if Spring Security is performing the authorization) +// if (!request.isUserInRole("ROLE_TELLER")) { +// throw new AccessDeniedException("You must be a teller to post transactions (Spring Security message)"); // only for Spring Security managed authentication +// } + + // Actual business logic + Long id = ServletRequestUtils.getRequiredLongParameter(request, "id"); + Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount"); + Account a = bankService.readAccount(id); + bankService.post(a, amount); + + return new ModelAndView("redirect:listAccounts.html"); + } } diff --git a/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyAuthenticationProcessingFilter.java b/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyAuthenticationProcessingFilter.java index a456c7fad9..97fe1bf0c0 100755 --- a/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyAuthenticationProcessingFilter.java +++ b/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyAuthenticationProcessingFilter.java @@ -3,9 +3,9 @@ package heavyduty.security.ui; import org.springframework.security.ui.webapp.AuthenticationProcessingFilter; public class HeavyDutyAuthenticationProcessingFilter extends AuthenticationProcessingFilter { - - + + - - + + } diff --git a/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyEntryPoint.java b/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyEntryPoint.java index 3ee843792c..0e65f9ebeb 100755 --- a/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyEntryPoint.java +++ b/sandbox/heavyduty/src/main/java/heavyduty/security/ui/HeavyDutyEntryPoint.java @@ -4,6 +4,6 @@ import org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntr public class HeavyDutyEntryPoint extends AuthenticationProcessingFilterEntryPoint { - - + + } diff --git a/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java b/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java index 8f281cf06f..5882a0d473 100644 --- a/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java +++ b/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java @@ -17,34 +17,34 @@ import org.springframework.web.servlet.mvc.multiaction.MultiActionController; * Reproduces SEC-830. */ public class TestMultiActionController extends MultiActionController { - public static final String VIEW_NAME = "multi-action-test"; - - public String login(HttpServletRequest request, HttpServletResponse response) { - return "login"; - } - - public void step1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - String[] x = request.getParameterValues("x"); - logger.info("x= " + (x == null ? "null" : Arrays.asList(x))); - String[] y = request.getParameterValues("y"); - logger.info("y = " + (y == null ? "null" : Arrays.asList(y))); - request.getRequestDispatcher("/testMulti.htm?action=step1xtra&x=5&x=5").forward(request, response); - } + public static final String VIEW_NAME = "multi-action-test"; + + public String login(HttpServletRequest request, HttpServletResponse response) { + return "login"; + } + + public void step1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String[] x = request.getParameterValues("x"); + logger.info("x= " + (x == null ? "null" : Arrays.asList(x))); + String[] y = request.getParameterValues("y"); + logger.info("y = " + (y == null ? "null" : Arrays.asList(y))); + request.getRequestDispatcher("/testMulti.htm?action=step1xtra&x=5&x=5").forward(request, response); + } - public ModelAndView step1xtra(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException { - logger.info("x = " + Arrays.asList(request.getParameterValues("x"))); - return createView("step2"); - } - - public ModelAndView step2(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException { - return createView("step1"); - } - - private ModelAndView createView(String name) { - Map model = new HashMap(); - model.put("nextAction", name); - return new ModelAndView(VIEW_NAME, model); - } - + public ModelAndView step1xtra(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException { + logger.info("x = " + Arrays.asList(request.getParameterValues("x"))); + return createView("step2"); + } + + public ModelAndView step2(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException { + return createView("step1"); + } + + private ModelAndView createView(String name) { + Map model = new HashMap(); + model.put("nextAction", name); + return new ModelAndView(VIEW_NAME, model); + } + } diff --git a/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java b/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java index 4272790621..1797481df5 100755 --- a/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java +++ b/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java @@ -8,39 +8,39 @@ import java.io.Serializable; */ public interface GenericDAO { - /** - * persist - * @param transientInstance objet to persist - */ - void persist(T transientInstance); + /** + * persist + * @param transientInstance objet to persist + */ + void persist(T transientInstance); - - /** - * refresh - * @param instance objet to refresh - */ - void refresh(T instance); + + /** + * refresh + * @param instance objet to refresh + */ + void refresh(T instance); - - /** - * delete - * @param persistentInstance objet to delete - */ - void delete(T persistentInstance); + + /** + * delete + * @param persistentInstance objet to delete + */ + void delete(T persistentInstance); - - /** - * merge - * @param detachedInstance objet to merge - * @return merged object - */ - T merge(T detachedInstance); - - - /** - * read - * @param id of object to read - * @return read object - */ - T read(PK id); + + /** + * merge + * @param detachedInstance objet to merge + * @return merged object + */ + T merge(T detachedInstance); + + + /** + * read + * @param id of object to read + * @return read object + */ + T read(PK id); } \ No newline at end of file diff --git a/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java b/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java index 5017a149f3..6555ad7baf 100755 --- a/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java +++ b/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java @@ -8,6 +8,6 @@ import sample.domain.User; * The Interface PatientDAO. */ public interface UserDAO extends GenericDAO { - - public User findByUsername(String username); + + public User findByUsername(String username); } diff --git a/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java b/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java index 4fffeb7ef3..01af5b984c 100755 --- a/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java +++ b/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java @@ -12,115 +12,115 @@ import sample.dao.GenericDAO; public class GenericDAOImpl - implements GenericDAO { - /** type */ - private Class type; + implements GenericDAO { + /** type */ + private Class type; - /** the logger */ - private static final Log LOG = LogFactory.getLog(GenericDAOImpl.class); + /** the logger */ + private static final Log LOG = LogFactory.getLog(GenericDAOImpl.class); - @PersistenceContext - private EntityManager entityManager; + @PersistenceContext + private EntityManager entityManager; - /** - * Minimal constructor - * - * @param t - * type POJO hibernate - */ - public GenericDAOImpl(Class t) { - this.type = t; - } + /** + * Minimal constructor + * + * @param t + * type POJO hibernate + */ + public GenericDAOImpl(Class t) { + this.type = t; + } - /** - * read data - * - * @param id - * data id - * @return data - */ - @SuppressWarnings("unchecked") - public T read(PK id) { - if (id == null) { - throw new IllegalArgumentException("Id cannot be null or empty"); - } + /** + * read data + * + * @param id + * data id + * @return data + */ + @SuppressWarnings("unchecked") + public T read(PK id) { + if (id == null) { + throw new IllegalArgumentException("Id cannot be null or empty"); + } - // find() au lieu de getReference() pour forcer l'initialisation de - // l'objet, sinon on ne recupère - // qu'un proxy non-initialisé ! - return entityManager.find(type, id); + // find() au lieu de getReference() pour forcer l'initialisation de + // l'objet, sinon on ne recupère + // qu'un proxy non-initialisé ! + return entityManager.find(type, id); - } + } - /** - * persist data - * - * @param transientInstance - * data to persist - * @see sido.common.dao.GenericDAO#persist(T) - */ - public void persist(T transientInstance) { - if (LOG.isDebugEnabled()) { - LOG.debug("Persisting instance of " - + transientInstance.getClass().getSimpleName()); - } - entityManager.persist(transientInstance); - } + /** + * persist data + * + * @param transientInstance + * data to persist + * @see sido.common.dao.GenericDAO#persist(T) + */ + public void persist(T transientInstance) { + if (LOG.isDebugEnabled()) { + LOG.debug("Persisting instance of " + + transientInstance.getClass().getSimpleName()); + } + entityManager.persist(transientInstance); + } - /** - * - * attach clean - * - * @param instance - * data to attach - * @see sido.common.dao.GenericDAO#refresh(T) - */ - public void refresh(T instance) { - if (LOG.isDebugEnabled()) { - LOG.debug("refreshing instance of " - + instance.getClass().getSimpleName()); - } - entityManager.refresh(instance); - } + /** + * + * attach clean + * + * @param instance + * data to attach + * @see sido.common.dao.GenericDAO#refresh(T) + */ + public void refresh(T instance) { + if (LOG.isDebugEnabled()) { + LOG.debug("refreshing instance of " + + instance.getClass().getSimpleName()); + } + entityManager.refresh(instance); + } - /** - * delete - * - * @param persistentInstance - * data to delete - * @see sido.common.dao.GenericDAO#delete(T) - */ - public void delete(T persistentInstance) { - if (LOG.isDebugEnabled()) { - LOG.debug("deleting instance of " - + persistentInstance.getClass().getSimpleName()); - } - entityManager.remove(persistentInstance); - } + /** + * delete + * + * @param persistentInstance + * data to delete + * @see sido.common.dao.GenericDAO#delete(T) + */ + public void delete(T persistentInstance) { + if (LOG.isDebugEnabled()) { + LOG.debug("deleting instance of " + + persistentInstance.getClass().getSimpleName()); + } + entityManager.remove(persistentInstance); + } - /** - * merge - * - * @param detachedInstance - * data to merge - * @return the merged data - * @see sido.common.dao.GenericDAO#merge(T) - */ - @SuppressWarnings("unchecked") - public T merge(T detachedInstance) { - if (LOG.isDebugEnabled()) { - LOG.debug("merging instance of " - + detachedInstance.getClass().getSimpleName()); - } - return entityManager.merge(detachedInstance); - } + /** + * merge + * + * @param detachedInstance + * data to merge + * @return the merged data + * @see sido.common.dao.GenericDAO#merge(T) + */ + @SuppressWarnings("unchecked") + public T merge(T detachedInstance) { + if (LOG.isDebugEnabled()) { + LOG.debug("merging instance of " + + detachedInstance.getClass().getSimpleName()); + } + return entityManager.merge(detachedInstance); + } - /** - * @return the entityManager - */ - public EntityManager getEntityManager() { - return entityManager; - } + /** + * @return the entityManager + */ + public EntityManager getEntityManager() { + return entityManager; + } } \ No newline at end of file diff --git a/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java b/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java index 0712ab455f..3799670509 100755 --- a/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java +++ b/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java @@ -9,19 +9,19 @@ import sample.domain.User; */ @Repository public class UserDAOImpl extends GenericDAOImpl implements - sample.dao.UserDAO { + sample.dao.UserDAO { - /** - * Required constructor - */ - public UserDAOImpl() { - super(User.class); - } + /** + * Required constructor + */ + public UserDAOImpl() { + super(User.class); + } - public User findByUsername(String username) { - return (User) getEntityManager().createNamedQuery("User.findByUsername") - .setParameter("username", username).getSingleResult(); - } - + public User findByUsername(String username) { + return (User) getEntityManager().createNamedQuery("User.findByUsername") + .setParameter("username", username).getSingleResult(); + } + } diff --git a/sandbox/heavyduty/src/main/java/sample/domain/User.java b/sandbox/heavyduty/src/main/java/sample/domain/User.java index 7fc7bf6afa..ddae57f207 100755 --- a/sandbox/heavyduty/src/main/java/sample/domain/User.java +++ b/sandbox/heavyduty/src/main/java/sample/domain/User.java @@ -19,88 +19,88 @@ import javax.persistence.NamedQuery; @NamedQuery(name = "User.findByUsername", query = "from User where username= :username") public class User implements Serializable { - /** serialVersionUID */ - private static final long serialVersionUID = 7073017148588882593L; + /** serialVersionUID */ + private static final long serialVersionUID = 7073017148588882593L; - /** The id. */ - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - private Long id; + /** The id. */ + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; - /** The username. */ - @Basic(optional = false) - private String username; + /** The username. */ + @Basic(optional = false) + private String username; - /** The username. */ - @Basic(optional = false) - private String password; + /** The username. */ + @Basic(optional = false) + private String password; - /** - * Default constructor - */ - public User() { - super(); - } + /** + * Default constructor + */ + public User() { + super(); + } - /** - * @param username - * @param password - */ - public User(String username, String password) { - super(); - this.username = username; - this.password = password; - } + /** + * @param username + * @param password + */ + public User(String username, String password) { + super(); + this.username = username; + this.password = password; + } - /** - * @return the id - */ - public Long getId() { - return id; - } + /** + * @return the id + */ + public Long getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } - /** - * @return the username - */ - public String getUsername() { - return username; - } + /** + * @return the username + */ + public String getUsername() { + return username; + } - /** - * @param username the username to set - */ - public void setUsername(String username) { - this.username = username; - } + /** + * @param username the username to set + */ + public void setUsername(String username) { + this.username = username; + } - /** - * Full constructor - * @param username - */ - public User(String username, String password, Date derniereConnexion, - String key) { - super(); - this.username = username; - } + /** + * Full constructor + * @param username + */ + public User(String username, String password, Date derniereConnexion, + String key) { + super(); + this.username = username; + } - /** - * @return the password - */ - public String getPassword() { - return password; - } + /** + * @return the password + */ + public String getPassword() { + return password; + } - /** - * @param password the password to set - */ - public void setPassword(String password) { - this.password = password; - } + /** + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; + } } diff --git a/sandbox/heavyduty/src/main/java/sample/service/UserService.java b/sandbox/heavyduty/src/main/java/sample/service/UserService.java index 7130c120ee..a81c6e91c9 100755 --- a/sandbox/heavyduty/src/main/java/sample/service/UserService.java +++ b/sandbox/heavyduty/src/main/java/sample/service/UserService.java @@ -4,13 +4,13 @@ import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; public interface UserService extends UserDetailsService { - - /** - * Register a new User in database - * @param username - */ - public UserDetails register(String username, String password); - - - + + /** + * Register a new User in database + * @param username + */ + public UserDetails register(String username, String password); + + + } diff --git a/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java b/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java index 8730c6888e..eb92fb845c 100755 --- a/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java +++ b/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java @@ -27,42 +27,42 @@ import sample.service.UserService; @Transactional public class UserServiceImpl implements UserService { - /** The logger */ - private static final Log LOG = LogFactory.getLog(UserServiceImpl.class); + /** The logger */ + private static final Log LOG = LogFactory.getLog(UserServiceImpl.class); - /** The User DAO */ - @Autowired - private UserDAO userDAO = null; + /** The User DAO */ + @Autowired + private UserDAO userDAO = null; - public UserDetails loadUserByUsername(String username) - throws AuthenticationException { - try { - User user = userDAO.findByUsername(username); + public UserDetails loadUserByUsername(String username) + throws AuthenticationException { + try { + User user = userDAO.findByUsername(username); - return new org.springframework.security.userdetails.User(user - .getUsername(), user.getPassword(), true, true, true, true, - new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_USER") }); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - throw new UsernameNotFoundException("No matching account", e); - } - } + return new org.springframework.security.userdetails.User(user + .getUsername(), user.getPassword(), true, true, true, true, + new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_USER") }); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + throw new UsernameNotFoundException("No matching account", e); + } + } - public UserDetails register(String username, String password) { - User user = new User(username, password); - userDAO.persist(user); - return new org.springframework.security.userdetails.User(user - .getUsername(), user.getPassword(), true, true, true, true, - new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_USER") }); + public UserDetails register(String username, String password) { + User user = new User(username, password); + userDAO.persist(user); + return new org.springframework.security.userdetails.User(user + .getUsername(), user.getPassword(), true, true, true, true, + new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_USER") }); - } + } - /** - * @param userDAO - * the userDAO to set - */ - public void setUserDAO(UserDAO userDAO) { - this.userDAO = userDAO; - } + /** + * @param userDAO + * the userDAO to set + */ + public void setUserDAO(UserDAO userDAO) { + this.userDAO = userDAO; + } } diff --git a/sandbox/other/src/test/java/org/springframework/security/AspectJParsingTests.java b/sandbox/other/src/test/java/org/springframework/security/AspectJParsingTests.java index d487c6bf65..3123fd5eb6 100644 --- a/sandbox/other/src/test/java/org/springframework/security/AspectJParsingTests.java +++ b/sandbox/other/src/test/java/org/springframework/security/AspectJParsingTests.java @@ -20,32 +20,32 @@ import org.junit.Test; */ public class AspectJParsingTests { - private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet(); + private static final Set DEFAULT_SUPPORTED_PRIMITIVES = new HashSet(); - @Pointcut("execution(int TargetObject.countLength(String))") - public void goodPointcut() {} + @Pointcut("execution(int TargetObject.countLength(String))") + public void goodPointcut() {} - static { - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.CALL); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS); - DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET); - } + static { + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.CALL); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS); + DEFAULT_SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET); + } - @Test - public void testMatches() throws Exception { - PointcutParser parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(DEFAULT_SUPPORTED_PRIMITIVES); - PointcutExpression expression = parser.parsePointcutExpression("org.springframework.security.AspectJParsingTests.goodPointcut()"); + @Test + public void testMatches() throws Exception { + PointcutParser parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(DEFAULT_SUPPORTED_PRIMITIVES); + PointcutExpression expression = parser.parsePointcutExpression("org.springframework.security.AspectJParsingTests.goodPointcut()"); - Method exec = OtherTargetObject.class.getMethod("countLength", new Class[] {String.class}); - Assert.assertTrue(expression.matchesMethodExecution(exec).alwaysMatches()); - } + Method exec = OtherTargetObject.class.getMethod("countLength", new Class[] {String.class}); + Assert.assertTrue(expression.matchesMethodExecution(exec).alwaysMatches()); + } } diff --git a/sandbox/other/src/test/java/org/springframework/security/vote/FirstDecisionBased.java b/sandbox/other/src/test/java/org/springframework/security/vote/FirstDecisionBased.java index 2756317914..a180359089 100644 --- a/sandbox/other/src/test/java/org/springframework/security/vote/FirstDecisionBased.java +++ b/sandbox/other/src/test/java/org/springframework/security/vote/FirstDecisionBased.java @@ -29,23 +29,23 @@ import org.springframework.security.ConfigAttributeDefinition; */ public class FirstDecisionBased extends AbstractAccessDecisionManager { - public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config ) throws AccessDeniedException { - Iterator voters = this.getDecisionVoters().iterator(); + public void decide(Authentication authentication, Object object, ConfigAttributeDefinition config ) throws AccessDeniedException { + Iterator voters = this.getDecisionVoters().iterator(); - while (voters.hasNext()) { - AccessDecisionVoter voter = (AccessDecisionVoter) voters.next(); - int result = voter.vote(authentication, object, config); - - switch (result) { - case AccessDecisionVoter.ACCESS_GRANTED: - return; - - case AccessDecisionVoter.ACCESS_DENIED: - throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied")); - } - } - - // To get this far, every AccessDecisionVoter abstained - checkAllowIfAllAbstainDecisions(); - } + while (voters.hasNext()) { + AccessDecisionVoter voter = (AccessDecisionVoter) voters.next(); + int result = voter.vote(authentication, object, config); + + switch (result) { + case AccessDecisionVoter.ACCESS_GRANTED: + return; + + case AccessDecisionVoter.ACCESS_DENIED: + throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied")); + } + } + + // To get this far, every AccessDecisionVoter abstained + checkAllowIfAllAbstainDecisions(); + } } \ No newline at end of file diff --git a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java index a2ab003d1f..168ee33db7 100644 --- a/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java +++ b/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagCustomGrantedAuthorityTests.java @@ -28,7 +28,6 @@ import javax.servlet.jsp.tagext.Tag; /** - * DOCUMENT ME! * * @author Francois Beausoleil * @version $Id$ @@ -81,10 +80,10 @@ public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase { private final String authority; public int compareTo(Object o) { - return 0; - } + return 0; + } - public CustomGrantedAuthority(String authority) { + public CustomGrantedAuthority(String authority) { this.authority = authority; }