Tidying up, removing compiler warnings etc.
This commit is contained in:
parent
8154161ef5
commit
cc5966bc7e
|
@ -44,7 +44,7 @@ import java.io.Serializable;
|
|||
*/
|
||||
public interface Acl extends Serializable {
|
||||
|
||||
/**
|
||||
/**
|
||||
* Returns all of the entries represented by the present <tt>Acl</tt>. Entries associated with
|
||||
* the <tt>Acl</tt> parents are not returned.
|
||||
*
|
||||
|
|
|
@ -39,9 +39,10 @@ public interface AclService {
|
|||
ObjectIdentity[] findChildren(ObjectIdentity parentIdentity);
|
||||
|
||||
/**
|
||||
* Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.<p>This method
|
||||
* should not be called as it does not leverage the underlaying implementation's potential ability to filter
|
||||
* <tt>Acl</tt> entries based on a {@link Sid} parameter.</p>
|
||||
* Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.
|
||||
* <p>
|
||||
* This method should not be called as it does not leverage the underlying implementation's potential ability to
|
||||
* filter <tt>Acl</tt> entries based on a {@link Sid} parameter.</p>
|
||||
*
|
||||
* @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 <tt>null</tt> to denote all entries)
|
||||
*
|
||||
* @return the {@link Acl} for the requested {@link ObjectIdentity} (never <tt>null</tt>)
|
||||
|
@ -89,7 +90,7 @@ public interface AclService {
|
|||
* not have a map key.</p>
|
||||
*
|
||||
* @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 <tt>null</tt> to denote all entries)
|
||||
*
|
||||
* @return a map with exactly one element for each {@link ObjectIdentity} passed as an argument (never <tt>null</tt>)
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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())
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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))) {
|
||||
|
|
|
@ -11,14 +11,14 @@ import org.springframework.security.acls.Permission;
|
|||
*/
|
||||
public interface PermissionFactory {
|
||||
|
||||
/**
|
||||
* Dynamically creates a <code>CumulativePermission</code> or <code>BasePermission</code> 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 <code>CumulativePermission</code> or <code>BasePermission</code> 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);
|
||||
|
||||
}
|
|
@ -290,7 +290,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
|
|||
* already, and adding the returned elements to the cache etc.</p>
|
||||
* <p>
|
||||
* This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
|
||||
* parent ACLs.</p>
|
||||
* parent ACLs.
|
||||
*
|
||||
*/
|
||||
private Map<ObjectIdentity, Acl> 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.<p>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.
|
||||
* <p>
|
||||
* 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.</p>
|
||||
* <p>The implementation works in batch sizes specfied by {@link #batchSize}.</p>
|
||||
* instead.
|
||||
* <p>
|
||||
* 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)
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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()]);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -62,7 +62,7 @@ public interface ObjectIdentity extends Serializable {
|
|||
*
|
||||
* @return the Java type of the domain object (never <tt>null</tt>)
|
||||
*/
|
||||
Class getJavaType();
|
||||
Class<?> getJavaType();
|
||||
|
||||
/**
|
||||
* @return a hash code representation of the <tt>ObjectIdentity</tt>
|
||||
|
|
|
@ -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'));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
private Long id;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<ObjectIdentity, Acl> 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<ObjectIdentity, Acl> 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<ObjectIdentity, Acl> 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<ObjectIdentity, Acl> 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<ObjectIdentity, Acl> 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<ObjectIdentity, Acl> 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));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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());
|
||||
|
|
|
@ -163,6 +163,7 @@ public class ObjectIdentityTests {
|
|||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private class MockOtherIdDomainObject {
|
||||
private Object id;
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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.");
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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<String, CasAuthenticationToken> cache = new HashMap<String, CasAuthenticationToken>();
|
||||
|
||||
public CasAuthenticationToken getByTicketId(String serviceTicket) {
|
||||
return (CasAuthenticationToken) cache.get(serviceTicket);
|
||||
return cache.get(serviceTicket);
|
||||
}
|
||||
|
||||
public void putTicketInCache(CasAuthenticationToken token) {
|
||||
|
|
|
@ -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<String> proxyList = new ArrayList<String>();
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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()));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -26,13 +26,10 @@ import org.springframework.security.userdetails.UserDetails;
|
|||
* A <code>GrantedAuthority</code> must either represent itself as a
|
||||
* <code>String</code> or be specifically supported by an {@link
|
||||
* AccessDecisionManager}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Implementations must implement {@link Comparable} in order to ensure that
|
||||
* array sorting logic guaranteed by {@link UserDetails#getAuthorities()} can
|
||||
* be reliably implemented.
|
||||
* </p>
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -159,7 +159,7 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl
|
|||
this.sessionRegistry = sessionRegistry;
|
||||
}
|
||||
|
||||
public SessionRegistry getSessionRegistry() {
|
||||
return sessionRegistry;
|
||||
}
|
||||
public SessionRegistry getSessionRegistry() {
|
||||
return sessionRegistry;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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<Element> interceptUrls = DomUtils.getChildElementsByTagName(element, "intercept-url");
|
||||
|
||||
|
|
|
@ -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 <global-method-security> detected.", source);
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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";
|
||||
|
|
|
@ -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());
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,8 +23,9 @@ import org.springframework.util.ClassUtils;
|
|||
|
||||
|
||||
/**
|
||||
* Outputs authentication-related application events to Commons Logging.<P>All authentication events are logged at
|
||||
* the warning level.</p>
|
||||
* Outputs authentication-related application events to Commons Logging.
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<ConfigAttribute> findAttributesSpecifiedAgainst(Method method, Class clazz) {
|
||||
private List<ConfigAttribute> findAttributesSpecifiedAgainst(Method method, Class<?> clazz) {
|
||||
RegisteredMethod registeredMethod = new RegisteredMethod(method, clazz);
|
||||
if (methodMap.containsKey(registeredMethod)) {
|
||||
return (List<ConfigAttribute>) 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<ConfigAttribute> attr) {
|
||||
public void addSecureMethod(Class<?> javaType, String mappedName, List<ConfigAttribute> 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<ConfigAttribute> attr) {
|
||||
public void addSecureMethod(Class<?> javaType, Method method, List<ConfigAttribute> 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;
|
||||
|
|
|
@ -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<String, List<ConfigAttribute>> mappings = new LinkedHashMap<String, List<ConfigAttribute>>();
|
||||
|
||||
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
|
||||
String name = (String) iter.next();
|
||||
|
|
|
@ -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}.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* It is very important to understand that only the <b>first</b> pointcut that matches a given
|
||||
* method will be taken as authoritative for that method. This is why pointcuts should be provided
|
||||
* as a <tt>LinkedHashMap</tt>, because their order is very important.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Note also that only beans defined in the Spring application context will be examined by this
|
||||
* class.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
*
|
||||
* @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<String,List<ConfigAttribute>> pointcutMap = new LinkedHashMap();
|
||||
private Map<String,List<ConfigAttribute>> pointcutMap = new LinkedHashMap<String,List<ConfigAttribute>>();
|
||||
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<PointcutPrimitive> supportedPrimitives = new HashSet<PointcutPrimitive>(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<String, List<ConfigAttribute>> map) {
|
||||
Assert.notEmpty(map);
|
||||
Iterator i = map.keySet().iterator();
|
||||
while (i.hasNext()) {
|
||||
String expression = i.next().toString();
|
||||
for (String expression : map.keySet()) {
|
||||
List<ConfigAttribute> value = map.get(expression);
|
||||
addPointcut(expression, value);
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
|
||||
|
||||
Set extraRoles = getAdditionalRoles(user, username);
|
||||
Set<GrantedAuthority> extraRoles = getAdditionalRoles(user, username);
|
||||
|
||||
if (extraRoles != null) {
|
||||
roles.addAll(extraRoles);
|
||||
|
@ -198,28 +198,25 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
|
|||
}
|
||||
|
||||
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
|
||||
Set authorities = new HashSet();
|
||||
|
||||
if (getGroupSearchBase() == null) {
|
||||
return authorities;
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
|
||||
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<String> 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();
|
||||
|
|
|
@ -155,18 +155,18 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
|
|||
searchControls.setTimeLimit(searchTimeLimit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the attributes that will be returned as part of the search.
|
||||
*<p>
|
||||
* 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.
|
||||
*<p>
|
||||
* 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();
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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";
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
|
|
|
@ -21,14 +21,11 @@ import java.util.Set;
|
|||
|
||||
|
||||
/**
|
||||
* The AuthorityGranter interface is used to map a given principal to role
|
||||
* names.
|
||||
*
|
||||
* <P>
|
||||
* The AuthorityGranter interface is used to map a given principal to role names.
|
||||
* <p>
|
||||
* 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. <br>
|
||||
* </p>
|
||||
* 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. <br>
|
||||
* return null.
|
||||
* <p>
|
||||
* 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<String> grant(Principal principal);
|
||||
}
|
||||
|
|
|
@ -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<GrantedAuthority> 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<GrantedAuthority> 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<GrantedAuthority>();
|
||||
|
||||
//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<Principal> 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<String> 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<GrantedAuthority>(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. <b>MUST NOT use
|
||||
* SecurityContextHolder we are logging out a session that is not related to the current user.</b>
|
||||
* SecurityContextHolder as we are logging out a session that is not related to the current user.</b>
|
||||
*
|
||||
* @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");
|
||||
|
|
|
@ -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<GrantedAuthority> authorities,
|
||||
LoginContext loginContext) {
|
||||
super(principal, credentials, authorities);
|
||||
this.loginContext = loginContext;
|
||||
}
|
||||
|
|
|
@ -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.<p>This LoginModule
|
||||
* provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not really be used in
|
||||
* conjunction with it.</p>
|
||||
* <p>The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.</p>
|
||||
* <p>The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security.
|
||||
* org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.
|
||||
* <p>
|
||||
* This LoginModule provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not
|
||||
* really be used in conjunction with it.
|
||||
* <p>
|
||||
* The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.
|
||||
* <p>
|
||||
* 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 <tt>ignoreMissingAuthentication</tt> 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.</p>
|
||||
* by default. This functionality can be changed with the <tt>ignoreMissingAuthentication</tt> 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 {
|
|||
* <code>LoginContext</code> likely won't provide one that understands Spring Security. Also ignores the
|
||||
* <code>sharedState</code> and <code>options</code> parameters, since none are recognized.
|
||||
*
|
||||
* @param subject the <code>Subject</code> to be authenticated. <p>
|
||||
* @param subject the <code>Subject</code> 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;
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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 <code>GrantedAuthority[]</code> objects will be returned.<p>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.</p>
|
||||
* is successful, an array of <code>GrantedAuthority[]</code> objects will be returned.
|
||||
* <p>
|
||||
* 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.
|
||||
|
|
|
@ -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.<p>A
|
||||
* new <code>Authentication</code> object is created by this class comprising the request <code>Authentication</code>
|
||||
* Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request.
|
||||
* <p>
|
||||
* A new <code>Authentication</code> object is created by this class comprising the request <code>Authentication</code>
|
||||
* object's <code>principal</code>, <code>credentials</code> and the <code>GrantedAuthority</code>[]s returned by the
|
||||
* <code>RemoteAuthenticationManager</code>.</p>
|
||||
* <p>The <code>RemoteAuthenticationManager</code> should not require any special username or password setting on
|
||||
* <code>RemoteAuthenticationManager</code>.
|
||||
* <p>
|
||||
* The <code>RemoteAuthenticationManager</code> 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 <code>Authentication</code> request object. In practical terms this means the
|
||||
* <code>RemoteAuthenticationManager</code> will <b>not</b> 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() {
|
||||
|
|
|
@ -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.<p>To be successfully validated, the
|
||||
* {@link org.springframework.security.providers.rememberme.RememberMeAuthenticationToken#getKeyHash()} must match this class'
|
||||
* {@link #getKey()}.</p>
|
||||
* An {@link AuthenticationProvider} implementation that validates {@link RememberMeAuthenticationToken}s.
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
||||
|
|
|
@ -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<ChannelProcessor> 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<ConfigAttribute> config) throws IOException, ServletException {
|
||||
|
||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
|
||||
Iterator attrs = config.iterator();
|
||||
Iterator<ConfigAttribute> 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<ChannelProcessor> 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<ChannelProcessor>(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;
|
||||
}
|
||||
|
|
|
@ -26,17 +26,12 @@ import javax.servlet.ServletException;
|
|||
|
||||
/**
|
||||
* Decides whether a web channel meets a specific security condition.
|
||||
*
|
||||
* <P>
|
||||
* <code>ChannelProcessor</code> implementations are iterated by the {@link
|
||||
* ChannelDecisionManagerImpl}.
|
||||
* </p>
|
||||
*
|
||||
* <P>
|
||||
* <p>
|
||||
* <code>ChannelProcessor</code> implementations are iterated by the {@link ChannelDecisionManagerImpl}.
|
||||
* <p>
|
||||
* 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.
|
||||
* </p>
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
|
@ -49,16 +44,16 @@ public interface ChannelProcessor {
|
|||
* security based on the requested list of <tt>ConfigAttribute</tt>s.
|
||||
*
|
||||
*/
|
||||
void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
||||
throws IOException, ServletException;
|
||||
void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException;
|
||||
|
||||
/**
|
||||
* Indicates whether this <code>ChannelProcessor</code> is able to process the passed
|
||||
* <code>ConfigAttribute</code>.<p>This allows the <code>ChannelProcessingFilter</code> to check every
|
||||
* configuration attribute can be consumed by the configured <code>ChannelDecisionManager</code>.</p>
|
||||
* <code>ConfigAttribute</code>.
|
||||
* <p>
|
||||
* This allows the <code>ChannelProcessingFilter</code> to check every configuration attribute can be consumed
|
||||
* by the configured <code>ChannelDecisionManager</code>.
|
||||
*
|
||||
* @param attribute a configuration attribute that has been configured against the
|
||||
* <code>ChannelProcessingFilter</code>
|
||||
* @param attribute a configuration attribute that has been configured against the <tt>ChannelProcessingFilter</tt>.
|
||||
*
|
||||
* @return true if this <code>ChannelProcessor</code> can support the passed configuration attribute
|
||||
*/
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Ensures channel security is inactive by review of <code>HttpServletRequest.isSecure()</code> responses.</p>
|
||||
* <P>The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected,
|
||||
* Ensures channel security is inactive by review of <code>HttpServletRequest.isSecure()</code> responses.
|
||||
* <p>
|
||||
* The class responds to one case-sensitive keyword, {@link #getInsecureKeyword}. If this keyword is detected,
|
||||
* <code>HttpServletRequest.isSecure()</code> is used to determine the channel security offered. If channel security
|
||||
* is present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
|
||||
* RetryWithHttpEntryPoint}.</p>
|
||||
* <P>The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.</p>
|
||||
* RetryWithHttpEntryPoint}.
|
||||
* <p>
|
||||
* The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.
|
||||
*
|
||||
* @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<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> 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());
|
||||
|
|
|
@ -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;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Ensures channel security is active by review of <code>HttpServletRequest.isSecure()</code> responses.</p>
|
||||
* <P>The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected,
|
||||
* Ensures channel security is active by review of <code>HttpServletRequest.isSecure()</code> responses.
|
||||
* <p>
|
||||
* The class responds to one case-sensitive keyword, {@link #getSecureKeyword}. If this keyword is detected,
|
||||
* <code>HttpServletRequest.isSecure()</code> is used to determine the channel security offered. If channel security
|
||||
* is not present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
|
||||
* RetryWithHttpsEntryPoint}.</p>
|
||||
* <P>The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.</p>
|
||||
* RetryWithHttpsEntryPoint}.
|
||||
* <p>
|
||||
* The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.
|
||||
*
|
||||
* @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<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> 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());
|
||||
|
|
|
@ -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 + "]";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<SecureRandom> {
|
||||
|
||||
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 <code>null</code> if no additional seeding is needed
|
||||
*/
|
||||
public void setSeed(Resource seed) {
|
||||
this.seed = seed;
|
||||
}
|
||||
public Class<SecureRandom> 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 <code>null</code> if no additional seeding is needed
|
||||
*/
|
||||
public void setSeed(Resource seed) {
|
||||
this.seed = seed;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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 <code>Token</code> that is equal to the original
|
||||
* <code>Token</code> 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 <code>Token</code> that is equal to the original
|
||||
* <code>Token</code> 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();
|
||||
}
|
||||
|
|
|
@ -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 <code>null</code>, 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 <code>TokenService</code> and
|
||||
* reconstructs the corresponding <code>Token</code>.
|
||||
*
|
||||
* @param key as obtained from {@link Token#getKey()} and created by this implementation
|
||||
* @return the token, or <code>null</code> if the token was not issued by this <code>TokenService</code>
|
||||
*/
|
||||
Token verifyToken(String key);
|
||||
/**
|
||||
* Forces the allocation of a new {@link Token}.
|
||||
*
|
||||
* @param the extended information desired in the token (cannot be <code>null</code>, 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 <code>TokenService</code> and
|
||||
* reconstructs the corresponding <code>Token</code>.
|
||||
*
|
||||
* @param key as obtained from {@link Token#getKey()} and created by this implementation
|
||||
* @return the token, or <code>null</code> if the token was not issued by this <code>TokenService</code>
|
||||
*/
|
||||
Token verifyToken(String key);
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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<GrantedAuthority> getGrantedAuthorities() {
|
||||
return authoritiesContainer.getGrantedAuthorities();
|
||||
}
|
||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||
return authoritiesContainer.getGrantedAuthorities();
|
||||
}
|
||||
|
||||
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
|
||||
this.authoritiesContainer.setGrantedAuthorities(authorities);
|
||||
}
|
||||
|
||||
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
|
||||
this.authoritiesContainer.setGrantedAuthorities(authorities);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append(super.toString() + "; ");
|
||||
sb.append(authoritiesContainer);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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 <tt>principalRequestHeader</tt> 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 <tt>principalRequestHeader</tt> 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 <tt>credentialsRequestHeader</tt> 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 <tt>credentialsRequestHeader</tt> 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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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.
|
||||
* <p>
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -70,8 +70,7 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen
|
|||
List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
|
||||
List<GrantedAuthority> 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;
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,16 +8,16 @@ import java.util.Iterator;
|
|||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Simple <tt>PersistentTokenRepository</tt> implementation backed by a Map. Intended for testing only.
|
||||
* Simple <tt>PersistentTokenRepository</tt> 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<String, PersistentRememberMeToken> seriesTokens = new HashMap<String, PersistentRememberMeToken>();
|
||||
|
||||
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<String> series = seriesTokens.keySet().iterator();
|
||||
|
||||
while (series.hasNext()) {
|
||||
Object seriesId = series.next();
|
||||
|
|
|
@ -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<PersistentRememberMeToken> 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<PersistentRememberMeToken> {
|
||||
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));
|
||||
|
|
|
@ -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
|
|||
* <tt>autoLogin</tt> method and the <tt>AuthenticationManager</tt>.
|
||||
*/
|
||||
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 <tt>autoLogin</tt> returns null.
|
||||
*/
|
||||
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException failed) {
|
||||
AuthenticationException failed) {
|
||||
}
|
||||
|
||||
public RememberMeServices getRememberMeServices() {
|
||||
|
|
|
@ -26,8 +26,9 @@ import java.util.TimeZone;
|
|||
|
||||
|
||||
/**
|
||||
* <p>Utility class to generate HTTP dates.</p>
|
||||
* <p>This class is based on code in Apache Tomcat.</p>
|
||||
* Utility class to generate HTTP dates.
|
||||
* <p>
|
||||
* 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<Long,String> formatCache = new HashMap<Long,String>();
|
||||
|
||||
/** Parser cache. */
|
||||
protected static final HashMap parseCache = new HashMap();
|
||||
protected static final HashMap<String,Long> parseCache = new HashMap<String,Long>();
|
||||
|
||||
//~ 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 <code>null</code>, 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;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -186,6 +186,7 @@ public class JdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
|
|||
* Executes the SQL <tt>usersByUsernameQuery</tt> and returns a list of UserDetails objects.
|
||||
* There should normally only be one matching user.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected List<UserDetails> 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<GrantedAuthority> 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<GrantedAuthority> loadGroupAuthorities(String username) {
|
||||
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
|
|
|
@ -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<String> 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<GrantedAuthority> findGroupAuthorities(String groupName) {
|
||||
logger.debug("Loading authorities for group '" + groupName + "'");
|
||||
Assert.hasText(groupName);
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
|
||||
SearchExecutor se = new SearchExecutor() {
|
||||
public NamingEnumeration executeSearch(DirContext ctx) throws NamingException {
|
||||
public NamingEnumeration<SearchResult> 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<ModificationItem> mods = new LinkedList<ModificationItem>(Arrays.asList(ctx.getModificationItems()));
|
||||
ListIterator<ModificationItem> 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
|
||||
|
|
|
@ -38,7 +38,7 @@ public class UserMap {
|
|||
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private Map userMap = new HashMap();
|
||||
private Map<String, UserDetails> userMap = new HashMap<String, UserDetails>();
|
||||
|
||||
//~ 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<String, UserDetails> users) {
|
||||
this.userMap = users;
|
||||
}
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue