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 {
|
public interface Acl extends Serializable {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all of the entries represented by the present <tt>Acl</tt>. Entries associated with
|
* Returns all of the entries represented by the present <tt>Acl</tt>. Entries associated with
|
||||||
* the <tt>Acl</tt> parents are not returned.
|
* the <tt>Acl</tt> parents are not returned.
|
||||||
*
|
*
|
||||||
|
|
|
@ -39,9 +39,10 @@ public interface AclService {
|
||||||
ObjectIdentity[] findChildren(ObjectIdentity parentIdentity);
|
ObjectIdentity[] findChildren(ObjectIdentity parentIdentity);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.<p>This method
|
* Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.
|
||||||
* should not be called as it does not leverage the underlaying implementation's potential ability to filter
|
* <p>
|
||||||
* <tt>Acl</tt> entries based on a {@link Sid} parameter.</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
|
* @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.
|
* Same as {@link #readAclsById(ObjectIdentity[], Sid[])} except it returns only a single Acl.
|
||||||
*
|
*
|
||||||
* @param object to locate an {@link Acl} for
|
* @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)
|
* (may be <tt>null</tt> to denote all entries)
|
||||||
*
|
*
|
||||||
* @return the {@link Acl} for the requested {@link ObjectIdentity} (never <tt>null</tt>)
|
* @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>
|
* not have a map key.</p>
|
||||||
*
|
*
|
||||||
* @param objects the objects to find {@link Acl} information for
|
* @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)
|
* (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>)
|
* @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 + "]";
|
return this.getClass().getSimpleName() + "[" + getPattern() + "=" + mask + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
public final int hashCode() {
|
public final int hashCode() {
|
||||||
return this.mask;
|
return this.mask;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -68,45 +68,45 @@ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAcce
|
||||||
AccessControlEntryImpl rhs = (AccessControlEntryImpl) arg0;
|
AccessControlEntryImpl rhs = (AccessControlEntryImpl) arg0;
|
||||||
|
|
||||||
if (this.acl == null) {
|
if (this.acl == null) {
|
||||||
if (rhs.getAcl() != null) {
|
if (rhs.getAcl() != null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Both this.acl and rhs.acl are null and thus equal
|
// Both this.acl and rhs.acl are null and thus equal
|
||||||
} else {
|
} else {
|
||||||
// this.acl is non-null
|
// this.acl is non-null
|
||||||
if (rhs.getAcl() == null) {
|
if (rhs.getAcl() == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both this.acl and rhs.acl are non-null, so do a comparison
|
// Both this.acl and rhs.acl are non-null, so do a comparison
|
||||||
if (this.acl.getObjectIdentity() == null) {
|
if (this.acl.getObjectIdentity() == null) {
|
||||||
if (rhs.acl.getObjectIdentity() != null) {
|
if (rhs.acl.getObjectIdentity() != null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Both this.acl and rhs.acl are null and thus equal
|
// Both this.acl and rhs.acl are null and thus equal
|
||||||
} else {
|
} else {
|
||||||
// Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null
|
// Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null
|
||||||
if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) {
|
if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.id == null) {
|
if (this.id == null) {
|
||||||
if (rhs.id != null) {
|
if (rhs.id != null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Both this.id and rhs.id are null and thus equal
|
// Both this.id and rhs.id are null and thus equal
|
||||||
} else {
|
} else {
|
||||||
// this.id is non-null
|
// this.id is non-null
|
||||||
if (rhs.id == null) {
|
if (rhs.id == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both this.id and rhs.id are non-null
|
// Both this.id and rhs.id are non-null
|
||||||
if (!this.id.equals(rhs.id)) {
|
if (!this.id.equals(rhs.id)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((this.auditFailure != rhs.isAuditFailure()) || (this.auditSuccess != rhs.isAuditSuccess())
|
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;
|
private String pattern = THIRTY_TWO_RESERVED_OFF;
|
||||||
|
|
||||||
public CumulativePermission() {
|
public CumulativePermission() {
|
||||||
super(0, ' ');
|
super(0, ' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
public CumulativePermission clear(Permission permission) {
|
public CumulativePermission clear(Permission permission) {
|
||||||
|
|
|
@ -36,7 +36,7 @@ public class DefaultPermissionFactory implements PermissionFactory {
|
||||||
Assert.notNull(clazz, "Class required");
|
Assert.notNull(clazz, "Class required");
|
||||||
Assert.isAssignable(Permission.class, clazz);
|
Assert.isAssignable(Permission.class, clazz);
|
||||||
|
|
||||||
Field[] fields = clazz.getFields();
|
Field[] fields = clazz.getFields();
|
||||||
|
|
||||||
for (int i = 0; i < fields.length; i++) {
|
for (int i = 0; i < fields.length; i++) {
|
||||||
try {
|
try {
|
||||||
|
@ -53,20 +53,20 @@ public class DefaultPermissionFactory implements PermissionFactory {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void registerPermission(Permission perm, String permissionName) {
|
public void registerPermission(Permission perm, String permissionName) {
|
||||||
Assert.notNull(perm, "Permission required");
|
Assert.notNull(perm, "Permission required");
|
||||||
Assert.hasText(permissionName, "Permission name required");
|
Assert.hasText(permissionName, "Permission name required");
|
||||||
|
|
||||||
Integer mask = new Integer(perm.getMask());
|
Integer mask = new Integer(perm.getMask());
|
||||||
|
|
||||||
// Ensure no existing Permission uses this integer or code
|
// Ensure no existing Permission uses this integer or code
|
||||||
Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask), "An existing Permission already provides mask " + mask);
|
Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask), "An existing Permission already provides mask " + mask);
|
||||||
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), "An existing Permission already provides name '" + permissionName + "'");
|
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), "An existing Permission already provides name '" + permissionName + "'");
|
||||||
|
|
||||||
// Register the new Permission
|
// Register the new Permission
|
||||||
registeredPermissionsByInteger.put(mask, perm);
|
registeredPermissionsByInteger.put(mask, perm);
|
||||||
registeredPermissionsByName.put(permissionName, perm);
|
registeredPermissionsByName.put(permissionName, perm);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Permission buildFromMask(int mask) {
|
public Permission buildFromMask(int mask) {
|
||||||
if (registeredPermissionsByInteger.containsKey(new Integer(mask))) {
|
if (registeredPermissionsByInteger.containsKey(new Integer(mask))) {
|
||||||
|
|
|
@ -11,14 +11,14 @@ import org.springframework.security.acls.Permission;
|
||||||
*/
|
*/
|
||||||
public interface PermissionFactory {
|
public interface PermissionFactory {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dynamically creates a <code>CumulativePermission</code> or <code>BasePermission</code> representing the
|
* Dynamically creates a <code>CumulativePermission</code> or <code>BasePermission</code> representing the
|
||||||
* active bits in the passed mask.
|
* active bits in the passed mask.
|
||||||
*
|
*
|
||||||
* @param mask to build
|
* @param mask to build
|
||||||
*
|
*
|
||||||
* @return a Permission representing the requested object
|
* @return a Permission representing the requested object
|
||||||
*/
|
*/
|
||||||
public abstract Permission buildFromMask(int mask);
|
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>
|
* already, and adding the returned elements to the cache etc.</p>
|
||||||
* <p>
|
* <p>
|
||||||
* This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
|
* 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) {
|
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 acls the AclImpls (with StubAclParents)
|
||||||
* @param findNow Long-based primary keys to retrieve
|
* @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) {
|
private void lookupPrimaryKeys(final Map acls, final Set findNow, final Sid[] sids) {
|
||||||
Assert.notNull(acls, "ACLs are required");
|
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
|
* The main method.
|
||||||
* in the cache is expected to contain all SIDs. If you have serious performance needs (eg a very large number of
|
* <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
|
* SIDs per object identity), you'll probably want to develop a custom {@link LookupStrategy} implementation
|
||||||
* instead.</p>
|
* instead.
|
||||||
* <p>The implementation works in batch sizes specfied by {@link #batchSize}.</p>
|
* <p>
|
||||||
|
* The implementation works in batch sizes specified by {@link #batchSize}.
|
||||||
*
|
*
|
||||||
* @param objects the identities to lookup (required)
|
* @param objects the identities to lookup (required)
|
||||||
* @param sids the SIDs for which identities are required (ignored by this implementation)
|
* @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());
|
return initializeTransientFields((MutableAcl)element.getValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
public MutableAcl getFromCache(Serializable pk) {
|
public MutableAcl getFromCache(Serializable pk) {
|
||||||
Assert.notNull(pk, "Primary key (identifier) required");
|
Assert.notNull(pk, "Primary key (identifier) required");
|
||||||
|
|
||||||
Element element = null;
|
Element element = null;
|
||||||
|
@ -117,8 +117,8 @@ public class EhCacheBasedAclCache implements AclCache {
|
||||||
|
|
||||||
if (this.aclAuthorizationStrategy == null) {
|
if (this.aclAuthorizationStrategy == null) {
|
||||||
if (acl instanceof AclImpl) {
|
if (acl instanceof AclImpl) {
|
||||||
this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl);
|
this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl);
|
||||||
this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl);
|
this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -131,10 +131,10 @@ public class EhCacheBasedAclCache implements AclCache {
|
||||||
}
|
}
|
||||||
|
|
||||||
private MutableAcl initializeTransientFields(MutableAcl value) {
|
private MutableAcl initializeTransientFields(MutableAcl value) {
|
||||||
if (value instanceof AclImpl) {
|
if (value instanceof AclImpl) {
|
||||||
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
|
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
|
||||||
FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger);
|
FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger);
|
||||||
}
|
}
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -89,7 +89,7 @@ public class JdbcAclService implements AclService {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (objects.size() == 0) {
|
if (objects.size() == 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (ObjectIdentityImpl[]) objects.toArray(new ObjectIdentityImpl[objects.size()]);
|
return (ObjectIdentityImpl[]) objects.toArray(new ObjectIdentityImpl[objects.size()]);
|
||||||
|
|
|
@ -60,7 +60,7 @@ import javax.sql.DataSource;
|
||||||
public class JdbcMutableAclService extends JdbcAclService implements MutableAclService {
|
public class JdbcMutableAclService extends JdbcAclService implements MutableAclService {
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
private boolean foreignKeysInDatabase = true;
|
private boolean foreignKeysInDatabase = true;
|
||||||
private AclCache aclCache;
|
private AclCache aclCache;
|
||||||
private String deleteEntryByObjectIdentityForeignKey = "delete from acl_entry where acl_object_identity=?";
|
private String deleteEntryByObjectIdentityForeignKey = "delete from acl_entry where acl_object_identity=?";
|
||||||
private String deleteObjectIdentityByPrimaryKey = "delete from acl_object_identity where id=?";
|
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");
|
Assert.notNull(objectIdentity.getIdentifier(), "Object Identity doesn't provide an identifier");
|
||||||
|
|
||||||
if (deleteChildren) {
|
if (deleteChildren) {
|
||||||
ObjectIdentity[] children = findChildren(objectIdentity);
|
ObjectIdentity[] children = findChildren(objectIdentity);
|
||||||
if (children != null) {
|
if (children != null) {
|
||||||
for (int i = 0; i < children.length; i++) {
|
for (int i = 0; i < children.length; i++) {
|
||||||
deleteAcl(children[i], true);
|
deleteAcl(children[i], true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!foreignKeysInDatabase) {
|
if (!foreignKeysInDatabase) {
|
||||||
// We need to perform a manual verification for what a FK would normally do
|
// 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
|
// We generally don't do this, in the interests of deadlock management
|
||||||
ObjectIdentity[] children = findChildren(objectIdentity);
|
ObjectIdentity[] children = findChildren(objectIdentity);
|
||||||
if (children != null) {
|
if (children != null) {
|
||||||
throw new ChildrenExistException("Cannot delete '" + objectIdentity + "' (has " + children.length
|
throw new ChildrenExistException("Cannot delete '" + objectIdentity + "' (has " + children.length
|
||||||
+ " children)");
|
+ " children)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Long oidPrimaryKey = retrieveObjectIdentityPrimaryKey(objectIdentity);
|
Long oidPrimaryKey = retrieveObjectIdentityPrimaryKey(objectIdentity);
|
||||||
|
@ -273,7 +273,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
|
||||||
* @param oidPrimaryKey the rows in acl_entry to delete
|
* @param oidPrimaryKey the rows in acl_entry to delete
|
||||||
*/
|
*/
|
||||||
protected void deleteEntries(Long oidPrimaryKey) {
|
protected void deleteEntries(Long oidPrimaryKey) {
|
||||||
jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey,
|
jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey,
|
||||||
new Object[] {oidPrimaryKey});
|
new Object[] {oidPrimaryKey});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -341,12 +341,12 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
|
||||||
}
|
}
|
||||||
|
|
||||||
private void clearCacheIncludingChildren(ObjectIdentity objectIdentity) {
|
private void clearCacheIncludingChildren(ObjectIdentity objectIdentity) {
|
||||||
Assert.notNull(objectIdentity, "ObjectIdentity required");
|
Assert.notNull(objectIdentity, "ObjectIdentity required");
|
||||||
ObjectIdentity[] children = findChildren(objectIdentity);
|
ObjectIdentity[] children = findChildren(objectIdentity);
|
||||||
if (children != null) {
|
if (children != null) {
|
||||||
for (int i = 0; i < children.length; i++) {
|
for (int i = 0; i < children.length; i++) {
|
||||||
clearCacheIncludingChildren(children[i]);
|
clearCacheIncludingChildren(children[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
aclCache.evictFromCache(objectIdentity);
|
aclCache.evictFromCache(objectIdentity);
|
||||||
}
|
}
|
||||||
|
@ -381,20 +381,20 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setClassIdentityQuery(String identityQuery) {
|
public void setClassIdentityQuery(String identityQuery) {
|
||||||
Assert.hasText(identityQuery, "New identity query is required");
|
Assert.hasText(identityQuery, "New identity query is required");
|
||||||
this.classIdentityQuery = identityQuery;
|
this.classIdentityQuery = identityQuery;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSidIdentityQuery(String identityQuery) {
|
public void setSidIdentityQuery(String identityQuery) {
|
||||||
Assert.hasText(identityQuery, "New identity query is required");
|
Assert.hasText(identityQuery, "New identity query is required");
|
||||||
this.sidIdentityQuery = identityQuery;
|
this.sidIdentityQuery = identityQuery;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* @param foreignKeysInDatabase if false this class will perform additional FK constrain checking, which may
|
* @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)
|
* cause deadlocks (the default is true, so deadlocks are avoided but the database is expected to enforce FKs)
|
||||||
*/
|
*/
|
||||||
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
|
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
|
||||||
this.foreignKeysInDatabase = 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>)
|
* @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>
|
* @return a hash code representation of the <tt>ObjectIdentity</tt>
|
||||||
|
|
|
@ -10,115 +10,115 @@ import junit.framework.TestCase;
|
||||||
*/
|
*/
|
||||||
public class AclFormattingUtilsTests extends TestCase {
|
public class AclFormattingUtilsTests extends TestCase {
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public final void testDemergePatternsParametersConstraints() throws Exception {
|
public final void testDemergePatternsParametersConstraints() throws Exception {
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.demergePatterns(null, "SOME STRING");
|
AclFormattingUtils.demergePatterns(null, "SOME STRING");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.demergePatterns("SOME STRING", null);
|
AclFormattingUtils.demergePatterns("SOME STRING", null);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
|
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
|
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void testDemergePatterns() throws Exception {
|
public final void testDemergePatterns() throws Exception {
|
||||||
String original = "...........................A...R";
|
String original = "...........................A...R";
|
||||||
String removeBits = "...............................R";
|
String removeBits = "...............................R";
|
||||||
Assert.assertEquals("...........................A....", AclFormattingUtils
|
Assert.assertEquals("...........................A....", AclFormattingUtils
|
||||||
.demergePatterns(original, removeBits));
|
.demergePatterns(original, removeBits));
|
||||||
|
|
||||||
Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......"));
|
Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......"));
|
||||||
Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL"));
|
Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void testMergePatternsParametersConstraints() throws Exception {
|
public final void testMergePatternsParametersConstraints() throws Exception {
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.mergePatterns(null, "SOME STRING");
|
AclFormattingUtils.mergePatterns(null, "SOME STRING");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.mergePatterns("SOME STRING", null);
|
AclFormattingUtils.mergePatterns("SOME STRING", null);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
|
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
|
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void testMergePatterns() throws Exception {
|
public final void testMergePatterns() throws Exception {
|
||||||
String original = "...............................R";
|
String original = "...............................R";
|
||||||
String extraBits = "...........................A....";
|
String extraBits = "...........................A....";
|
||||||
Assert.assertEquals("...........................A...R", AclFormattingUtils
|
Assert.assertEquals("...........................A...R", AclFormattingUtils
|
||||||
.mergePatterns(original, extraBits));
|
.mergePatterns(original, extraBits));
|
||||||
|
|
||||||
Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......"));
|
Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......"));
|
||||||
Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"));
|
Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void testBinaryPrints() throws Exception {
|
public final void testBinaryPrints() throws Exception {
|
||||||
Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15));
|
Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
|
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
|
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x'));
|
Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,8 +34,8 @@ public class PermissionTests {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void basePermissionTest() {
|
public void basePermissionTest() {
|
||||||
Permission p = BasePermission.buildFromName("WRITE");
|
Permission p = BasePermission.buildFromName("WRITE");
|
||||||
assertNotNull(p);
|
assertNotNull(p);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|
|
@ -31,10 +31,10 @@ public class SpecialPermission extends BasePermission {
|
||||||
* that the static methods will operate correctly.
|
* that the static methods will operate correctly.
|
||||||
*/
|
*/
|
||||||
static {
|
static {
|
||||||
registerPermissionsFor(SpecialPermission.class);
|
registerPermissionsFor(SpecialPermission.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected SpecialPermission(int mask, char code) {
|
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.DataSourceTransactionManager;
|
||||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||||
import org.springframework.security.Authentication;
|
import org.springframework.security.Authentication;
|
||||||
import org.springframework.security.GrantedAuthority;
|
|
||||||
import org.springframework.security.GrantedAuthorityImpl;
|
import org.springframework.security.GrantedAuthorityImpl;
|
||||||
import org.springframework.security.acls.MutableAcl;
|
import org.springframework.security.acls.MutableAcl;
|
||||||
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
|
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.acls.sid.PrincipalSid;
|
||||||
import org.springframework.security.context.SecurityContextHolder;
|
import org.springframework.security.context.SecurityContextHolder;
|
||||||
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.util.AuthorityUtils;
|
||||||
import org.springframework.transaction.TransactionStatus;
|
import org.springframework.transaction.TransactionStatus;
|
||||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||||
|
|
||||||
public class AclPermissionInheritanceTests extends TestCase {
|
public class AclPermissionInheritanceTests extends TestCase {
|
||||||
|
|
||||||
private JdbcMutableAclService aclService;
|
private JdbcMutableAclService aclService;
|
||||||
private JdbcTemplate jdbcTemplate;
|
private JdbcTemplate jdbcTemplate;
|
||||||
private DriverManagerDataSource dataSource;
|
private DriverManagerDataSource dataSource;
|
||||||
private DataSourceTransactionManager txManager;
|
private DataSourceTransactionManager txManager;
|
||||||
private TransactionStatus txStatus;
|
private TransactionStatus txStatus;
|
||||||
|
|
||||||
protected void setUp() throws Exception {
|
protected void setUp() throws Exception {
|
||||||
|
|
||||||
dataSource = new DriverManagerDataSource();
|
|
||||||
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
|
|
||||||
dataSource.setUrl("jdbc:hsqldb:mem:permissiontest");
|
|
||||||
dataSource.setUsername("sa");
|
|
||||||
dataSource.setPassword("");
|
|
||||||
|
|
||||||
jdbcTemplate = new JdbcTemplate(dataSource);
|
dataSource = new DriverManagerDataSource();
|
||||||
|
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
|
||||||
txManager = new DataSourceTransactionManager();
|
dataSource.setUrl("jdbc:hsqldb:mem:permissiontest");
|
||||||
txManager.setDataSource(dataSource);
|
dataSource.setUsername("sa");
|
||||||
|
dataSource.setPassword("");
|
||||||
txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
|
|
||||||
|
jdbcTemplate = new JdbcTemplate(dataSource);
|
||||||
aclService = createAclService(dataSource);
|
|
||||||
|
txManager = new DataSourceTransactionManager();
|
||||||
Authentication auth = new UsernamePasswordAuthenticationToken(
|
txManager.setDataSource(dataSource);
|
||||||
"system", "secret", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")});
|
|
||||||
|
txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
|
||||||
|
|
||||||
|
aclService = createAclService(dataSource);
|
||||||
|
|
||||||
|
Authentication auth = new UsernamePasswordAuthenticationToken("system", "secret",
|
||||||
|
AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
|
||||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tearDown() throws Exception {
|
protected void tearDown() throws Exception {
|
||||||
txManager.rollback(txStatus);
|
txManager.rollback(txStatus);
|
||||||
SecurityContextHolder.clearContext();
|
SecurityContextHolder.clearContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void test1() throws Exception {
|
public void test1() throws Exception {
|
||||||
|
|
||||||
createAclSchema(jdbcTemplate);
|
createAclSchema(jdbcTemplate);
|
||||||
|
|
||||||
ObjectIdentityImpl rootObject =
|
ObjectIdentityImpl rootObject =
|
||||||
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
|
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
|
||||||
|
|
||||||
MutableAcl parent = aclService.createAcl(rootObject);
|
MutableAcl parent = aclService.createAcl(rootObject);
|
||||||
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
||||||
child.setParent(parent);
|
child.setParent(parent);
|
||||||
aclService.updateAcl(child);
|
aclService.updateAcl(child);
|
||||||
|
|
||||||
parent = (AclImpl) aclService.readAclById(rootObject);
|
parent = (AclImpl) aclService.readAclById(rootObject);
|
||||||
parent.insertAce(0, BasePermission.READ,
|
parent.insertAce(0, BasePermission.READ,
|
||||||
new PrincipalSid("john"), true);
|
new PrincipalSid("john"), true);
|
||||||
aclService.updateAcl(parent);
|
aclService.updateAcl(parent);
|
||||||
|
|
||||||
parent = (AclImpl) aclService.readAclById(rootObject);
|
parent = (AclImpl) aclService.readAclById(rootObject);
|
||||||
parent.insertAce(1, BasePermission.READ,
|
parent.insertAce(1, BasePermission.READ,
|
||||||
new PrincipalSid("joe"), true);
|
new PrincipalSid("joe"), true);
|
||||||
aclService.updateAcl(parent);
|
aclService.updateAcl(parent);
|
||||||
|
|
||||||
child = (MutableAcl) aclService.readAclById(
|
child = (MutableAcl) aclService.readAclById(
|
||||||
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
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",
|
assertEquals("Fails because child has a stale reference to its parent",
|
||||||
2, parent.getEntries().length);
|
2, parent.getEntries().length);
|
||||||
assertEquals(1, parent.getEntries()[0].getPermission().getMask());
|
assertEquals(1, parent.getEntries()[0].getPermission().getMask());
|
||||||
assertEquals(new PrincipalSid("john"), parent.getEntries()[0].getSid());
|
assertEquals(new PrincipalSid("john"), parent.getEntries()[0].getSid());
|
||||||
assertEquals(1, parent.getEntries()[1].getPermission().getMask());
|
assertEquals(1, parent.getEntries()[1].getPermission().getMask());
|
||||||
assertEquals(new PrincipalSid("joe"), parent.getEntries()[1].getSid());
|
assertEquals(new PrincipalSid("joe"), parent.getEntries()[1].getSid());
|
||||||
|
|
||||||
}
|
}
|
||||||
public void test2() throws Exception {
|
public void test2() throws Exception {
|
||||||
|
|
||||||
createAclSchema(jdbcTemplate);
|
createAclSchema(jdbcTemplate);
|
||||||
|
|
||||||
ObjectIdentityImpl rootObject =
|
ObjectIdentityImpl rootObject =
|
||||||
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
|
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
|
||||||
|
|
||||||
MutableAcl parent = aclService.createAcl(rootObject);
|
MutableAcl parent = aclService.createAcl(rootObject);
|
||||||
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
||||||
child.setParent(parent);
|
child.setParent(parent);
|
||||||
aclService.updateAcl(child);
|
aclService.updateAcl(child);
|
||||||
|
|
||||||
parent.insertAce(0, BasePermission.ADMINISTRATION,
|
parent.insertAce(0, BasePermission.ADMINISTRATION,
|
||||||
new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
|
new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
|
||||||
aclService.updateAcl(parent);
|
aclService.updateAcl(parent);
|
||||||
|
|
||||||
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
|
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
|
||||||
aclService.updateAcl(parent);
|
aclService.updateAcl(parent);
|
||||||
|
|
||||||
child = (MutableAcl) aclService.readAclById(
|
child = (MutableAcl) aclService.readAclById(
|
||||||
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
|
||||||
|
|
||||||
parent = (MutableAcl) child.getParentAcl();
|
parent = (MutableAcl) child.getParentAcl();
|
||||||
|
|
||||||
assertEquals(2, parent.getEntries().length);
|
assertEquals(2, parent.getEntries().length);
|
||||||
assertEquals(16, parent.getEntries()[0].getPermission().getMask());
|
assertEquals(16, parent.getEntries()[0].getPermission().getMask());
|
||||||
assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()[0].getSid());
|
assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()[0].getSid());
|
||||||
assertEquals(8, parent.getEntries()[1].getPermission().getMask());
|
assertEquals(8, parent.getEntries()[1].getPermission().getMask());
|
||||||
assertEquals(new PrincipalSid("terry"), parent.getEntries()[1].getSid());
|
assertEquals(new PrincipalSid("terry"), parent.getEntries()[1].getSid());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private JdbcMutableAclService createAclService(DriverManagerDataSource ds)
|
private JdbcMutableAclService createAclService(DriverManagerDataSource ds)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
|
|
||||||
GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
|
GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
|
||||||
AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl(
|
AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl(
|
||||||
new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority});
|
new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority});
|
||||||
|
|
||||||
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
|
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
|
||||||
ehCacheManagerFactoryBean.afterPropertiesSet();
|
ehCacheManagerFactoryBean.afterPropertiesSet();
|
||||||
CacheManager cacheManager = (CacheManager) ehCacheManagerFactoryBean.getObject();
|
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void createAclSchema(JdbcTemplate jdbcTemplate) {
|
EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
|
||||||
|
ehCacheFactoryBean.setCacheName("aclAche");
|
||||||
jdbcTemplate.execute("DROP TABLE ACL_ENTRY IF EXISTS;");
|
ehCacheFactoryBean.setCacheManager(cacheManager);
|
||||||
jdbcTemplate.execute("DROP TABLE ACL_OBJECT_IDENTITY IF EXISTS;");
|
ehCacheFactoryBean.afterPropertiesSet();
|
||||||
jdbcTemplate.execute("DROP TABLE ACL_CLASS IF EXISTS");
|
Ehcache ehCache = (Ehcache) ehCacheFactoryBean.getObject();
|
||||||
jdbcTemplate.execute("DROP TABLE ACL_SID IF EXISTS");
|
|
||||||
|
AclCache aclAche = new EhCacheBasedAclCache(ehCache);
|
||||||
jdbcTemplate.execute(
|
|
||||||
|
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(" +
|
"CREATE TABLE ACL_SID(" +
|
||||||
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
||||||
"PRINCIPAL BOOLEAN NOT NULL," +
|
"PRINCIPAL BOOLEAN NOT NULL," +
|
||||||
"SID VARCHAR_IGNORECASE(100) NOT NULL," +
|
"SID VARCHAR_IGNORECASE(100) NOT NULL," +
|
||||||
"CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
|
"CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
|
||||||
jdbcTemplate.execute(
|
jdbcTemplate.execute(
|
||||||
"CREATE TABLE ACL_CLASS(" +
|
"CREATE TABLE ACL_CLASS(" +
|
||||||
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
||||||
"CLASS VARCHAR_IGNORECASE(100) NOT NULL," +
|
"CLASS VARCHAR_IGNORECASE(100) NOT NULL," +
|
||||||
"CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
|
"CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
|
||||||
jdbcTemplate.execute(
|
jdbcTemplate.execute(
|
||||||
"CREATE TABLE ACL_OBJECT_IDENTITY(" +
|
"CREATE TABLE ACL_OBJECT_IDENTITY(" +
|
||||||
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
||||||
"OBJECT_ID_CLASS BIGINT NOT NULL," +
|
"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_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_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID)," +
|
||||||
"CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
|
"CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
|
||||||
jdbcTemplate.execute(
|
jdbcTemplate.execute(
|
||||||
"CREATE TABLE ACL_ENTRY(" +
|
"CREATE TABLE ACL_ENTRY(" +
|
||||||
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
|
"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," +
|
"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)," +
|
"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_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID)," +
|
||||||
"CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");
|
"CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class TestDomainObject {
|
public static class TestDomainObject {
|
||||||
|
|
||||||
private Long id;
|
|
||||||
|
|
||||||
public Long getId() {
|
private Long id;
|
||||||
return id;
|
|
||||||
}
|
public Long getId() {
|
||||||
|
return id;
|
||||||
public void setId(Long id) {
|
}
|
||||||
this.id = id;
|
|
||||||
}
|
public void setId(Long id) {
|
||||||
}
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -35,12 +35,12 @@ import org.springframework.util.FileCopyUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tests {@link BasicLookupStrategy}
|
* Tests {@link BasicLookupStrategy}
|
||||||
*
|
*
|
||||||
* @author Andrei Stefan
|
* @author Andrei Stefan
|
||||||
*/
|
*/
|
||||||
public class BasicLookupStrategyTests {
|
public class BasicLookupStrategyTests {
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
private static JdbcTemplate jdbcTemplate;
|
private static JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
private LookupStrategy strategy;
|
private LookupStrategy strategy;
|
||||||
|
@ -123,7 +123,7 @@ public class BasicLookupStrategyTests {
|
||||||
// Deliberately use an integer for the child, to reproduce bug report in SEC-819
|
// 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));
|
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);
|
checkEntries(topParentOid, middleParentOid, childOid, map);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -138,7 +138,7 @@ public class BasicLookupStrategyTests {
|
||||||
|
|
||||||
// Let's empty the database to force acls retrieval from cache
|
// Let's empty the database to force acls retrieval from cache
|
||||||
emptyDatabase();
|
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);
|
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
|
// Set a batch size to allow multiple database queries in order to retrieve all acls
|
||||||
((BasicLookupStrategy) this.strategy).setBatchSize(1);
|
((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);
|
checkEntries(topParentOid, middleParentOid, childOid, map);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid, Map map)
|
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
|
||||||
throws Exception {
|
Map<ObjectIdentity, Acl> map) throws Exception {
|
||||||
Assert.assertEquals(3, map.size());
|
Assert.assertEquals(3, map.size());
|
||||||
|
|
||||||
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
|
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
|
||||||
|
@ -221,20 +221,20 @@ public class BasicLookupStrategyTests {
|
||||||
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries()[0]).isAuditSuccess());
|
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries()[0]).isAuditSuccess());
|
||||||
Assert.assertFalse((child.getEntries()[0]).isGranting());
|
Assert.assertFalse((child.getEntries()[0]).isGranting());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAllParentsAreRetrievedWhenChildIsLoaded() throws Exception {
|
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);";
|
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);
|
jdbcTemplate.execute(query);
|
||||||
|
|
||||||
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
|
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
|
||||||
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(101));
|
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(101));
|
||||||
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
|
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
|
||||||
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(103));
|
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(103));
|
||||||
|
|
||||||
// Retrieve the child
|
// 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
|
// Check that the child and all its parents were retrieved
|
||||||
Assert.assertNotNull(map.get(childOid));
|
Assert.assertNotNull(map.get(childOid));
|
||||||
Assert.assertEquals(childOid, ((Acl) map.get(childOid)).getObjectIdentity());
|
Assert.assertEquals(childOid, ((Acl) map.get(childOid)).getObjectIdentity());
|
||||||
|
@ -242,7 +242,7 @@ public class BasicLookupStrategyTests {
|
||||||
Assert.assertEquals(middleParentOid, ((Acl) map.get(middleParentOid)).getObjectIdentity());
|
Assert.assertEquals(middleParentOid, ((Acl) map.get(middleParentOid)).getObjectIdentity());
|
||||||
Assert.assertNotNull(map.get(topParentOid));
|
Assert.assertNotNull(map.get(topParentOid));
|
||||||
Assert.assertEquals(topParentOid, ((Acl) map.get(topParentOid)).getObjectIdentity());
|
Assert.assertEquals(topParentOid, ((Acl) map.get(topParentOid)).getObjectIdentity());
|
||||||
|
|
||||||
// The second parent shouldn't have been retrieved
|
// The second parent shouldn't have been retrieved
|
||||||
Assert.assertNull(map.get(middleParent2Oid));
|
Assert.assertNull(map.get(middleParent2Oid));
|
||||||
}
|
}
|
||||||
|
@ -268,9 +268,9 @@ public class BasicLookupStrategyTests {
|
||||||
Permission[] checkPermission = new Permission[] { BasePermission.READ };
|
Permission[] checkPermission = new Permission[] { BasePermission.READ };
|
||||||
Sid[] sids = new Sid[] { new PrincipalSid("ben") };
|
Sid[] sids = new Sid[] { new PrincipalSid("ben") };
|
||||||
ObjectIdentity[] childOids = new ObjectIdentity[] { childOid };
|
ObjectIdentity[] childOids = new ObjectIdentity[] { childOid };
|
||||||
|
|
||||||
((BasicLookupStrategy) this.strategy).setBatchSize(6);
|
((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);
|
Acl foundChildAcl = (Acl) foundAcls.get(childOid);
|
||||||
Assert.assertNotNull(foundChildAcl);
|
Assert.assertNotNull(foundChildAcl);
|
||||||
|
@ -290,5 +290,5 @@ public class BasicLookupStrategyTests {
|
||||||
Assert.assertNotNull(foundParent2Acl);
|
Assert.assertNotNull(foundParent2Acl);
|
||||||
Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false));
|
Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -68,11 +68,10 @@ public class EhCacheBasedAclCacheTests {
|
||||||
|
|
||||||
return cache;
|
return cache;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected=IllegalArgumentException.class)
|
@Test(expected=IllegalArgumentException.class)
|
||||||
public void constructorRejectsNullParameters() throws Exception {
|
public void constructorRejectsNullParameters() throws Exception {
|
||||||
AclCache aclCache = new EhCacheBasedAclCache(null);
|
new EhCacheBasedAclCache(null);
|
||||||
fail("It should have thrown IllegalArgumentException");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -125,7 +124,7 @@ public class EhCacheBasedAclCacheTests {
|
||||||
assertTrue(true);
|
assertTrue(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SEC-527
|
// SEC-527
|
||||||
@Test
|
@Test
|
||||||
public void testDiskSerializationOfMutableAclObjectInstance() throws Exception {
|
public void testDiskSerializationOfMutableAclObjectInstance() throws Exception {
|
||||||
|
@ -138,20 +137,20 @@ public class EhCacheBasedAclCacheTests {
|
||||||
// Serialization test
|
// Serialization test
|
||||||
File file = File.createTempFile("SEC_TEST", ".object");
|
File file = File.createTempFile("SEC_TEST", ".object");
|
||||||
FileOutputStream fos = new FileOutputStream(file);
|
FileOutputStream fos = new FileOutputStream(file);
|
||||||
ObjectOutputStream oos = new ObjectOutputStream(fos);
|
ObjectOutputStream oos = new ObjectOutputStream(fos);
|
||||||
oos.writeObject(acl);
|
oos.writeObject(acl);
|
||||||
oos.close();
|
oos.close();
|
||||||
|
|
||||||
FileInputStream fis = new FileInputStream(file);
|
FileInputStream fis = new FileInputStream(file);
|
||||||
ObjectInputStream ois = new ObjectInputStream(fis);
|
ObjectInputStream ois = new ObjectInputStream(fis);
|
||||||
MutableAcl retrieved = (MutableAcl) ois.readObject();
|
MutableAcl retrieved = (MutableAcl) ois.readObject();
|
||||||
ois.close();
|
ois.close();
|
||||||
|
|
||||||
assertEquals(acl, retrieved);
|
assertEquals(acl, retrieved);
|
||||||
|
|
||||||
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
|
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
|
||||||
assertEquals(null, retrieved1);
|
assertEquals(null, retrieved1);
|
||||||
|
|
||||||
Object retrieved2 = FieldUtils.getProtectedFieldValue("auditLogger", retrieved);
|
Object retrieved2 = FieldUtils.getProtectedFieldValue("auditLogger", retrieved);
|
||||||
assertEquals(null, retrieved2);
|
assertEquals(null, retrieved2);
|
||||||
}
|
}
|
||||||
|
@ -173,7 +172,7 @@ public class EhCacheBasedAclCacheTests {
|
||||||
assertEquals(2, cache.getDiskStoreSize());
|
assertEquals(2, cache.getDiskStoreSize());
|
||||||
assertTrue(cache.isElementOnDisk(acl.getObjectIdentity()));
|
assertTrue(cache.isElementOnDisk(acl.getObjectIdentity()));
|
||||||
assertFalse(cache.isElementInMemory(acl.getObjectIdentity()));
|
assertFalse(cache.isElementInMemory(acl.getObjectIdentity()));
|
||||||
|
|
||||||
// Check we can get from cache the same objects we put in
|
// Check we can get from cache the same objects we put in
|
||||||
assertEquals(myCache.getFromCache(new Long(1)), acl);
|
assertEquals(myCache.getFromCache(new Long(1)), acl);
|
||||||
assertEquals(myCache.getFromCache(identity), acl);
|
assertEquals(myCache.getFromCache(identity), acl);
|
||||||
|
@ -208,7 +207,7 @@ public class EhCacheBasedAclCacheTests {
|
||||||
public void cacheOperationsAclWithParent() throws Exception {
|
public void cacheOperationsAclWithParent() throws Exception {
|
||||||
Ehcache cache = getCache();
|
Ehcache cache = getCache();
|
||||||
EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache);
|
EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache);
|
||||||
|
|
||||||
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
|
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
|
||||||
new GrantedAuthorityImpl("ROLE_GENERAL") });
|
new GrantedAuthorityImpl("ROLE_GENERAL") });
|
||||||
auth.setAuthenticated(true);
|
auth.setAuthenticated(true);
|
||||||
|
@ -221,7 +220,7 @@ public class EhCacheBasedAclCacheTests {
|
||||||
new GrantedAuthorityImpl("ROLE_GENERAL") });
|
new GrantedAuthorityImpl("ROLE_GENERAL") });
|
||||||
MutableAcl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
MutableAcl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||||
MutableAcl parentAcl = new AclImpl(identityParent, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
MutableAcl parentAcl = new AclImpl(identityParent, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||||
|
|
||||||
acl.setParent(parentAcl);
|
acl.setParent(parentAcl);
|
||||||
|
|
||||||
assertEquals(0, cache.getDiskStoreSize());
|
assertEquals(0, cache.getDiskStoreSize());
|
||||||
|
|
|
@ -163,6 +163,7 @@ public class ObjectIdentityTests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
private class MockOtherIdDomainObject {
|
private class MockOtherIdDomainObject {
|
||||||
private Object id;
|
private Object id;
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,7 @@ public class SidTests extends TestCase {
|
||||||
// Check one String-argument constructor
|
// Check one String-argument constructor
|
||||||
try {
|
try {
|
||||||
String string = null;
|
String string = null;
|
||||||
Sid principalSid = new PrincipalSid(string);
|
new PrincipalSid(string);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -27,7 +27,7 @@ public class SidTests extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Sid principalSid = new PrincipalSid("");
|
new PrincipalSid("");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -35,7 +35,7 @@ public class SidTests extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Sid principalSid = new PrincipalSid("johndoe");
|
new PrincipalSid("johndoe");
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
|
@ -45,7 +45,7 @@ public class SidTests extends TestCase {
|
||||||
// Check one Authentication-argument constructor
|
// Check one Authentication-argument constructor
|
||||||
try {
|
try {
|
||||||
Authentication authentication = null;
|
Authentication authentication = null;
|
||||||
Sid principalSid = new PrincipalSid(authentication);
|
new PrincipalSid(authentication);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -54,7 +54,7 @@ public class SidTests extends TestCase {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Authentication authentication = new TestingAuthenticationToken(null, "password");
|
Authentication authentication = new TestingAuthenticationToken(null, "password");
|
||||||
Sid principalSid = new PrincipalSid(authentication);
|
new PrincipalSid(authentication);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -63,7 +63,7 @@ public class SidTests extends TestCase {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
|
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
|
||||||
Sid principalSid = new PrincipalSid(authentication);
|
new PrincipalSid(authentication);
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
|
@ -75,7 +75,7 @@ public class SidTests extends TestCase {
|
||||||
// Check one String-argument constructor
|
// Check one String-argument constructor
|
||||||
try {
|
try {
|
||||||
String string = null;
|
String string = null;
|
||||||
Sid gaSid = new GrantedAuthoritySid(string);
|
new GrantedAuthoritySid(string);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -83,7 +83,7 @@ public class SidTests extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Sid gaSid = new GrantedAuthoritySid("");
|
new GrantedAuthoritySid("");
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -91,7 +91,7 @@ public class SidTests extends TestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Sid gaSid = new GrantedAuthoritySid("ROLE_TEST");
|
new GrantedAuthoritySid("ROLE_TEST");
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
catch (IllegalArgumentException notExpected) {
|
||||||
|
@ -101,7 +101,7 @@ public class SidTests extends TestCase {
|
||||||
// Check one GrantedAuthority-argument constructor
|
// Check one GrantedAuthority-argument constructor
|
||||||
try {
|
try {
|
||||||
GrantedAuthority ga = null;
|
GrantedAuthority ga = null;
|
||||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
new GrantedAuthoritySid(ga);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -110,7 +110,7 @@ public class SidTests extends TestCase {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
GrantedAuthority ga = new GrantedAuthorityImpl(null);
|
GrantedAuthority ga = new GrantedAuthorityImpl(null);
|
||||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
new GrantedAuthoritySid(ga);
|
||||||
Assert.fail("It should have thrown IllegalArgumentException");
|
Assert.fail("It should have thrown IllegalArgumentException");
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException expected) {
|
catch (IllegalArgumentException expected) {
|
||||||
|
@ -119,7 +119,7 @@ public class SidTests extends TestCase {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
||||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
new GrantedAuthoritySid(ga);
|
||||||
Assert.assertTrue(true);
|
Assert.assertTrue(true);
|
||||||
}
|
}
|
||||||
catch (IllegalArgumentException notExpected) {
|
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.Assertion;
|
||||||
import org.jasig.cas.client.validation.TicketValidationException;
|
import org.jasig.cas.client.validation.TicketValidationException;
|
||||||
import org.jasig.cas.client.validation.TicketValidator;
|
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.beans.factory.InitializingBean;
|
||||||
|
|
||||||
import org.springframework.context.MessageSource;
|
import org.springframework.context.MessageSource;
|
||||||
import org.springframework.context.MessageSourceAware;
|
import org.springframework.context.MessageSourceAware;
|
||||||
import org.springframework.context.support.MessageSourceAccessor;
|
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;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
|
||||||
|
@ -60,9 +51,6 @@ import org.springframework.util.Assert;
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
|
public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
|
||||||
//~ Static fields/initializers =====================================================================================
|
|
||||||
|
|
||||||
private static final Log logger = LogFactory.getLog(CasAuthenticationProvider.class);
|
|
||||||
|
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
|
@ -144,17 +132,17 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
|
||||||
try {
|
try {
|
||||||
final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
|
final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
|
||||||
final UserDetails userDetails = loadUserByAssertion(assertion);
|
final UserDetails userDetails = loadUserByAssertion(assertion);
|
||||||
userDetailsChecker.check(userDetails);
|
userDetailsChecker.check(userDetails);
|
||||||
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), userDetails.getAuthorities(), userDetails, assertion);
|
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), userDetails.getAuthorities(), userDetails, assertion);
|
||||||
} catch (final TicketValidationException e) {
|
} catch (final TicketValidationException e) {
|
||||||
throw new BadCredentialsException(e.getMessage(), 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
|
* 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.
|
* can override this method and retrieve the user based on any criteria they desire.
|
||||||
*
|
*
|
||||||
* @param assertion The CAS Assertion.
|
* @param assertion The CAS Assertion.
|
||||||
* @returns the UserDetails.
|
* @returns the UserDetails.
|
||||||
*/
|
*/
|
||||||
|
@ -169,7 +157,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
|
||||||
public void setUserDetailsService(final UserDetailsService userDetailsService) {
|
public void setUserDetailsService(final UserDetailsService userDetailsService) {
|
||||||
this.userDetailsService = userDetailsService;
|
this.userDetailsService = userDetailsService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setServiceProperties(final ServiceProperties serviceProperties) {
|
public void setServiceProperties(final ServiceProperties serviceProperties) {
|
||||||
this.serviceProperties = serviceProperties;
|
this.serviceProperties = serviceProperties;
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,31 +33,31 @@ import org.springframework.security.providers.cas.StatelessTicketCache;
|
||||||
*/
|
*/
|
||||||
public final class NullStatelessTicketCache implements StatelessTicketCache {
|
public final class NullStatelessTicketCache implements StatelessTicketCache {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return null since we are not storing any tickets.
|
* @return null since we are not storing any tickets.
|
||||||
*/
|
*/
|
||||||
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
|
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is a no-op since we are not storing tickets.
|
* This is a no-op since we are not storing tickets.
|
||||||
*/
|
*/
|
||||||
public void putTicketInCache(final CasAuthenticationToken token) {
|
public void putTicketInCache(final CasAuthenticationToken token) {
|
||||||
// nothing to do
|
// nothing to do
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is a no-op since we are not storing tickets.
|
* This is a no-op since we are not storing tickets.
|
||||||
*/
|
*/
|
||||||
public void removeTicketFromCache(final CasAuthenticationToken token) {
|
public void removeTicketFromCache(final CasAuthenticationToken token) {
|
||||||
// nothing to do
|
// nothing to do
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is a no-op since we are not storing tickets.
|
* This is a no-op since we are not storing tickets.
|
||||||
*/
|
*/
|
||||||
public void removeTicketFromCache(final String serviceTicket) {
|
public void removeTicketFromCache(final String serviceTicket) {
|
||||||
// nothing to do
|
// nothing to do
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -60,13 +60,13 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint,
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.hasLength(this.loginUrl, "loginUrl must be specified");
|
Assert.hasLength(this.loginUrl, "loginUrl must be specified");
|
||||||
Assert.notNull(this.serviceProperties, "serviceProperties must be specified");
|
Assert.notNull(this.serviceProperties, "serviceProperties must be specified");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void commence(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse,
|
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 HttpServletResponse response = (HttpServletResponse) servletResponse;
|
||||||
final String urlEncodedService = CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, "ticket", this.encodeServiceUrlWithSessionId);
|
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) {
|
public void setEncodeServiceUrlWithSessionId(final boolean encodeServiceUrlWithSessionId) {
|
||||||
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
|
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,7 +38,7 @@ public class ServiceProperties implements InitializingBean {
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
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.User;
|
||||||
import org.springframework.security.userdetails.UserDetails;
|
import org.springframework.security.userdetails.UserDetails;
|
||||||
import org.springframework.security.userdetails.UserDetailsService;
|
import org.springframework.security.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.util.AuthorityUtils;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
@ -54,12 +55,12 @@ public class CasAuthenticationProviderTests {
|
||||||
|
|
||||||
private UserDetails makeUserDetails() {
|
private UserDetails makeUserDetails() {
|
||||||
return new User("user", "password", true, true, true, true,
|
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() {
|
private UserDetails makeUserDetailsFromAuthoritiesPopulator() {
|
||||||
return new User("user", "password", true, true, true, true,
|
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() {
|
private ServiceProperties makeServiceProperties() {
|
||||||
|
@ -83,8 +84,8 @@ public class CasAuthenticationProviderTests {
|
||||||
cap.setTicketValidator(new MockTicketValidator(true));
|
cap.setTicketValidator(new MockTicketValidator(true));
|
||||||
cap.afterPropertiesSet();
|
cap.afterPropertiesSet();
|
||||||
|
|
||||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER,
|
UsernamePasswordAuthenticationToken token =
|
||||||
"ST-123");
|
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, "ST-123");
|
||||||
token.setDetails("details");
|
token.setDetails("details");
|
||||||
|
|
||||||
Authentication result = cap.authenticate(token);
|
Authentication result = cap.authenticate(token);
|
||||||
|
@ -124,8 +125,8 @@ public class CasAuthenticationProviderTests {
|
||||||
cap.setServiceProperties(makeServiceProperties());
|
cap.setServiceProperties(makeServiceProperties());
|
||||||
cap.afterPropertiesSet();
|
cap.afterPropertiesSet();
|
||||||
|
|
||||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER,
|
UsernamePasswordAuthenticationToken token =
|
||||||
"ST-456");
|
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER, "ST-456");
|
||||||
token.setDetails("details");
|
token.setDetails("details");
|
||||||
|
|
||||||
Authentication result = cap.authenticate(token);
|
Authentication result = cap.authenticate(token);
|
||||||
|
@ -183,7 +184,7 @@ public class CasAuthenticationProviderTests {
|
||||||
cap.afterPropertiesSet();
|
cap.afterPropertiesSet();
|
||||||
|
|
||||||
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
|
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
|
||||||
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), assertion);
|
AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion);
|
||||||
|
|
||||||
cap.authenticate(token);
|
cap.authenticate(token);
|
||||||
}
|
}
|
||||||
|
@ -275,7 +276,7 @@ public class CasAuthenticationProviderTests {
|
||||||
cap.afterPropertiesSet();
|
cap.afterPropertiesSet();
|
||||||
|
|
||||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
|
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
|
||||||
"password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
|
"password", AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||||
assertEquals(null, cap.authenticate(token));
|
assertEquals(null, cap.authenticate(token));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -295,10 +296,10 @@ public class CasAuthenticationProviderTests {
|
||||||
}
|
}
|
||||||
|
|
||||||
private class MockStatelessTicketCache implements StatelessTicketCache {
|
private class MockStatelessTicketCache implements StatelessTicketCache {
|
||||||
private Map cache = new HashMap();
|
private Map<String, CasAuthenticationToken> cache = new HashMap<String, CasAuthenticationToken>();
|
||||||
|
|
||||||
public CasAuthenticationToken getByTicketId(String serviceTicket) {
|
public CasAuthenticationToken getByTicketId(String serviceTicket) {
|
||||||
return (CasAuthenticationToken) cache.get(serviceTicket);
|
return cache.get(serviceTicket);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void putTicketInCache(CasAuthenticationToken token) {
|
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.Assertion;
|
||||||
import org.jasig.cas.client.validation.AssertionImpl;
|
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.providers.cas.CasAuthenticationToken;
|
||||||
import org.springframework.security.userdetails.User;
|
import org.springframework.security.userdetails.User;
|
||||||
|
import org.springframework.security.util.AuthorityUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @author Scott Battaglia
|
* @author Scott Battaglia
|
||||||
* @version $Revision$ $Date$
|
* @version $Id$
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractStatelessTicketCacheTests {
|
public abstract class AbstractStatelessTicketCacheTests {
|
||||||
|
|
||||||
protected CasAuthenticationToken getToken() {
|
protected CasAuthenticationToken getToken() {
|
||||||
List<String> proxyList = new ArrayList<String>();
|
List<String> proxyList = new ArrayList<String>();
|
||||||
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||||
|
|
||||||
User user = new User("rod", "password", true, true, true, true,
|
User user = new User("rod", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
|
||||||
final Assertion assertion = new AssertionImpl("rod");
|
final Assertion assertion = new AssertionImpl("rod");
|
||||||
|
|
||||||
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
|
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
|
||||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
|
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion);
|
||||||
assertion);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,18 +30,18 @@ import static org.junit.Assert.*;
|
||||||
*/
|
*/
|
||||||
public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests {
|
public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests {
|
||||||
|
|
||||||
private StatelessTicketCache cache = new NullStatelessTicketCache();
|
private StatelessTicketCache cache = new NullStatelessTicketCache();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testGetter() {
|
public void testGetter() {
|
||||||
assertNull(cache.getByTicketId(null));
|
assertNull(cache.getByTicketId(null));
|
||||||
assertNull(cache.getByTicketId("test"));
|
assertNull(cache.getByTicketId("test"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testInsertAndGet() {
|
public void testInsertAndGet() {
|
||||||
final CasAuthenticationToken token = getToken();
|
final CasAuthenticationToken token = getToken();
|
||||||
cache.putTicketInCache(token);
|
cache.putTicketInCache(token);
|
||||||
assertNull(cache.getByTicketId((String) token.getCredentials()));
|
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
|
* A <code>GrantedAuthority</code> must either represent itself as a
|
||||||
* <code>String</code> or be specifically supported by an {@link
|
* <code>String</code> or be specifically supported by an {@link
|
||||||
* AccessDecisionManager}.
|
* AccessDecisionManager}.
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* Implementations must implement {@link Comparable} in order to ensure that
|
* Implementations must implement {@link Comparable} in order to ensure that
|
||||||
* array sorting logic guaranteed by {@link UserDetails#getAuthorities()} can
|
* array sorting logic guaranteed by {@link UserDetails#getAuthorities()} can
|
||||||
* be reliably implemented.
|
* be reliably implemented.
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
|
|
@ -73,16 +73,16 @@ public class GrantedAuthorityImpl implements GrantedAuthority, Serializable {
|
||||||
return this.role;
|
return this.role;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int compareTo(Object o) {
|
public int compareTo(Object o) {
|
||||||
if (o != null && o instanceof GrantedAuthority) {
|
if (o != null && o instanceof GrantedAuthority) {
|
||||||
String rhsRole = ((GrantedAuthority) o).getAuthority();
|
String rhsRole = ((GrantedAuthority) o).getAuthority();
|
||||||
|
|
||||||
if (rhsRole == null) {
|
if (rhsRole == null) {
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
return role.compareTo(rhsRole);
|
return role.compareTo(rhsRole);
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -159,7 +159,7 @@ public class ConcurrentSessionControllerImpl implements ConcurrentSessionControl
|
||||||
this.sessionRegistry = sessionRegistry;
|
this.sessionRegistry = sessionRegistry;
|
||||||
}
|
}
|
||||||
|
|
||||||
public SessionRegistry getSessionRegistry() {
|
public SessionRegistry getSessionRegistry() {
|
||||||
return sessionRegistry;
|
return sessionRegistry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,6 @@ import org.springframework.security.ui.logout.SecurityContextLogoutHandler;
|
||||||
import org.springframework.security.util.UrlUtils;
|
import org.springframework.security.util.UrlUtils;
|
||||||
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
import javax.servlet.FilterChain;
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
|
|
|
@ -17,45 +17,45 @@ import org.w3c.dom.Element;
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements BeanDefinitionParser {
|
public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements BeanDefinitionParser {
|
||||||
private static final String CACHE_REF = "cache-ref";
|
private static final String CACHE_REF = "cache-ref";
|
||||||
public static final String CACHING_SUFFIX = ".caching";
|
public static final String CACHING_SUFFIX = ".caching";
|
||||||
|
|
||||||
/** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */
|
/** UserDetailsService bean Id. For use in a stateful context (i.e. in AuthenticationProviderBDP) */
|
||||||
private String id;
|
private String id;
|
||||||
|
|
||||||
protected abstract String getBeanClassName(Element element);
|
protected abstract String getBeanClassName(Element element);
|
||||||
|
|
||||||
protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder);
|
protected abstract void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder);
|
||||||
|
|
||||||
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element));
|
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(getBeanClassName(element));
|
||||||
|
|
||||||
doParse(element, parserContext, builder);
|
doParse(element, parserContext, builder);
|
||||||
|
|
||||||
RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition();
|
RootBeanDefinition userService = (RootBeanDefinition) builder.getBeanDefinition();
|
||||||
String beanId = resolveId(element, userService, parserContext);
|
String beanId = resolveId(element, userService, parserContext);
|
||||||
|
|
||||||
parserContext.getRegistry().registerBeanDefinition(beanId, userService);
|
parserContext.getRegistry().registerBeanDefinition(beanId, userService);
|
||||||
|
|
||||||
String cacheRef = element.getAttribute(CACHE_REF);
|
String cacheRef = element.getAttribute(CACHE_REF);
|
||||||
|
|
||||||
// Register a caching version of the user service if there's a cache-ref
|
// Register a caching version of the user service if there's a cache-ref
|
||||||
if (StringUtils.hasText(cacheRef)) {
|
if (StringUtils.hasText(cacheRef)) {
|
||||||
BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class);
|
BeanDefinitionBuilder cachingUSBuilder = BeanDefinitionBuilder.rootBeanDefinition(CachingUserDetailsService.class);
|
||||||
cachingUSBuilder.addConstructorArgReference(beanId);
|
cachingUSBuilder.addConstructorArgReference(beanId);
|
||||||
|
|
||||||
cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
|
cachingUSBuilder.addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
|
||||||
BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition();
|
BeanDefinition cachingUserService = cachingUSBuilder.getBeanDefinition();
|
||||||
parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService);
|
parserContext.getRegistry().registerBeanDefinition(beanId + CACHING_SUFFIX, cachingUserService);
|
||||||
}
|
}
|
||||||
|
|
||||||
id = beanId;
|
id = beanId;
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
|
private String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext)
|
||||||
throws BeanDefinitionStoreException {
|
throws BeanDefinitionStoreException {
|
||||||
|
|
||||||
String id = element.getAttribute("id");
|
String id = element.getAttribute("id");
|
||||||
|
|
||||||
|
@ -76,7 +76,7 @@ public abstract class AbstractUserDetailsServiceBeanDefinitionParser implements
|
||||||
return BeanIds.USER_DETAILS_SERVICE;
|
return BeanIds.USER_DETAILS_SERVICE;
|
||||||
}
|
}
|
||||||
|
|
||||||
String getId() {
|
String getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,11 +19,11 @@ import org.w3c.dom.Element;
|
||||||
*/
|
*/
|
||||||
public class AuthenticationManagerBeanDefinitionParser implements BeanDefinitionParser {
|
public class AuthenticationManagerBeanDefinitionParser implements BeanDefinitionParser {
|
||||||
private static final String ATT_SESSION_CONTROLLER_REF = "session-controller-ref";
|
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) {
|
public BeanDefinition parse(Element element, ParserContext parserContext) {
|
||||||
ConfigUtils.registerProviderManagerIfNecessary(parserContext);
|
ConfigUtils.registerProviderManagerIfNecessary(parserContext);
|
||||||
|
|
||||||
String alias = element.getAttribute(ATT_ALIAS);
|
String alias = element.getAttribute(ATT_ALIAS);
|
||||||
|
|
||||||
if (!StringUtils.hasText(alias)) {
|
if (!StringUtils.hasText(alias)) {
|
||||||
|
@ -33,16 +33,16 @@ public class AuthenticationManagerBeanDefinitionParser implements BeanDefinition
|
||||||
String sessionControllerRef = element.getAttribute(ATT_SESSION_CONTROLLER_REF);
|
String sessionControllerRef = element.getAttribute(ATT_SESSION_CONTROLLER_REF);
|
||||||
|
|
||||||
if (StringUtils.hasText(sessionControllerRef)) {
|
if (StringUtils.hasText(sessionControllerRef)) {
|
||||||
BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER);
|
BeanDefinition authManager = parserContext.getRegistry().getBeanDefinition(BeanIds.AUTHENTICATION_MANAGER);
|
||||||
ConfigUtils.setSessionControllerOnAuthenticationManager(parserContext,
|
ConfigUtils.setSessionControllerOnAuthenticationManager(parserContext,
|
||||||
BeanIds.CONCURRENT_SESSION_CONTROLLER, element);
|
BeanIds.CONCURRENT_SESSION_CONTROLLER, element);
|
||||||
authManager.getPropertyValues().addPropertyValue("sessionController",
|
authManager.getPropertyValues().addPropertyValue("sessionController",
|
||||||
new RuntimeBeanReference(sessionControllerRef));
|
new RuntimeBeanReference(sessionControllerRef));
|
||||||
RootBeanDefinition sessionRegistryInjector = new RootBeanDefinition(SessionRegistryInjectionBeanPostProcessor.class);
|
RootBeanDefinition sessionRegistryInjector = new RootBeanDefinition(SessionRegistryInjectionBeanPostProcessor.class);
|
||||||
sessionRegistryInjector.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
sessionRegistryInjector.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||||
sessionRegistryInjector.getConstructorArgumentValues().addGenericArgumentValue(sessionControllerRef);
|
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);
|
parserContext.getRegistry().registerAlias(BeanIds.AUTHENTICATION_MANAGER, alias);
|
||||||
|
|
|
@ -20,30 +20,30 @@ import org.w3c.dom.Element;
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class BasicAuthenticationBeanDefinitionParser implements BeanDefinitionParser {
|
public class BasicAuthenticationBeanDefinitionParser implements BeanDefinitionParser {
|
||||||
private String realmName;
|
private String realmName;
|
||||||
|
|
||||||
public BasicAuthenticationBeanDefinitionParser(String realmName) {
|
public BasicAuthenticationBeanDefinitionParser(String realmName) {
|
||||||
this.realmName = realmName;
|
this.realmName = realmName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public BeanDefinition parse(Element elt, ParserContext parserContext) {
|
public BeanDefinition parse(Element elt, ParserContext parserContext) {
|
||||||
BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder.rootBeanDefinition(BasicProcessingFilter.class);
|
BeanDefinitionBuilder filterBuilder = BeanDefinitionBuilder.rootBeanDefinition(BasicProcessingFilter.class);
|
||||||
RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class);
|
RootBeanDefinition entryPoint = new RootBeanDefinition(BasicProcessingFilterEntryPoint.class);
|
||||||
entryPoint.setSource(parserContext.extractSource(elt));
|
entryPoint.setSource(parserContext.extractSource(elt));
|
||||||
entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
entryPoint.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||||
|
|
||||||
entryPoint.getPropertyValues().addPropertyValue("realmName", realmName);
|
entryPoint.getPropertyValues().addPropertyValue("realmName", realmName);
|
||||||
|
|
||||||
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint);
|
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, entryPoint);
|
||||||
|
|
||||||
filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
|
filterBuilder.addPropertyValue("authenticationManager", new RuntimeBeanReference(BeanIds.AUTHENTICATION_MANAGER));
|
||||||
filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT));
|
filterBuilder.addPropertyValue("authenticationEntryPoint", new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT));
|
||||||
|
|
||||||
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER,
|
parserContext.getRegistry().registerBeanDefinition(BeanIds.BASIC_AUTHENTICATION_FILTER,
|
||||||
filterBuilder.getBeanDefinition());
|
filterBuilder.getBeanDefinition());
|
||||||
ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER));
|
ConfigUtils.addHttpFilter(parserContext, new RuntimeBeanReference(BeanIds.BASIC_AUTHENTICATION_FILTER));
|
||||||
parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(),
|
parserContext.registerComponent(new BeanComponentDefinition(filterBuilder.getBeanDefinition(),
|
||||||
BeanIds.BASIC_AUTHENTICATION_FILTER));
|
BeanIds.BASIC_AUTHENTICATION_FILTER));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,33 +12,33 @@ import org.springframework.util.Assert;
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*/
|
*/
|
||||||
class CachingUserDetailsService implements UserDetailsService {
|
class CachingUserDetailsService implements UserDetailsService {
|
||||||
private UserCache userCache = new NullUserCache();
|
private UserCache userCache = new NullUserCache();
|
||||||
private UserDetailsService delegate;
|
private UserDetailsService delegate;
|
||||||
|
|
||||||
CachingUserDetailsService(UserDetailsService delegate) {
|
CachingUserDetailsService(UserDetailsService delegate) {
|
||||||
this.delegate = delegate;
|
this.delegate = delegate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserCache getUserCache() {
|
public UserCache getUserCache() {
|
||||||
return userCache;
|
return userCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setUserCache(UserCache userCache) {
|
public void setUserCache(UserCache userCache) {
|
||||||
this.userCache = userCache;
|
this.userCache = userCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UserDetails loadUserByUsername(String username) {
|
public UserDetails loadUserByUsername(String username) {
|
||||||
UserDetails user = userCache.getUserFromCache(username);
|
UserDetails user = userCache.getUserFromCache(username);
|
||||||
|
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
user = delegate.loadUserByUsername(username);
|
user = delegate.loadUserByUsername(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " +
|
Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " +
|
||||||
"This is an interface contract violation");
|
"This is an interface contract violation");
|
||||||
|
|
||||||
userCache.putUserInCache(user);
|
userCache.putUserInCache(user);
|
||||||
|
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -87,11 +87,13 @@ abstract class ConfigUtils {
|
||||||
((ArrayList) authManager.getPropertyValues().getPropertyValue("providerBeanNames").getValue()).add(beanName);
|
((ArrayList) authManager.getPropertyValues().getPropertyValue("providerBeanNames").getValue()).add(beanName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
static ManagedList getRegisteredAfterInvocationProviders(ParserContext parserContext) {
|
static ManagedList getRegisteredAfterInvocationProviders(ParserContext parserContext) {
|
||||||
BeanDefinition manager = registerAfterInvocationProviderManagerIfNecessary(parserContext);
|
BeanDefinition manager = registerAfterInvocationProviderManagerIfNecessary(parserContext);
|
||||||
return (ManagedList) manager.getPropertyValues().getPropertyValue("providers").getValue();
|
return (ManagedList) manager.getPropertyValues().getPropertyValue("providers").getValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private static BeanDefinition registerAfterInvocationProviderManagerIfNecessary(ParserContext parserContext) {
|
private static BeanDefinition registerAfterInvocationProviderManagerIfNecessary(ParserContext parserContext) {
|
||||||
if(parserContext.getRegistry().containsBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER)) {
|
if(parserContext.getRegistry().containsBeanDefinition(BeanIds.AFTER_INVOCATION_MANAGER)) {
|
||||||
return parserContext.getRegistry().getBeanDefinition(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";
|
return "org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource";
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
|
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
|
||||||
List<Element> interceptUrls = DomUtils.getChildElementsByTagName(element, "intercept-url");
|
List<Element> interceptUrls = DomUtils.getChildElementsByTagName(element, "intercept-url");
|
||||||
|
|
||||||
|
|
|
@ -166,6 +166,7 @@ class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionParser {
|
||||||
pc.getRegistry().registerBeanDefinition(ACCESS_MANAGER_ID, accessMgrBuilder.getBeanDefinition());
|
pc.getRegistry().registerBeanDefinition(ACCESS_MANAGER_ID, accessMgrBuilder.getBeanDefinition());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private void registerDelegatingMethodDefinitionSource(ParserContext parserContext, ManagedList delegates, Object source) {
|
private void registerDelegatingMethodDefinitionSource(ParserContext parserContext, ManagedList delegates, Object source) {
|
||||||
if (parserContext.getRegistry().containsBeanDefinition(DELEGATING_METHOD_DEFINITION_SOURCE_ID)) {
|
if (parserContext.getRegistry().containsBeanDefinition(DELEGATING_METHOD_DEFINITION_SOURCE_ID)) {
|
||||||
parserContext.getReaderContext().error("Duplicate <global-method-security> detected.", source);
|
parserContext.getReaderContext().error("Duplicate <global-method-security> detected.", source);
|
||||||
|
|
|
@ -42,7 +42,6 @@ class InternalInterceptMethodsBeanDefinitionDecorator extends AbstractIntercepto
|
||||||
static final String ATT_ACCESS = "access";
|
static final String ATT_ACCESS = "access";
|
||||||
private static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
|
private static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
protected BeanDefinition createInterceptorDefinition(Node node) {
|
protected BeanDefinition createInterceptorDefinition(Node node) {
|
||||||
Element interceptMethodsElt = (Element)node;
|
Element interceptMethodsElt = (Element)node;
|
||||||
BeanDefinitionBuilder interceptor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityInterceptor.class);
|
BeanDefinitionBuilder interceptor = BeanDefinitionBuilder.rootBeanDefinition(MethodSecurityInterceptor.class);
|
||||||
|
|
|
@ -11,11 +11,11 @@ import org.w3c.dom.Element;
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServiceBeanDefinitionParser {
|
public class JdbcUserServiceBeanDefinitionParser extends AbstractUserDetailsServiceBeanDefinitionParser {
|
||||||
static final String ATT_DATA_SOURCE = "data-source-ref";
|
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_USERS_BY_USERNAME_QUERY = "users-by-username-query";
|
||||||
static final String ATT_AUTHORITIES_BY_USERNAME_QUERY = "authorities-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_GROUP_AUTHORITIES_QUERY = "group-authorities-by-username-query";
|
||||||
static final String ATT_ROLE_PREFIX = "role-prefix";
|
static final String ATT_ROLE_PREFIX = "role-prefix";
|
||||||
|
|
||||||
protected String getBeanClassName(Element element) {
|
protected String getBeanClassName(Element element) {
|
||||||
return "org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager";
|
return "org.springframework.security.userdetails.jdbc.JdbcUserDetailsManager";
|
||||||
|
|
|
@ -14,8 +14,8 @@ public class SecurityNamespaceHandler extends NamespaceHandlerSupport {
|
||||||
|
|
||||||
public void init() {
|
public void init() {
|
||||||
// Parsers
|
// Parsers
|
||||||
registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser());
|
registerBeanDefinitionParser(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser());
|
||||||
registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser());
|
registerBeanDefinitionParser(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser());
|
||||||
registerBeanDefinitionParser(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser());
|
registerBeanDefinitionParser(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser());
|
||||||
registerBeanDefinitionParser(Elements.HTTP, new HttpSecurityBeanDefinitionParser());
|
registerBeanDefinitionParser(Elements.HTTP, new HttpSecurityBeanDefinitionParser());
|
||||||
registerBeanDefinitionParser(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser());
|
registerBeanDefinitionParser(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser());
|
||||||
|
|
|
@ -56,7 +56,6 @@ class SessionRegistryInjectionBeanPostProcessor implements BeanPostProcessor, Be
|
||||||
return bean;
|
return bean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private SessionRegistry getSessionRegistry() {
|
private SessionRegistry getSessionRegistry() {
|
||||||
if (sessionRegistry != null) {
|
if (sessionRegistry != null) {
|
||||||
return sessionRegistry;
|
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.");
|
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;
|
return sessionRegistry;
|
||||||
}
|
}
|
||||||
|
|
|
@ -30,11 +30,11 @@ import org.springframework.util.Assert;
|
||||||
public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticationEvent {
|
public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticationEvent {
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
private Class generatedBy;
|
private Class<?> generatedBy;
|
||||||
|
|
||||||
//~ Constructors ===================================================================================================
|
//~ Constructors ===================================================================================================
|
||||||
|
|
||||||
public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class generatedBy) {
|
public InteractiveAuthenticationSuccessEvent(Authentication authentication, Class<?> generatedBy) {
|
||||||
super(authentication);
|
super(authentication);
|
||||||
Assert.notNull(generatedBy);
|
Assert.notNull(generatedBy);
|
||||||
this.generatedBy = generatedBy;
|
this.generatedBy = generatedBy;
|
||||||
|
@ -48,7 +48,7 @@ public class InteractiveAuthenticationSuccessEvent extends AbstractAuthenticatio
|
||||||
*
|
*
|
||||||
* @return the class
|
* @return the class
|
||||||
*/
|
*/
|
||||||
public Class getGeneratedBy() {
|
public Class<?> getGeneratedBy() {
|
||||||
return generatedBy;
|
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
|
* Outputs authentication-related application events to Commons Logging.
|
||||||
* the warning level.</p>
|
* <p>
|
||||||
|
* All authentication events are logged at the warning level.
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
@ -44,7 +45,7 @@ public class LoggerListener implements ApplicationListener {
|
||||||
AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event;
|
AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event;
|
||||||
|
|
||||||
if (!logInteractiveAuthenticationSuccessEvents && authEvent instanceof InteractiveAuthenticationSuccessEvent) {
|
if (!logInteractiveAuthenticationSuccessEvents && authEvent instanceof InteractiveAuthenticationSuccessEvent) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (logger.isWarnEnabled()) {
|
if (logger.isWarnEnabled()) {
|
||||||
|
@ -62,12 +63,12 @@ public class LoggerListener implements ApplicationListener {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isLogInteractiveAuthenticationSuccessEvents() {
|
public boolean isLogInteractiveAuthenticationSuccessEvents() {
|
||||||
return logInteractiveAuthenticationSuccessEvents;
|
return logInteractiveAuthenticationSuccessEvents;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setLogInteractiveAuthenticationSuccessEvents(
|
public void setLogInteractiveAuthenticationSuccessEvents(
|
||||||
boolean logInteractiveAuthenticationSuccessEvents) {
|
boolean logInteractiveAuthenticationSuccessEvents) {
|
||||||
this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents;
|
this.logInteractiveAuthenticationSuccessEvents = logInteractiveAuthenticationSuccessEvents;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,7 +20,6 @@ import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
@ -88,7 +87,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
|
||||||
return findAttributesSpecifiedAgainst(method, targetClass);
|
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);
|
RegisteredMethod registeredMethod = new RegisteredMethod(method, clazz);
|
||||||
if (methodMap.containsKey(registeredMethod)) {
|
if (methodMap.containsKey(registeredMethod)) {
|
||||||
return (List<ConfigAttribute>) methodMap.get(registeredMethod);
|
return (List<ConfigAttribute>) methodMap.get(registeredMethod);
|
||||||
|
@ -118,7 +117,7 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
|
||||||
Assert.hasText(methodName, "Method not found for '" + name + "'");
|
Assert.hasText(methodName, "Method not found for '" + name + "'");
|
||||||
|
|
||||||
String typeName = name.substring(0, lastDotIndex);
|
String typeName = name.substring(0, lastDotIndex);
|
||||||
Class type = ClassUtils.resolveClassName(typeName, this.beanClassLoader);
|
Class<?> type = ClassUtils.resolveClassName(typeName, this.beanClassLoader);
|
||||||
|
|
||||||
addSecureMethod(type, methodName, attr);
|
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 mappedName mapped method name, which the javaType has declared or inherited
|
||||||
* @param attr required authorities associated with the method
|
* @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;
|
String name = javaType.getName() + '.' + mappedName;
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
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
|
* 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
|
* 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);
|
RegisteredMethod key = new RegisteredMethod(method, javaType);
|
||||||
|
|
||||||
if (methodMap.containsKey(key)) {
|
if (methodMap.containsKey(key)) {
|
||||||
|
@ -255,9 +254,9 @@ public class MapBasedMethodDefinitionSource extends AbstractFallbackMethodDefini
|
||||||
*/
|
*/
|
||||||
private class RegisteredMethod {
|
private class RegisteredMethod {
|
||||||
private Method method;
|
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(method, "Method required");
|
||||||
Assert.notNull(registeredJavaType, "Registered Java Type required");
|
Assert.notNull(registeredJavaType, "Registered Java Type required");
|
||||||
this.method = method;
|
this.method = method;
|
||||||
|
|
|
@ -15,23 +15,18 @@
|
||||||
|
|
||||||
package org.springframework.security.intercept.method;
|
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.beans.PropertyEditorSupport;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.LinkedHashMap;
|
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$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class MethodDefinitionSourceEditor extends PropertyEditorSupport {
|
public class MethodDefinitionSourceEditor extends PropertyEditorSupport {
|
||||||
//~ Static fields/initializers =====================================================================================
|
|
||||||
|
|
||||||
private static final Log logger = LogFactory.getLog(MethodDefinitionSourceEditor.class);
|
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public void setAsText(String s) throws IllegalArgumentException {
|
public void setAsText(String s) throws IllegalArgumentException {
|
||||||
if ((s == null) || "".equals(s)) {
|
if ((s == null) || "".equals(s)) {
|
||||||
setValue(new MapBasedMethodDefinitionSource());
|
setValue(new MapBasedMethodDefinitionSource());
|
||||||
|
@ -63,7 +55,7 @@ public class MethodDefinitionSourceEditor extends PropertyEditorSupport {
|
||||||
Properties props = (Properties) propertiesEditor.getValue();
|
Properties props = (Properties) propertiesEditor.getValue();
|
||||||
|
|
||||||
// Now we have properties, process each one individually
|
// 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();) {
|
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
|
||||||
String name = (String) iter.next();
|
String name = (String) iter.next();
|
||||||
|
|
|
@ -2,7 +2,6 @@ package org.springframework.security.intercept.method;
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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
|
* 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
|
* those pointcuts. Where a match is found, the matching method will be registered with the
|
||||||
* {@link MapBasedMethodDefinitionSource}.
|
* {@link MapBasedMethodDefinitionSource}.
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* It is very important to understand that only the <b>first</b> pointcut that matches a given
|
* 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
|
* 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.
|
* as a <tt>LinkedHashMap</tt>, because their order is very important.
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* Note also that only beans defined in the Spring application context will be examined by this
|
* Note also that only beans defined in the Spring application context will be examined by this
|
||||||
* class.
|
* class.
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <p>
|
* <p>
|
||||||
* Because this class registers method security metadata with {@link MapBasedMethodDefinitionSource},
|
* Because this class registers method security metadata with {@link MapBasedMethodDefinitionSource},
|
||||||
* normal Spring Security capabilities such as {@link MethodDefinitionSourceAdvisor} can be used.
|
* 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
|
* It does not matter the fact the method metadata was originally obtained from an AspectJ pointcut
|
||||||
* expression evaluation.
|
* expression evaluation.
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @verion $Id$
|
* @verion $Id$
|
||||||
|
@ -58,7 +50,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||||
|
|
||||||
private static final Log logger = LogFactory.getLog(ProtectPointcutPostProcessor.class);
|
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 MapBasedMethodDefinitionSource mapBasedMethodDefinitionSource;
|
||||||
private PointcutParser parser;
|
private PointcutParser parser;
|
||||||
|
|
||||||
|
@ -66,18 +58,18 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||||
Assert.notNull(mapBasedMethodDefinitionSource, "MapBasedMethodDefinitionSource to populate is required");
|
Assert.notNull(mapBasedMethodDefinitionSource, "MapBasedMethodDefinitionSource to populate is required");
|
||||||
this.mapBasedMethodDefinitionSource = mapBasedMethodDefinitionSource;
|
this.mapBasedMethodDefinitionSource = mapBasedMethodDefinitionSource;
|
||||||
|
|
||||||
// Setup AspectJ pointcut expression parser
|
// Set up AspectJ pointcut expression parser
|
||||||
Set supportedPrimitives = new HashSet();
|
Set<PointcutPrimitive> supportedPrimitives = new HashSet<PointcutPrimitive>(3);
|
||||||
supportedPrimitives.add(PointcutPrimitive.EXECUTION);
|
supportedPrimitives.add(PointcutPrimitive.EXECUTION);
|
||||||
supportedPrimitives.add(PointcutPrimitive.ARGS);
|
supportedPrimitives.add(PointcutPrimitive.ARGS);
|
||||||
supportedPrimitives.add(PointcutPrimitive.REFERENCE);
|
supportedPrimitives.add(PointcutPrimitive.REFERENCE);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.THIS);
|
// supportedPrimitives.add(PointcutPrimitive.THIS);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.TARGET);
|
// supportedPrimitives.add(PointcutPrimitive.TARGET);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.WITHIN);
|
// supportedPrimitives.add(PointcutPrimitive.WITHIN);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION);
|
// supportedPrimitives.add(PointcutPrimitive.AT_ANNOTATION);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN);
|
// supportedPrimitives.add(PointcutPrimitive.AT_WITHIN);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.AT_ARGS);
|
// supportedPrimitives.add(PointcutPrimitive.AT_ARGS);
|
||||||
// supportedPrimitives.add(PointcutPrimitive.AT_TARGET);
|
// supportedPrimitives.add(PointcutPrimitive.AT_TARGET);
|
||||||
parser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives);
|
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
|
// Check to see if any of those methods are compatible with our pointcut expressions
|
||||||
for (int i = 0; i < methods.length; i++) {
|
for (int i = 0; i < methods.length; i++) {
|
||||||
Iterator iter = pointcutMap.keySet().iterator();
|
for (String ex : pointcutMap.keySet()) {
|
||||||
while (iter.hasNext()) {
|
|
||||||
String ex = iter.next().toString();
|
|
||||||
|
|
||||||
// Parse the presented AspectJ pointcut expression
|
// Parse the presented AspectJ pointcut expression
|
||||||
PointcutExpression expression = parser.parsePointcutExpression(ex);
|
PointcutExpression expression = parser.parsePointcutExpression(ex);
|
||||||
|
|
||||||
|
@ -114,7 +103,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||||
return bean;
|
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
|
// Determine if the presented AspectJ pointcut expression matches this method
|
||||||
boolean matches = expression.matchesMethodExecution(method).alwaysMatches();
|
boolean matches = expression.matchesMethodExecution(method).alwaysMatches();
|
||||||
|
|
||||||
|
@ -134,9 +123,7 @@ public final class ProtectPointcutPostProcessor implements BeanPostProcessor {
|
||||||
|
|
||||||
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
|
public void setPointcutMap(Map<String, List<ConfigAttribute>> map) {
|
||||||
Assert.notEmpty(map);
|
Assert.notEmpty(map);
|
||||||
Iterator i = map.keySet().iterator();
|
for (String expression : map.keySet()) {
|
||||||
while (i.hasNext()) {
|
|
||||||
String expression = i.next().toString();
|
|
||||||
List<ConfigAttribute> value = map.get(expression);
|
List<ConfigAttribute> value = map.get(expression);
|
||||||
addPointcut(expression, value);
|
addPointcut(expression, value);
|
||||||
}
|
}
|
||||||
|
|
|
@ -115,6 +115,7 @@ public class MethodDefinitionSourceAdvisor extends AbstractPointcutAdvisor imple
|
||||||
//~ Inner Classes ==================================================================================================
|
//~ Inner Classes ==================================================================================================
|
||||||
|
|
||||||
class MethodDefinitionSourcePointcut extends StaticMethodMatcherPointcut {
|
class MethodDefinitionSourcePointcut extends StaticMethodMatcherPointcut {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public boolean matches(Method m, Class targetClass) {
|
public boolean matches(Method m, Class targetClass) {
|
||||||
return attributeSource.getAttributes(m, targetClass) != null;
|
return attributeSource.getAttributes(m, targetClass) != null;
|
||||||
}
|
}
|
||||||
|
|
|
@ -49,21 +49,21 @@ public class RequestKey {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (method == null) {
|
if (method == null) {
|
||||||
return key.method == null;
|
return key.method == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return method.equals(key.method);
|
return method.equals(key.method);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
StringBuffer sb = new StringBuffer(url.length() + 7);
|
StringBuffer sb = new StringBuffer(url.length() + 7);
|
||||||
sb.append("[");
|
sb.append("[");
|
||||||
if (method != null) {
|
if (method != null) {
|
||||||
sb.append(method).append(",");
|
sb.append(method).append(",");
|
||||||
}
|
}
|
||||||
sb.append(url);
|
sb.append(url);
|
||||||
sb.append("]");
|
sb.append("]");
|
||||||
|
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -29,8 +29,8 @@ import org.apache.commons.logging.LogFactory;
|
||||||
import javax.naming.directory.SearchControls;
|
import javax.naming.directory.SearchControls;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
|
@ -181,7 +181,7 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
|
||||||
|
|
||||||
Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
|
Set<GrantedAuthority> roles = getGroupMembershipRoles(userDn, username);
|
||||||
|
|
||||||
Set extraRoles = getAdditionalRoles(user, username);
|
Set<GrantedAuthority> extraRoles = getAdditionalRoles(user, username);
|
||||||
|
|
||||||
if (extraRoles != null) {
|
if (extraRoles != null) {
|
||||||
roles.addAll(extraRoles);
|
roles.addAll(extraRoles);
|
||||||
|
@ -198,28 +198,25 @@ public class DefaultLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
|
||||||
}
|
}
|
||||||
|
|
||||||
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
|
public Set<GrantedAuthority> getGroupMembershipRoles(String userDn, String username) {
|
||||||
Set authorities = new HashSet();
|
|
||||||
|
|
||||||
if (getGroupSearchBase() == null) {
|
if (getGroupSearchBase() == null) {
|
||||||
return authorities;
|
return Collections.emptySet();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
|
logger.debug("Searching for roles for user '" + username + "', DN = " + "'" + userDn + "', with filter "
|
||||||
+ groupSearchFilter + " in search base '" + getGroupSearchBase() + "'");
|
+ groupSearchFilter + " in search base '" + getGroupSearchBase() + "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
Set userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
|
Set<String> userRoles = ldapTemplate.searchForSingleAttributeValues(getGroupSearchBase(), groupSearchFilter,
|
||||||
new String[]{userDn, username}, groupRoleAttribute);
|
new String[]{userDn, username}, groupRoleAttribute);
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("Roles from search: " + userRoles);
|
logger.debug("Roles from search: " + userRoles);
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator it = userRoles.iterator();
|
for (String role : userRoles) {
|
||||||
|
|
||||||
while (it.hasNext()) {
|
|
||||||
String role = (String) it.next();
|
|
||||||
|
|
||||||
if (convertToUpperCase) {
|
if (convertToUpperCase) {
|
||||||
role = role.toUpperCase();
|
role = role.toUpperCase();
|
||||||
|
|
|
@ -155,18 +155,18 @@ public class FilterBasedLdapUserSearch implements LdapUserSearch {
|
||||||
searchControls.setTimeLimit(searchTimeLimit);
|
searchControls.setTimeLimit(searchTimeLimit);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Specifies the attributes that will be returned as part of the search.
|
* Specifies the attributes that will be returned as part of the search.
|
||||||
*<p>
|
*<p>
|
||||||
* null indicates that all attributes will be returned.
|
* null indicates that all attributes will be returned.
|
||||||
* An empty array indicates no attributes are returned.
|
* An empty array indicates no attributes are returned.
|
||||||
*
|
*
|
||||||
* @param attrs An array of attribute names identifying the attributes that
|
* @param attrs An array of attribute names identifying the attributes that
|
||||||
* will be returned. Can be null.
|
* will be returned. Can be null.
|
||||||
*/
|
*/
|
||||||
public void setReturningAttributes(String[] attrs) {
|
public void setReturningAttributes(String[] attrs) {
|
||||||
searchControls.setReturningAttributes(attrs);
|
searchControls.setReturningAttributes(attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
|
|
|
@ -81,7 +81,7 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements
|
||||||
return auth;
|
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;
|
boolean addedToken = false;
|
||||||
|
|
||||||
if (applyAnonymousForThisRequest(request)) {
|
if (applyAnonymousForThisRequest(request)) {
|
||||||
|
@ -109,11 +109,11 @@ public class AnonymousProcessingFilter extends SpringSecurityFilter implements
|
||||||
SecurityContextHolder.getContext().setAuthentication(null);
|
SecurityContextHolder.getContext().setAuthentication(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return FilterChainOrder.ANONYMOUS_FILTER;
|
return FilterChainOrder.ANONYMOUS_FILTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return key;
|
return key;
|
||||||
|
|
|
@ -50,7 +50,7 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication
|
||||||
|
|
||||||
protected void additionalAuthenticationChecks(UserDetails userDetails,
|
protected void additionalAuthenticationChecks(UserDetails userDetails,
|
||||||
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
|
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
|
||||||
Object salt = null;
|
Object salt = null;
|
||||||
|
|
||||||
if (this.saltSource != null) {
|
if (this.saltSource != null) {
|
||||||
salt = this.saltSource.getSalt(userDetails);
|
salt = this.saltSource.getSalt(userDetails);
|
||||||
|
@ -143,6 +143,6 @@ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthentication
|
||||||
*/
|
*/
|
||||||
public void setIncludeDetailsObject(boolean includeDetailsObject) {
|
public void setIncludeDetailsObject(boolean includeDetailsObject) {
|
||||||
this.includeDetailsObject = includeDetailsObject;
|
this.includeDetailsObject = includeDetailsObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,160 +20,160 @@ package org.springframework.security.providers.encoding;
|
||||||
* @author Alan Stewart
|
* @author Alan Stewart
|
||||||
*/
|
*/
|
||||||
class Md4 {
|
class Md4 {
|
||||||
private static final int BLOCK_SIZE = 64;
|
private static final int BLOCK_SIZE = 64;
|
||||||
private static final int HASH_SIZE = 16;
|
private static final int HASH_SIZE = 16;
|
||||||
private final byte[] buffer = new byte[BLOCK_SIZE];
|
private final byte[] buffer = new byte[BLOCK_SIZE];
|
||||||
private int bufferOffset;
|
private int bufferOffset;
|
||||||
private long byteCount;
|
private long byteCount;
|
||||||
private int[] state = new int[4];
|
private int[] state = new int[4];
|
||||||
private int[] tmp = new int[16];
|
private int[] tmp = new int[16];
|
||||||
|
|
||||||
Md4() {
|
Md4() {
|
||||||
reset();
|
reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void reset() {
|
public void reset() {
|
||||||
bufferOffset = 0;
|
bufferOffset = 0;
|
||||||
byteCount = 0;
|
byteCount = 0;
|
||||||
state[0] = 0x67452301;
|
state[0] = 0x67452301;
|
||||||
state[1] = 0xEFCDAB89;
|
state[1] = 0xEFCDAB89;
|
||||||
state[2] = 0x98BADCFE;
|
state[2] = 0x98BADCFE;
|
||||||
state[3] = 0x10325476;
|
state[3] = 0x10325476;
|
||||||
}
|
}
|
||||||
|
|
||||||
public byte[] digest() {
|
public byte[] digest() {
|
||||||
byte[] resBuf = new byte[HASH_SIZE];
|
byte[] resBuf = new byte[HASH_SIZE];
|
||||||
digest(resBuf, 0, HASH_SIZE);
|
digest(resBuf, 0, HASH_SIZE);
|
||||||
return resBuf;
|
return resBuf;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void digest(byte[] buffer, int off) {
|
private void digest(byte[] buffer, int off) {
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
for (int j = 0; j < 4; j++) {
|
for (int j = 0; j < 4; j++) {
|
||||||
buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j));
|
buffer[off + (i * 4 + j)] = (byte) (state[i] >>> (8 * j));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void digest(byte[] buffer, int offset, int len) {
|
private void digest(byte[] buffer, int offset, int len) {
|
||||||
this.buffer[this.bufferOffset++] = (byte) 0x80;
|
this.buffer[this.bufferOffset++] = (byte) 0x80;
|
||||||
int lenOfBitLen = 8;
|
int lenOfBitLen = 8;
|
||||||
int C = BLOCK_SIZE - lenOfBitLen;
|
int C = BLOCK_SIZE - lenOfBitLen;
|
||||||
if (this.bufferOffset > C) {
|
if (this.bufferOffset > C) {
|
||||||
while (this.bufferOffset < BLOCK_SIZE) {
|
while (this.bufferOffset < BLOCK_SIZE) {
|
||||||
this.buffer[this.bufferOffset++] = (byte) 0x00;
|
this.buffer[this.bufferOffset++] = (byte) 0x00;
|
||||||
}
|
}
|
||||||
update(this.buffer, 0);
|
update(this.buffer, 0);
|
||||||
this.bufferOffset = 0;
|
this.bufferOffset = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
while (this.bufferOffset < C) {
|
while (this.bufferOffset < C) {
|
||||||
this.buffer[this.bufferOffset++] = (byte) 0x00;
|
this.buffer[this.bufferOffset++] = (byte) 0x00;
|
||||||
}
|
}
|
||||||
|
|
||||||
long bitCount = byteCount * 8;
|
long bitCount = byteCount * 8;
|
||||||
for (int i = 0; i < 64; i += 8) {
|
for (int i = 0; i < 64; i += 8) {
|
||||||
this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i));
|
this.buffer[this.bufferOffset++] = (byte) (bitCount >>> (i));
|
||||||
}
|
}
|
||||||
|
|
||||||
update(this.buffer, 0);
|
update(this.buffer, 0);
|
||||||
digest(buffer, offset);
|
digest(buffer, offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void update(byte[] input, int offset, int length) {
|
public void update(byte[] input, int offset, int length) {
|
||||||
byteCount += length;
|
byteCount += length;
|
||||||
int todo;
|
int todo;
|
||||||
while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) {
|
while (length >= (todo = BLOCK_SIZE - this.bufferOffset)) {
|
||||||
System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo);
|
System.arraycopy(input, offset, this.buffer, this.bufferOffset, todo);
|
||||||
update(this.buffer, 0);
|
update(this.buffer, 0);
|
||||||
length -= todo;
|
length -= todo;
|
||||||
offset += todo;
|
offset += todo;
|
||||||
this.bufferOffset = 0;
|
this.bufferOffset = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
System.arraycopy(input, offset, this.buffer, this.bufferOffset, length);
|
System.arraycopy(input, offset, this.buffer, this.bufferOffset, length);
|
||||||
bufferOffset += length;
|
bufferOffset += length;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void update(byte[] block, int offset) {
|
private void update(byte[] block, int offset) {
|
||||||
for (int i = 0; i < 16; i++) {
|
for (int i = 0; i < 16; i++) {
|
||||||
tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24;
|
tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16 | (block[offset++] & 0xFF) << 24;
|
||||||
}
|
}
|
||||||
|
|
||||||
int A = state[0];
|
int A = state[0];
|
||||||
int B = state[1];
|
int B = state[1];
|
||||||
int C = state[2];
|
int C = state[2];
|
||||||
int D = state[3];
|
int D = state[3];
|
||||||
|
|
||||||
A = FF(A, B, C, D, tmp[0], 3);
|
A = FF(A, B, C, D, tmp[0], 3);
|
||||||
D = FF(D, A, B, C, tmp[1], 7);
|
D = FF(D, A, B, C, tmp[1], 7);
|
||||||
C = FF(C, D, A, B, tmp[2], 11);
|
C = FF(C, D, A, B, tmp[2], 11);
|
||||||
B = FF(B, C, D, A, tmp[3], 19);
|
B = FF(B, C, D, A, tmp[3], 19);
|
||||||
A = FF(A, B, C, D, tmp[4], 3);
|
A = FF(A, B, C, D, tmp[4], 3);
|
||||||
D = FF(D, A, B, C, tmp[5], 7);
|
D = FF(D, A, B, C, tmp[5], 7);
|
||||||
C = FF(C, D, A, B, tmp[6], 11);
|
C = FF(C, D, A, B, tmp[6], 11);
|
||||||
B = FF(B, C, D, A, tmp[7], 19);
|
B = FF(B, C, D, A, tmp[7], 19);
|
||||||
A = FF(A, B, C, D, tmp[8], 3);
|
A = FF(A, B, C, D, tmp[8], 3);
|
||||||
D = FF(D, A, B, C, tmp[9], 7);
|
D = FF(D, A, B, C, tmp[9], 7);
|
||||||
C = FF(C, D, A, B, tmp[10], 11);
|
C = FF(C, D, A, B, tmp[10], 11);
|
||||||
B = FF(B, C, D, A, tmp[11], 19);
|
B = FF(B, C, D, A, tmp[11], 19);
|
||||||
A = FF(A, B, C, D, tmp[12], 3);
|
A = FF(A, B, C, D, tmp[12], 3);
|
||||||
D = FF(D, A, B, C, tmp[13], 7);
|
D = FF(D, A, B, C, tmp[13], 7);
|
||||||
C = FF(C, D, A, B, tmp[14], 11);
|
C = FF(C, D, A, B, tmp[14], 11);
|
||||||
B = FF(B, C, D, A, tmp[15], 19);
|
B = FF(B, C, D, A, tmp[15], 19);
|
||||||
|
|
||||||
A = GG(A, B, C, D, tmp[0], 3);
|
A = GG(A, B, C, D, tmp[0], 3);
|
||||||
D = GG(D, A, B, C, tmp[4], 5);
|
D = GG(D, A, B, C, tmp[4], 5);
|
||||||
C = GG(C, D, A, B, tmp[8], 9);
|
C = GG(C, D, A, B, tmp[8], 9);
|
||||||
B = GG(B, C, D, A, tmp[12], 13);
|
B = GG(B, C, D, A, tmp[12], 13);
|
||||||
A = GG(A, B, C, D, tmp[1], 3);
|
A = GG(A, B, C, D, tmp[1], 3);
|
||||||
D = GG(D, A, B, C, tmp[5], 5);
|
D = GG(D, A, B, C, tmp[5], 5);
|
||||||
C = GG(C, D, A, B, tmp[9], 9);
|
C = GG(C, D, A, B, tmp[9], 9);
|
||||||
B = GG(B, C, D, A, tmp[13], 13);
|
B = GG(B, C, D, A, tmp[13], 13);
|
||||||
A = GG(A, B, C, D, tmp[2], 3);
|
A = GG(A, B, C, D, tmp[2], 3);
|
||||||
D = GG(D, A, B, C, tmp[6], 5);
|
D = GG(D, A, B, C, tmp[6], 5);
|
||||||
C = GG(C, D, A, B, tmp[10], 9);
|
C = GG(C, D, A, B, tmp[10], 9);
|
||||||
B = GG(B, C, D, A, tmp[14], 13);
|
B = GG(B, C, D, A, tmp[14], 13);
|
||||||
A = GG(A, B, C, D, tmp[3], 3);
|
A = GG(A, B, C, D, tmp[3], 3);
|
||||||
D = GG(D, A, B, C, tmp[7], 5);
|
D = GG(D, A, B, C, tmp[7], 5);
|
||||||
C = GG(C, D, A, B, tmp[11], 9);
|
C = GG(C, D, A, B, tmp[11], 9);
|
||||||
B = GG(B, C, D, A, tmp[15], 13);
|
B = GG(B, C, D, A, tmp[15], 13);
|
||||||
|
|
||||||
A = HH(A, B, C, D, tmp[0], 3);
|
A = HH(A, B, C, D, tmp[0], 3);
|
||||||
D = HH(D, A, B, C, tmp[8], 9);
|
D = HH(D, A, B, C, tmp[8], 9);
|
||||||
C = HH(C, D, A, B, tmp[4], 11);
|
C = HH(C, D, A, B, tmp[4], 11);
|
||||||
B = HH(B, C, D, A, tmp[12], 15);
|
B = HH(B, C, D, A, tmp[12], 15);
|
||||||
A = HH(A, B, C, D, tmp[2], 3);
|
A = HH(A, B, C, D, tmp[2], 3);
|
||||||
D = HH(D, A, B, C, tmp[10], 9);
|
D = HH(D, A, B, C, tmp[10], 9);
|
||||||
C = HH(C, D, A, B, tmp[6], 11);
|
C = HH(C, D, A, B, tmp[6], 11);
|
||||||
B = HH(B, C, D, A, tmp[14], 15);
|
B = HH(B, C, D, A, tmp[14], 15);
|
||||||
A = HH(A, B, C, D, tmp[1], 3);
|
A = HH(A, B, C, D, tmp[1], 3);
|
||||||
D = HH(D, A, B, C, tmp[9], 9);
|
D = HH(D, A, B, C, tmp[9], 9);
|
||||||
C = HH(C, D, A, B, tmp[5], 11);
|
C = HH(C, D, A, B, tmp[5], 11);
|
||||||
B = HH(B, C, D, A, tmp[13], 15);
|
B = HH(B, C, D, A, tmp[13], 15);
|
||||||
A = HH(A, B, C, D, tmp[3], 3);
|
A = HH(A, B, C, D, tmp[3], 3);
|
||||||
D = HH(D, A, B, C, tmp[11], 9);
|
D = HH(D, A, B, C, tmp[11], 9);
|
||||||
C = HH(C, D, A, B, tmp[7], 11);
|
C = HH(C, D, A, B, tmp[7], 11);
|
||||||
B = HH(B, C, D, A, tmp[15], 15);
|
B = HH(B, C, D, A, tmp[15], 15);
|
||||||
|
|
||||||
state[0] += A;
|
state[0] += A;
|
||||||
state[1] += B;
|
state[1] += B;
|
||||||
state[2] += C;
|
state[2] += C;
|
||||||
state[3] += D;
|
state[3] += D;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int FF(int a, int b, int c, int d, int x, int s) {
|
private int FF(int a, int b, int c, int d, int x, int s) {
|
||||||
int t = a + ((b & c) | (~b & d)) + x;
|
int t = a + ((b & c) | (~b & d)) + x;
|
||||||
return t << s | t >>> (32 - s);
|
return t << s | t >>> (32 - s);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int GG(int a, int b, int c, int d, int x, int 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;
|
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
|
||||||
return t << s | t >>> (32 - s);
|
return t << s | t >>> (32 - s);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int HH(int a, int b, int c, int d, int x, int s) {
|
private int HH(int a, int b, int c, int d, int x, int s) {
|
||||||
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
|
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
|
||||||
return t << s | t >>> (32 - s);
|
return t << s | t >>> (32 - s);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -36,52 +36,52 @@ public class Md4PasswordEncoder extends BaseDigestPasswordEncoder {
|
||||||
//~ Methods ========================================================================================================
|
//~ 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.
|
* before encoding.
|
||||||
*
|
*
|
||||||
* @param rawPass The plain text password
|
* @param rawPass The plain text password
|
||||||
* @param salt The salt to sprinkle
|
* @param salt The salt to sprinkle
|
||||||
* @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
|
* @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
|
||||||
*/
|
*/
|
||||||
public String encodePassword(String rawPass, Object salt) {
|
public String encodePassword(String rawPass, Object salt) {
|
||||||
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
|
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
|
||||||
|
|
||||||
byte[] passBytes;
|
byte[] passBytes;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
passBytes = saltedPass.getBytes("UTF-8");
|
passBytes = saltedPass.getBytes("UTF-8");
|
||||||
} catch (UnsupportedEncodingException e) {
|
} catch (UnsupportedEncodingException e) {
|
||||||
throw new IllegalStateException("UTF-8 not supported!");
|
throw new IllegalStateException("UTF-8 not supported!");
|
||||||
}
|
}
|
||||||
|
|
||||||
Md4 md4 = new Md4();
|
Md4 md4 = new Md4();
|
||||||
md4.update(passBytes, 0, passBytes.length);
|
md4.update(passBytes, 0, passBytes.length);
|
||||||
|
|
||||||
byte[] resBuf = md4.digest();
|
byte[] resBuf = md4.digest();
|
||||||
|
|
||||||
if (getEncodeHashAsBase64()) {
|
if (getEncodeHashAsBase64()) {
|
||||||
return new String(Base64.encodeBase64(resBuf));
|
return new String(Base64.encodeBase64(resBuf));
|
||||||
} else {
|
} else {
|
||||||
return new String(Hex.encodeHex(resBuf));
|
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.
|
* encoding that value.
|
||||||
*
|
*
|
||||||
* @param encPass previously encoded password
|
* @param encPass previously encoded password
|
||||||
* @param rawPass plain text password
|
* @param rawPass plain text password
|
||||||
* @param salt salt to mix into password
|
* @param salt salt to mix into password
|
||||||
* @return true or false
|
* @return true or false
|
||||||
*/
|
*/
|
||||||
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
|
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
|
||||||
String pass1 = "" + encPass;
|
String pass1 = "" + encPass;
|
||||||
String pass2 = encodePassword(rawPass, salt);
|
String pass2 = encodePassword(rawPass, salt);
|
||||||
return pass1.equals(pass2);
|
return pass1.equals(pass2);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getAlgorithm() {
|
public String getAlgorithm() {
|
||||||
return "MD4";
|
return "MD4";
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -74,12 +74,12 @@ public class MessageDigestPasswordEncoder extends BaseDigestPasswordEncoder {
|
||||||
MessageDigest messageDigest = getMessageDigest();
|
MessageDigest messageDigest = getMessageDigest();
|
||||||
|
|
||||||
byte[] digest;
|
byte[] digest;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
|
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
|
||||||
} catch (UnsupportedEncodingException e) {
|
} catch (UnsupportedEncodingException e) {
|
||||||
throw new IllegalStateException("UTF-8 not supported!");
|
throw new IllegalStateException("UTF-8 not supported!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (getEncodeHashAsBase64()) {
|
if (getEncodeHashAsBase64()) {
|
||||||
return new String(Base64.encodeBase64(digest));
|
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
|
* The AuthorityGranter interface is used to map a given principal to role names.
|
||||||
* names.
|
* <p>
|
||||||
*
|
|
||||||
* <P>
|
|
||||||
* If a Windows NT login module were to be used from JAAS, an AuthrityGranter
|
* 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
|
* implementation could be created to map a NT Group Principal to a ROLE_USER
|
||||||
* role for instance. <br>
|
* role for instance.
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author Ray Krueger
|
* @author Ray Krueger
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
@ -40,13 +37,14 @@ public interface AuthorityGranter {
|
||||||
* The grant method is called for each principal returned from the LoginContext subject. If the
|
* 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
|
* 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
|
* 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
|
* The set may contain any object as all objects in the returned set will be passed to the JaasGrantedAuthority
|
||||||
* constructor using toString().
|
* constructor using toString().
|
||||||
*
|
*
|
||||||
* @param principal One of the principals from the LoginContext.getSubect().getPrincipals() method.
|
* @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;
|
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.io.IOException;
|
||||||
|
|
||||||
import java.security.Principal;
|
import java.security.Principal;
|
||||||
import java.security.Security;
|
import java.security.Security;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import javax.security.auth.callback.Callback;
|
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.LoginContext;
|
||||||
import javax.security.auth.login.LoginException;
|
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.
|
* 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
|
* only throws a AuthenticationServiceException, with the message of the LoginException that will be
|
||||||
* thrown, should the loginContext.login() method fail.
|
* thrown, should the loginContext.login() method fail.
|
||||||
*/
|
*/
|
||||||
public Authentication authenticate(Authentication auth)
|
public Authentication authenticate(Authentication auth) throws AuthenticationException {
|
||||||
throws AuthenticationException {
|
if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
|
||||||
if (auth instanceof UsernamePasswordAuthenticationToken) {
|
return null;
|
||||||
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
|
}
|
||||||
|
|
||||||
try {
|
UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;
|
||||||
//Create the LoginContext object, and pass our InternallCallbackHandler
|
Set<GrantedAuthority> authorities;
|
||||||
LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));
|
|
||||||
|
|
||||||
//Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
|
try {
|
||||||
loginContext.login();
|
// 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.
|
// Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
|
||||||
Set<GrantedAuthority> authorities = new HashSet();
|
loginContext.login();
|
||||||
|
|
||||||
if (request.getAuthorities() != null) {
|
// Create a set to hold the authorities, and add any that have already been applied.
|
||||||
authorities.addAll(request.getAuthorities());
|
authorities = new HashSet<GrantedAuthority>();
|
||||||
}
|
|
||||||
|
|
||||||
//get the subject principals and pass them to each of the AuthorityGranters
|
if (request.getAuthorities() != null) {
|
||||||
Set principals = loginContext.getSubject().getPrincipals();
|
authorities.addAll(request.getAuthorities());
|
||||||
|
}
|
||||||
|
|
||||||
for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
|
// Get the subject principals and pass them to each of the AuthorityGranters
|
||||||
Principal principal = (Principal) iterator.next();
|
Set<Principal> principals = loginContext.getSubject().getPrincipals();
|
||||||
|
|
||||||
for (int i = 0; i < authorityGranters.length; i++) {
|
for (Principal principal : principals) {
|
||||||
AuthorityGranter granter = authorityGranters[i];
|
for (int i = 0; i < authorityGranters.length; i++) {
|
||||||
Set roles = granter.grant(principal);
|
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 the granter doesn't wish to grant any authorities, it should return null.
|
||||||
if ((roles != null) && !roles.isEmpty()) {
|
if ((roles != null) && !roles.isEmpty()) {
|
||||||
for (Iterator roleIterator = roles.iterator(); roleIterator.hasNext();) {
|
for (String role : roles) {
|
||||||
String role = roleIterator.next().toString();
|
authorities.add(new JaasGrantedAuthority(role, principal));
|
||||||
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
|
* 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
|
* @param event
|
||||||
*/
|
*/
|
||||||
protected void handleLogout(HttpSessionDestroyedEvent event) {
|
protected void handleLogout(HttpSessionDestroyedEvent event) {
|
||||||
SecurityContext context = (SecurityContext)
|
SecurityContext context = (SecurityContext)
|
||||||
event.getSession().getAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY);
|
event.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
|
||||||
|
|
||||||
if (context == null) {
|
if (context == null) {
|
||||||
log.debug("The destroyed session has no SecurityContext");
|
log.debug("The destroyed session has no SecurityContext");
|
||||||
|
|
|
@ -15,6 +15,8 @@
|
||||||
|
|
||||||
package org.springframework.security.providers.jaas;
|
package org.springframework.security.providers.jaas;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.springframework.security.GrantedAuthority;
|
import org.springframework.security.GrantedAuthority;
|
||||||
|
|
||||||
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
||||||
|
@ -40,8 +42,8 @@ public class JaasAuthenticationToken extends UsernamePasswordAuthenticationToken
|
||||||
this.loginContext = loginContext;
|
this.loginContext = loginContext;
|
||||||
}
|
}
|
||||||
|
|
||||||
public JaasAuthenticationToken(Object principal, Object credentials, GrantedAuthority[] authorities,
|
public JaasAuthenticationToken(Object principal, Object credentials, List<GrantedAuthority> authorities,
|
||||||
LoginContext loginContext) {
|
LoginContext loginContext) {
|
||||||
super(principal, credentials, authorities);
|
super(principal, credentials, authorities);
|
||||||
this.loginContext = loginContext;
|
this.loginContext = loginContext;
|
||||||
}
|
}
|
||||||
|
|
|
@ -32,16 +32,18 @@ import javax.security.auth.spi.LoginModule;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An implementation of {@link LoginModule} that uses a Spring Security {@link
|
* An implementation of {@link LoginModule} that uses a Spring Security {@link
|
||||||
* org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.<p>This LoginModule
|
* org.springframework.security.context.SecurityContext SecurityContext} to provide authentication.
|
||||||
* provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not really be used in
|
* <p>
|
||||||
* conjunction with it.</p>
|
* This LoginModule provides opposite functionality to the {@link JaasAuthenticationProvider} API, and should not
|
||||||
* <p>The {@link JaasAuthenticationProvider} allows Spring Security to authenticate against Jaas.</p>
|
* really be used in conjunction with it.
|
||||||
* <p>The SecurityContextLoginModule allows a Jaas based application to authenticate against Spring Security.
|
* <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
|
* If there is no Authentication in the {@link SecurityContextHolder} the login() method will throw a LoginException
|
||||||
* by default.
|
* by default. This functionality can be changed with the <tt>ignoreMissingAuthentication</tt> option by setting it
|
||||||
* This functionality can be changed with the <tt>ignoreMissingAuthentication</tt> option by setting it to "true".
|
* to "true". Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false
|
||||||
* Setting ignoreMissingAuthentication=true will tell the SecurityContextLoginModule to simply return false and be
|
* and be ignored if the authentication is null.
|
||||||
* ignored if the authentication is null.</p>
|
|
||||||
*
|
*
|
||||||
* @author Brian Moseley
|
* @author Brian Moseley
|
||||||
* @author Ray Krueger
|
* @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>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.
|
* <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 callbackHandler is ignored
|
||||||
* @param sharedState is ignored
|
* @param sharedState is ignored
|
||||||
* @param options are ignored
|
* @param options are ignored
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
|
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
|
||||||
this.subject = subject;
|
this.subject = subject;
|
||||||
|
|
||||||
|
|
|
@ -15,6 +15,11 @@
|
||||||
|
|
||||||
package org.springframework.security.providers.ldap.authenticator;
|
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.Authentication;
|
||||||
import org.springframework.security.BadCredentialsException;
|
import org.springframework.security.BadCredentialsException;
|
||||||
import org.springframework.security.ldap.LdapUtils;
|
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.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.providers.encoding.PasswordEncoder;
|
import org.springframework.security.providers.encoding.PasswordEncoder;
|
||||||
import org.springframework.security.userdetails.UsernameNotFoundException;
|
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.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
|
* 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 username = authentication.getName();
|
||||||
String password = (String)authentication.getCredentials();
|
String password = (String)authentication.getCredentials();
|
||||||
|
|
||||||
Iterator dns = getUserDns(username).iterator();
|
|
||||||
|
|
||||||
SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
|
SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
|
||||||
|
|
||||||
while (dns.hasNext() && user == null) {
|
for (String userDn : getUserDns(username)) {
|
||||||
final String userDn = (String) dns.next();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
|
user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
|
||||||
} catch (NameNotFoundException ignore) {
|
} catch (NameNotFoundException ignore) {
|
||||||
}
|
}
|
||||||
|
if (user != null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user == null && getUserSearch() != null) {
|
if (user == null && getUserSearch() != null) {
|
||||||
|
|
|
@ -1,21 +1,17 @@
|
||||||
package org.springframework.security.providers.preauth;
|
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.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.beans.factory.InitializingBean;
|
||||||
import org.springframework.core.Ordered;
|
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;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -87,8 +83,7 @@ public class PreAuthenticatedAuthenticationProvider implements AuthenticationPro
|
||||||
userDetailsChecker.check(ud);
|
userDetailsChecker.check(ud);
|
||||||
|
|
||||||
PreAuthenticatedAuthenticationToken result =
|
PreAuthenticatedAuthenticationToken result =
|
||||||
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(),
|
new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities());
|
||||||
ud.getAuthorities().toArray(new GrantedAuthority[0]));
|
|
||||||
result.setDetails(authentication.getDetails());
|
result.setDetails(authentication.getDetails());
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|
|
@ -29,11 +29,12 @@ public interface RemoteAuthenticationManager {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attempts to authenticate the remote client using the presented username and password. If authentication
|
* 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
|
* is successful, an array of <code>GrantedAuthority[]</code> objects will be returned.
|
||||||
* maximise remoting protocol compatibility, a design decision was taken to operate with minimal arguments and
|
* <p>
|
||||||
* return only the minimal amount of information required for remote clients to enable/disable relevant user
|
* In order to maximise remoting protocol compatibility, a design decision was taken to operate with minimal
|
||||||
* interface commands etc. There is nothing preventing users from implementing their own equivalent package that
|
* arguments and return only the minimal amount of information required for remote clients to enable/disable
|
||||||
* works with more complex object types.</p>
|
* 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 username the username the remote client wishes to authenticate with.
|
||||||
* @param password the password 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;
|
package org.springframework.security.providers.rcp;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
import org.springframework.security.Authentication;
|
import org.springframework.security.Authentication;
|
||||||
import org.springframework.security.AuthenticationException;
|
import org.springframework.security.AuthenticationException;
|
||||||
import org.springframework.security.GrantedAuthority;
|
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
|
* Client-side object which queries a {@link RemoteAuthenticationManager} to validate an authentication request.
|
||||||
* new <code>Authentication</code> object is created by this class comprising the request <code>Authentication</code>
|
* <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
|
* object's <code>principal</code>, <code>credentials</code> and the <code>GrantedAuthority</code>[]s returned by the
|
||||||
* <code>RemoteAuthenticationManager</code>.</p>
|
* <code>RemoteAuthenticationManager</code>.
|
||||||
* <p>The <code>RemoteAuthenticationManager</code> should not require any special username or password setting on
|
* <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
|
* 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
|
* 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
|
* <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 ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.notNull(this.remoteAuthenticationManager, "remoteAuthenticationManager is mandatory");
|
Assert.notNull(this.remoteAuthenticationManager, "remoteAuthenticationManager is mandatory");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -60,7 +64,7 @@ public class RemoteAuthenticationProvider implements AuthenticationProvider, Ini
|
||||||
String password = authentication.getCredentials().toString();
|
String password = authentication.getCredentials().toString();
|
||||||
GrantedAuthority[] authorities = remoteAuthenticationManager.attemptAuthentication(username, password);
|
GrantedAuthority[] authorities = remoteAuthenticationManager.attemptAuthentication(username, password);
|
||||||
|
|
||||||
return new UsernamePasswordAuthenticationToken(username, password, authorities);
|
return new UsernamePasswordAuthenticationToken(username, password, Arrays.asList(authorities));
|
||||||
}
|
}
|
||||||
|
|
||||||
public RemoteAuthenticationManager getRemoteAuthenticationManager() {
|
public RemoteAuthenticationManager getRemoteAuthenticationManager() {
|
||||||
|
|
|
@ -15,36 +15,25 @@
|
||||||
|
|
||||||
package org.springframework.security.providers.rememberme;
|
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.beans.factory.InitializingBean;
|
||||||
|
|
||||||
import org.springframework.context.MessageSource;
|
import org.springframework.context.MessageSource;
|
||||||
import org.springframework.context.MessageSourceAware;
|
import org.springframework.context.MessageSourceAware;
|
||||||
import org.springframework.context.support.MessageSourceAccessor;
|
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;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An {@link AuthenticationProvider} implementation that validates {@link
|
* An {@link AuthenticationProvider} implementation that validates {@link RememberMeAuthenticationToken}s.
|
||||||
* org.springframework.security.providers.rememberme.RememberMeAuthenticationToken}s.<p>To be successfully validated, the
|
* <p>
|
||||||
* {@link org.springframework.security.providers.rememberme.RememberMeAuthenticationToken#getKeyHash()} must match this class'
|
* To be successfully validated, the {@link RememberMeAuthenticationToken#getKeyHash()} must match this class'
|
||||||
* {@link #getKey()}.</p>
|
* {@link #getKey()}.
|
||||||
*/
|
*/
|
||||||
public class RememberMeAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
|
public class RememberMeAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
|
||||||
//~ Static fields/initializers =====================================================================================
|
|
||||||
|
|
||||||
private static final Log logger = LogFactory.getLog(RememberMeAuthenticationProvider.class);
|
|
||||||
|
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||||
|
@ -52,13 +41,12 @@ public class RememberMeAuthenticationProvider implements AuthenticationProvider,
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.hasLength(key);
|
Assert.hasLength(key);
|
||||||
Assert.notNull(this.messages, "A message source must be set");
|
Assert.notNull(this.messages, "A message source must be set");
|
||||||
}
|
}
|
||||||
|
|
||||||
public Authentication authenticate(Authentication authentication)
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
throws AuthenticationException {
|
|
||||||
if (!supports(authentication.getClass())) {
|
if (!supports(authentication.getClass())) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,6 +39,9 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken i
|
||||||
|
|
||||||
//~ Constructors ===================================================================================================
|
//~ Constructors ===================================================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated
|
||||||
|
*/
|
||||||
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
|
public RememberMeAuthenticationToken(String key, Object principal, GrantedAuthority[] authorities) {
|
||||||
this(key, principal, Arrays.asList(authorities));
|
this(key, principal, Arrays.asList(authorities));
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,7 +46,7 @@ public class RunAsImplAuthenticationProvider implements InitializingBean, Authen
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ 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");
|
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.io.IOException;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
@ -52,35 +53,26 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
|
||||||
|
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
private List channelProcessors;
|
private List<ChannelProcessor> channelProcessors;
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
checkIfValidList(this.channelProcessors);
|
Assert.notEmpty(channelProcessors, "A list of ChannelProcessors is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void checkIfValidList(List listToCheck) {
|
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
|
||||||
Assert.notEmpty(listToCheck, "A list of ChannelProcessors is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
Iterator<ConfigAttribute> attrs = config.iterator();
|
||||||
throws IOException, ServletException {
|
|
||||||
|
|
||||||
Iterator attrs = config.iterator();
|
|
||||||
|
|
||||||
while (attrs.hasNext()) {
|
while (attrs.hasNext()) {
|
||||||
ConfigAttribute attribute = (ConfigAttribute) attrs.next();
|
ConfigAttribute attribute = attrs.next();
|
||||||
if (ANY_CHANNEL.equals(attribute.getAttribute())) {
|
if (ANY_CHANNEL.equals(attribute.getAttribute())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator iter = this.channelProcessors.iterator();
|
for (ChannelProcessor processor : channelProcessors) {
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
|
||||||
ChannelProcessor processor = (ChannelProcessor) iter.next();
|
|
||||||
|
|
||||||
processor.decide(invocation, config);
|
processor.decide(invocation, config);
|
||||||
|
|
||||||
if (invocation.getResponse().isCommitted()) {
|
if (invocation.getResponse().isCommitted()) {
|
||||||
|
@ -89,22 +81,20 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected List getChannelProcessors() {
|
protected List<ChannelProcessor> getChannelProcessors() {
|
||||||
return this.channelProcessors;
|
return this.channelProcessors;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setChannelProcessors(List newList) {
|
@SuppressWarnings("cast")
|
||||||
checkIfValidList(newList);
|
public void setChannelProcessors(List<?> newList) {
|
||||||
|
Assert.notEmpty(newList, "A list of ChannelProcessors is required");
|
||||||
|
channelProcessors = new ArrayList<ChannelProcessor>(newList.size());
|
||||||
|
|
||||||
Iterator iter = newList.iterator();
|
for (Object currentObject : newList) {
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
|
||||||
Object currentObject = iter.next();
|
|
||||||
Assert.isInstanceOf(ChannelProcessor.class, currentObject, "ChannelProcessor " +
|
Assert.isInstanceOf(ChannelProcessor.class, currentObject, "ChannelProcessor " +
|
||||||
currentObject.getClass().getName() + " must implement ChannelProcessor");
|
currentObject.getClass().getName() + " must implement ChannelProcessor");
|
||||||
|
channelProcessors.add((ChannelProcessor)currentObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.channelProcessors = newList;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean supports(ConfigAttribute attribute) {
|
public boolean supports(ConfigAttribute attribute) {
|
||||||
|
@ -112,11 +102,7 @@ public class ChannelDecisionManagerImpl implements ChannelDecisionManager, Initi
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator iter = this.channelProcessors.iterator();
|
for (ChannelProcessor processor : channelProcessors) {
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
|
||||||
ChannelProcessor processor = (ChannelProcessor) iter.next();
|
|
||||||
|
|
||||||
if (processor.supports(attribute)) {
|
if (processor.supports(attribute)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,17 +26,12 @@ import javax.servlet.ServletException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decides whether a web channel meets a specific security condition.
|
* Decides whether a web channel meets a specific security condition.
|
||||||
*
|
* <p>
|
||||||
* <P>
|
* <code>ChannelProcessor</code> implementations are iterated by the {@link ChannelDecisionManagerImpl}.
|
||||||
* <code>ChannelProcessor</code> implementations are iterated by the {@link
|
* <p>
|
||||||
* ChannelDecisionManagerImpl}.
|
|
||||||
* </p>
|
|
||||||
*
|
|
||||||
* <P>
|
|
||||||
* If an implementation has an issue with the channel security, they should
|
* If an implementation has an issue with the channel security, they should
|
||||||
* take action themselves. The callers of the implementation do not take any
|
* take action themselves. The callers of the implementation do not take any
|
||||||
* action.
|
* action.
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
@ -49,16 +44,16 @@ public interface ChannelProcessor {
|
||||||
* security based on the requested list of <tt>ConfigAttribute</tt>s.
|
* security based on the requested list of <tt>ConfigAttribute</tt>s.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException;
|
||||||
throws IOException, ServletException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates whether this <code>ChannelProcessor</code> is able to process the passed
|
* 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
|
* <code>ConfigAttribute</code>.
|
||||||
* configuration attribute can be consumed by the configured <code>ChannelDecisionManager</code>.</p>
|
* <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
|
* @param attribute a configuration attribute that has been configured against the <tt>ChannelProcessingFilter</tt>.
|
||||||
* <code>ChannelProcessingFilter</code>
|
|
||||||
*
|
*
|
||||||
* @return true if this <code>ChannelProcessor</code> can support the passed configuration attribute
|
* @return true if this <code>ChannelProcessor</code> can support the passed configuration attribute
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -15,29 +15,26 @@
|
||||||
|
|
||||||
package org.springframework.security.securechannel;
|
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.io.IOException;
|
||||||
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import javax.servlet.ServletException;
|
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>
|
* 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,
|
* <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
|
* <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
|
* is present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
|
||||||
* RetryWithHttpEntryPoint}.</p>
|
* RetryWithHttpEntryPoint}.
|
||||||
* <P>The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.</p>
|
* <p>
|
||||||
|
* The default <code>insecureKeyword</code> is <code>REQUIRES_INSECURE_CHANNEL</code>.
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
@ -55,17 +52,12 @@ public class InsecureChannelProcessor implements InitializingBean, ChannelProces
|
||||||
Assert.notNull(entryPoint, "entryPoint required");
|
Assert.notNull(entryPoint, "entryPoint required");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
|
||||||
throws IOException, ServletException {
|
|
||||||
if ((invocation == null) || (config == null)) {
|
if ((invocation == null) || (config == null)) {
|
||||||
throw new IllegalArgumentException("Nulls cannot be provided");
|
throw new IllegalArgumentException("Nulls cannot be provided");
|
||||||
}
|
}
|
||||||
|
|
||||||
Iterator iter = config.iterator();
|
for (ConfigAttribute attribute : config) {
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
|
||||||
ConfigAttribute attribute = (ConfigAttribute) iter.next();
|
|
||||||
|
|
||||||
if (supports(attribute)) {
|
if (supports(attribute)) {
|
||||||
if (invocation.getHttpRequest().isSecure()) {
|
if (invocation.getHttpRequest().isSecure()) {
|
||||||
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
|
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
|
||||||
|
|
|
@ -15,29 +15,26 @@
|
||||||
|
|
||||||
package org.springframework.security.securechannel;
|
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.io.IOException;
|
||||||
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import javax.servlet.ServletException;
|
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>
|
* 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,
|
* <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
|
* <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
|
* is not present, the configured <code>ChannelEntryPoint</code> is called. By default the entry point is {@link
|
||||||
* RetryWithHttpsEntryPoint}.</p>
|
* RetryWithHttpsEntryPoint}.
|
||||||
* <P>The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.</p>
|
* <p>
|
||||||
|
* The default <code>secureKeyword</code> is <code>REQUIRES_SECURE_CHANNEL</code>.
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
|
@ -55,15 +52,10 @@ public class SecureChannelProcessor implements InitializingBean, ChannelProcesso
|
||||||
Assert.notNull(entryPoint, "entryPoint required");
|
Assert.notNull(entryPoint, "entryPoint required");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void decide(FilterInvocation invocation, List<ConfigAttribute> config)
|
public void decide(FilterInvocation invocation, List<ConfigAttribute> config) throws IOException, ServletException {
|
||||||
throws IOException, ServletException {
|
|
||||||
Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided");
|
Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided");
|
||||||
|
|
||||||
Iterator iter = config.iterator();
|
for (ConfigAttribute attribute : config) {
|
||||||
|
|
||||||
while (iter.hasNext()) {
|
|
||||||
ConfigAttribute attribute = (ConfigAttribute) iter.next();
|
|
||||||
|
|
||||||
if (supports(attribute)) {
|
if (supports(attribute)) {
|
||||||
if (!invocation.getHttpRequest().isSecure()) {
|
if (!invocation.getHttpRequest().isSecure()) {
|
||||||
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
|
entryPoint.commence(invocation.getRequest(), invocation.getResponse());
|
||||||
|
|
|
@ -11,49 +11,49 @@ import org.springframework.util.Assert;
|
||||||
* @since 2.0.1
|
* @since 2.0.1
|
||||||
*/
|
*/
|
||||||
public class DefaultToken implements Token {
|
public class DefaultToken implements Token {
|
||||||
private String key;
|
private String key;
|
||||||
private long keyCreationTime;
|
private long keyCreationTime;
|
||||||
private String extendedInformation;
|
private String extendedInformation;
|
||||||
|
|
||||||
public DefaultToken(String key, long keyCreationTime, String extendedInformation) {
|
public DefaultToken(String key, long keyCreationTime, String extendedInformation) {
|
||||||
Assert.hasText(key, "Key required");
|
Assert.hasText(key, "Key required");
|
||||||
Assert.notNull(extendedInformation, "Extended information cannot be null");
|
Assert.notNull(extendedInformation, "Extended information cannot be null");
|
||||||
this.key = key;
|
this.key = key;
|
||||||
this.keyCreationTime = keyCreationTime;
|
this.keyCreationTime = keyCreationTime;
|
||||||
this.extendedInformation = extendedInformation;
|
this.extendedInformation = extendedInformation;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getKey() {
|
public String getKey() {
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getKeyCreationTime() {
|
public long getKeyCreationTime() {
|
||||||
return keyCreationTime;
|
return keyCreationTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getExtendedInformation() {
|
public String getExtendedInformation() {
|
||||||
return extendedInformation;
|
return extendedInformation;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean equals(Object obj) {
|
public boolean equals(Object obj) {
|
||||||
if (obj != null && obj instanceof DefaultToken) {
|
if (obj != null && obj instanceof DefaultToken) {
|
||||||
DefaultToken rhs = (DefaultToken) obj;
|
DefaultToken rhs = (DefaultToken) obj;
|
||||||
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation);
|
return this.key.equals(rhs.key) && this.keyCreationTime == rhs.keyCreationTime && this.extendedInformation.equals(rhs.extendedInformation);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
int code = 979;
|
int code = 979;
|
||||||
code = code * key.hashCode();
|
code = code * key.hashCode();
|
||||||
code = code * new Long(keyCreationTime).hashCode();
|
code = code * new Long(keyCreationTime).hashCode();
|
||||||
code = code * extendedInformation.hashCode();
|
code = code * extendedInformation.hashCode();
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "DefaultToken[key=" + new String(key) + "; creation=" + new Date(keyCreationTime) + "; extended=" + extendedInformation + "]";
|
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 {
|
public class KeyBasedPersistenceTokenService implements TokenService, InitializingBean {
|
||||||
private int pseudoRandomNumberBits = 256;
|
private int pseudoRandomNumberBits = 256;
|
||||||
private String serverSecret;
|
private String serverSecret;
|
||||||
private Integer serverInteger;
|
private Integer serverInteger;
|
||||||
private SecureRandom secureRandom;
|
private SecureRandom secureRandom;
|
||||||
|
|
||||||
public Token allocateToken(String extendedInformation) {
|
public Token allocateToken(String extendedInformation) {
|
||||||
Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)");
|
Assert.notNull(extendedInformation, "Must provided non-null extendedInformation (but it can be empty)");
|
||||||
long creationTime = new Date().getTime();
|
long creationTime = new Date().getTime();
|
||||||
String serverSecret = computeServerSecretApplicableAt(creationTime);
|
String serverSecret = computeServerSecretApplicableAt(creationTime);
|
||||||
String pseudoRandomNumber = generatePseudoRandomNumber();
|
String pseudoRandomNumber = generatePseudoRandomNumber();
|
||||||
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation;
|
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInformation;
|
||||||
|
|
||||||
// Compute key
|
// Compute key
|
||||||
String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
|
String sha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
|
||||||
String keyPayload = content + ":" + sha512Hex;
|
String keyPayload = content + ":" + sha512Hex;
|
||||||
String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload)));
|
String key = convertToString(Base64.encodeBase64(convertToBytes(keyPayload)));
|
||||||
|
|
||||||
return new DefaultToken(key, creationTime, extendedInformation);
|
return new DefaultToken(key, creationTime, extendedInformation);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Token verifyToken(String key) {
|
public Token verifyToken(String key) {
|
||||||
if (key == null || "".equals(key)) {
|
if (key == null || "".equals(key)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":");
|
String[] tokens = StringUtils.delimitedListToStringArray(convertToString(Base64.decodeBase64(convertToBytes(key))), ":");
|
||||||
Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length);
|
Assert.isTrue(tokens.length >= 4, "Expected 4 or more tokens but found " + tokens.length);
|
||||||
|
|
||||||
long creationTime;
|
long creationTime;
|
||||||
try {
|
try {
|
||||||
creationTime = Long.decode(tokens[0]).longValue();
|
creationTime = Long.decode(tokens[0]).longValue();
|
||||||
} catch (NumberFormatException nfe) {
|
} catch (NumberFormatException nfe) {
|
||||||
throw new IllegalArgumentException("Expected number but found " + tokens[0]);
|
throw new IllegalArgumentException("Expected number but found " + tokens[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
String serverSecret = computeServerSecretApplicableAt(creationTime);
|
String serverSecret = computeServerSecretApplicableAt(creationTime);
|
||||||
String pseudoRandomNumber = tokens[1];
|
String pseudoRandomNumber = tokens[1];
|
||||||
|
|
||||||
// Permit extendedInfo to itself contain ":" characters
|
// Permit extendedInfo to itself contain ":" characters
|
||||||
StringBuffer extendedInfo = new StringBuffer();
|
StringBuffer extendedInfo = new StringBuffer();
|
||||||
for (int i = 2; i < tokens.length-1; i++) {
|
for (int i = 2; i < tokens.length-1; i++) {
|
||||||
if (i > 2) {
|
if (i > 2) {
|
||||||
extendedInfo.append(":");
|
extendedInfo.append(":");
|
||||||
}
|
}
|
||||||
extendedInfo.append(tokens[i]);
|
extendedInfo.append(tokens[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
String sha1Hex = tokens[tokens.length-1];
|
String sha1Hex = tokens[tokens.length-1];
|
||||||
|
|
||||||
// Verification
|
// Verification
|
||||||
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
|
String content = new Long(creationTime).toString() + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
|
||||||
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
|
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
|
||||||
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
|
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
|
||||||
|
|
||||||
return new DefaultToken(key, creationTime, extendedInfo.toString());
|
return new DefaultToken(key, creationTime, extendedInfo.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
private byte[] convertToBytes(String input) {
|
private byte[] convertToBytes(String input) {
|
||||||
try {
|
try {
|
||||||
return input.getBytes("UTF-8");
|
return input.getBytes("UTF-8");
|
||||||
} catch (UnsupportedEncodingException e) {
|
} catch (UnsupportedEncodingException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String convertToString(byte[] bytes) {
|
private String convertToString(byte[] bytes) {
|
||||||
try {
|
try {
|
||||||
return new String(bytes, "UTF-8");
|
return new String(bytes, "UTF-8");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return a pseduo random number (hex encoded)
|
* @return a pseduo random number (hex encoded)
|
||||||
*/
|
*/
|
||||||
private String generatePseudoRandomNumber() {
|
private String generatePseudoRandomNumber() {
|
||||||
byte[] randomizedBits = new byte[pseudoRandomNumberBits];
|
byte[] randomizedBits = new byte[pseudoRandomNumberBits];
|
||||||
secureRandom.nextBytes(randomizedBits);
|
secureRandom.nextBytes(randomizedBits);
|
||||||
return new String(Hex.encodeHex(randomizedBits));
|
return new String(Hex.encodeHex(randomizedBits));
|
||||||
}
|
}
|
||||||
|
|
||||||
private String computeServerSecretApplicableAt(long time) {
|
private String computeServerSecretApplicableAt(long time) {
|
||||||
return serverSecret + ":" + new Long(time % serverInteger.intValue()).intValue();
|
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)
|
* @param serverSecret the new secret, which can contain a ":" if desired (never being sent to the client)
|
||||||
*/
|
*/
|
||||||
public void setServerSecret(String serverSecret) {
|
public void setServerSecret(String serverSecret) {
|
||||||
this.serverSecret = serverSecret;
|
this.serverSecret = serverSecret;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setSecureRandom(SecureRandom secureRandom) {
|
public void setSecureRandom(SecureRandom secureRandom) {
|
||||||
this.secureRandom = secureRandom;
|
this.secureRandom = secureRandom;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256)
|
* @param pseudoRandomNumberBits changes the number of bits issued (must be >= 0; defaults to 256)
|
||||||
*/
|
*/
|
||||||
public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) {
|
public void setPseudoRandomNumberBits(int pseudoRandomNumberBits) {
|
||||||
Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size");
|
Assert.isTrue(pseudoRandomNumberBits >= 0, "Must have a positive pseudo random number bit size");
|
||||||
this.pseudoRandomNumberBits = pseudoRandomNumberBits;
|
this.pseudoRandomNumberBits = pseudoRandomNumberBits;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setServerInteger(Integer serverInteger) {
|
public void setServerInteger(Integer serverInteger) {
|
||||||
this.serverInteger = serverInteger;
|
this.serverInteger = serverInteger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.hasText(serverSecret, "Server secret required");
|
Assert.hasText(serverSecret, "Server secret required");
|
||||||
Assert.notNull(serverInteger, "Server integer required");
|
Assert.notNull(serverInteger, "Server integer required");
|
||||||
Assert.notNull(secureRandom, "SecureRandom instance required");
|
Assert.notNull(secureRandom, "SecureRandom instance required");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,60 +10,59 @@ import org.springframework.util.FileCopyUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a {@link SecureRandom} instance.
|
* Creates a {@link SecureRandom} instance.
|
||||||
*
|
*
|
||||||
* @author Ben Alex
|
* @author Ben Alex
|
||||||
* @since 2.0.1
|
* @since 2.0.1
|
||||||
*
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class SecureRandomFactoryBean implements FactoryBean {
|
public class SecureRandomFactoryBean implements FactoryBean<SecureRandom> {
|
||||||
|
|
||||||
private String algorithm = "SHA1PRNG";
|
private String algorithm = "SHA1PRNG";
|
||||||
private Resource seed;
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Class getObjectType() {
|
public SecureRandom getObject() throws Exception {
|
||||||
return SecureRandom.class;
|
SecureRandom rnd = SecureRandom.getInstance(algorithm);
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isSingleton() {
|
if (seed != null) {
|
||||||
return false;
|
// 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;
|
||||||
* 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
public Class<SecureRandom> getObjectType() {
|
||||||
* Allows the user to specify a resource which will act as a seed for the {@link SecureRandom}
|
return SecureRandom.class;
|
||||||
* 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
|
public boolean isSingleton() {
|
||||||
* set a seed using this method (it never reduces randomness).
|
return false;
|
||||||
*
|
}
|
||||||
* @param seed to use, or <code>null</code> if no additional seeding is needed
|
|
||||||
*/
|
/**
|
||||||
public void setSeed(Resource seed) {
|
* Allows the Pseudo Random Number Generator (PRNG) algorithm to be nominated. Defaults to "SHA1PRNG".
|
||||||
this.seed = seed;
|
*
|
||||||
}
|
* @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
|
* @since 2.0.1
|
||||||
*/
|
*/
|
||||||
public interface Token {
|
public interface Token {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtains the randomised, secure key assigned to this token. Presentation of this token to
|
* 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
|
* {@link TokenService} will always return a <code>Token</code> that is equal to the original
|
||||||
* <code>Token</code> issued for that key.
|
* <code>Token</code> issued for that key.
|
||||||
*
|
*
|
||||||
* @return a key with appropriate randomness and security.
|
* @return a key with appropriate randomness and security.
|
||||||
*/
|
*/
|
||||||
String getKey();
|
String getKey();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The time the token key was initially created is available from this method. Note that a given
|
* 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
|
* 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.
|
* 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()).
|
* @return the time this token key was created, in the same format as specified by {@link Date#getTime()).
|
||||||
*/
|
*/
|
||||||
long getKeyCreationTime();
|
long getKeyCreationTime();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtains the extended information associated within the token, which was presented when the token
|
* Obtains the extended information associated within the token, which was presented when the token
|
||||||
* was first created.
|
* was first created.
|
||||||
*
|
*
|
||||||
* @return the user-specified extended information, if any
|
* @return the user-specified extended information, if any
|
||||||
*/
|
*/
|
||||||
String getExtendedInformation();
|
String getExtendedInformation();
|
||||||
}
|
}
|
||||||
|
|
|
@ -26,21 +26,21 @@ package org.springframework.security.token;
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public interface TokenService {
|
public interface TokenService {
|
||||||
/**
|
/**
|
||||||
* Forces the allocation of a new {@link Token}.
|
* 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)
|
* @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
|
* @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.
|
* by this implementation's {@link #verifyToken(String)} at any future time.
|
||||||
*/
|
*/
|
||||||
Token allocateToken(String extendedInformation);
|
Token allocateToken(String extendedInformation);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Permits verification the <{@link Token#getKey()} was issued by this <code>TokenService</code> and
|
* Permits verification the <{@link Token#getKey()} was issued by this <code>TokenService</code> and
|
||||||
* reconstructs the corresponding <code>Token</code>.
|
* reconstructs the corresponding <code>Token</code>.
|
||||||
*
|
*
|
||||||
* @param key as obtained from {@link Token#getKey()} and created by this implementation
|
* @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>
|
* @return the token, or <code>null</code> if the token was not issued by this <code>TokenService</code>
|
||||||
*/
|
*/
|
||||||
Token verifyToken(String key);
|
Token verifyToken(String key);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,8 +1,6 @@
|
||||||
package org.springframework.security.ui;
|
package org.springframework.security.ui;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.net.URLDecoder;
|
|
||||||
|
|
||||||
import javax.servlet.ServletException;
|
import javax.servlet.ServletException;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
|
@ -174,7 +174,7 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi
|
||||||
chain.doFilter(request, response);
|
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
|
// Only reauthenticate if username doesn't match SecurityContextHolder and user isn't authenticated
|
||||||
// (see SEC-53)
|
// (see SEC-53)
|
||||||
Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
|
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
|
// both of which force re-authentication if the respective header is detected (and in doing so replace
|
||||||
// any existing AnonymousAuthenticationToken). See SEC-610.
|
// any existing AnonymousAuthenticationToken). See SEC-610.
|
||||||
if (existingAuth instanceof AnonymousAuthenticationToken) {
|
if (existingAuth instanceof AnonymousAuthenticationToken) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||||
Authentication authResult) throws IOException {
|
Authentication authResult) throws IOException {
|
||||||
}
|
}
|
||||||
|
@ -242,20 +242,20 @@ public class BasicProcessingFilter extends SpringSecurityFilter implements Initi
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRememberMeServices(RememberMeServices rememberMeServices) {
|
public void setRememberMeServices(RememberMeServices rememberMeServices) {
|
||||||
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
|
Assert.notNull(rememberMeServices, "rememberMeServices cannot be null");
|
||||||
this.rememberMeServices = rememberMeServices;
|
this.rememberMeServices = rememberMeServices;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCredentialsCharset(String credentialsCharset) {
|
public void setCredentialsCharset(String credentialsCharset) {
|
||||||
Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
|
Assert.hasText(credentialsCharset, "credentialsCharset cannot be null or empty");
|
||||||
this.credentialsCharset = credentialsCharset;
|
this.credentialsCharset = credentialsCharset;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String getCredentialsCharset(HttpServletRequest httpRequest) {
|
protected String getCredentialsCharset(HttpServletRequest httpRequest) {
|
||||||
return credentialsCharset;
|
return credentialsCharset;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return FilterChainOrder.BASIC_PROCESSING_FILTER;
|
return FilterChainOrder.BASIC_PROCESSING_FILTER;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -44,8 +44,8 @@ public class BasicProcessingFilterEntryPoint implements AuthenticationEntryPoint
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.hasText(realmName, "realmName must be specified");
|
Assert.hasText(realmName, "realmName must be specified");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
|
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
|
||||||
|
|
|
@ -57,14 +57,14 @@ public class DigestProcessingFilterEntryPoint implements AuthenticationEntryPoin
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return order;
|
return order;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOrder(int order) {
|
public void setOrder(int order) {
|
||||||
this.order = order;
|
this.order = order;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
if ((realmName == null) || "".equals(realmName)) {
|
if ((realmName == null) || "".equals(realmName)) {
|
||||||
throw new IllegalArgumentException("realmName must be specified");
|
throw new IllegalArgumentException("realmName must be specified");
|
||||||
}
|
}
|
||||||
|
|
|
@ -99,7 +99,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec
|
||||||
unsuccessfulAuthentication(request, response, failed);
|
unsuccessfulAuthentication(request, response, failed);
|
||||||
|
|
||||||
if (!continueFilterChainOnUnsuccessfulAuthentication) {
|
if (!continueFilterChainOnUnsuccessfulAuthentication) {
|
||||||
throw failed;
|
throw failed;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -158,7 +158,7 @@ public abstract class AbstractPreAuthenticatedProcessingFilter extends SpringSec
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setContinueFilterChainOnUnsuccessfulAuthentication(boolean shouldContinue) {
|
public void setContinueFilterChainOnUnsuccessfulAuthentication(boolean shouldContinue) {
|
||||||
continueFilterChainOnUnsuccessfulAuthentication = shouldContinue;
|
continueFilterChainOnUnsuccessfulAuthentication = shouldContinue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -4,8 +4,8 @@ import org.springframework.security.AuthenticationException;
|
||||||
|
|
||||||
public class PreAuthenticatedCredentialsNotFoundException extends AuthenticationException {
|
public class PreAuthenticatedCredentialsNotFoundException extends AuthenticationException {
|
||||||
|
|
||||||
public PreAuthenticatedCredentialsNotFoundException(String msg) {
|
public PreAuthenticatedCredentialsNotFoundException(String msg) {
|
||||||
super(msg);
|
super(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,27 +18,27 @@ import org.springframework.security.MutableGrantedAuthoritiesContainer;
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*/
|
*/
|
||||||
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends WebAuthenticationDetails implements
|
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails extends WebAuthenticationDetails implements
|
||||||
MutableGrantedAuthoritiesContainer {
|
MutableGrantedAuthoritiesContainer {
|
||||||
public static final long serialVersionUID = 1L;
|
public static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl();
|
private MutableGrantedAuthoritiesContainer authoritiesContainer = new GrantedAuthoritiesContainerImpl();
|
||||||
|
|
||||||
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) {
|
public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(HttpServletRequest request) {
|
||||||
super(request);
|
super(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<GrantedAuthority> getGrantedAuthorities() {
|
public List<GrantedAuthority> getGrantedAuthorities() {
|
||||||
return authoritiesContainer.getGrantedAuthorities();
|
return authoritiesContainer.getGrantedAuthorities();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
|
public void setGrantedAuthorities(List<GrantedAuthority> authorities) {
|
||||||
this.authoritiesContainer.setGrantedAuthorities(authorities);
|
this.authoritiesContainer.setGrantedAuthorities(authorities);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String toString() {
|
public String toString() {
|
||||||
StringBuffer sb = new StringBuffer();
|
StringBuffer sb = new StringBuffer();
|
||||||
sb.append(super.toString() + "; ");
|
sb.append(super.toString() + "; ");
|
||||||
sb.append(authoritiesContainer);
|
sb.append(authoritiesContainer);
|
||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -38,28 +38,28 @@ import org.springframework.core.Ordered;
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*/
|
*/
|
||||||
public class PreAuthenticatedProcessingFilterEntryPoint implements AuthenticationEntryPoint, Ordered {
|
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.
|
* Always returns a 403 error code to the client.
|
||||||
*/
|
*/
|
||||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
|
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
|
||||||
ServletException {
|
ServletException {
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("Pre-authenticated entry point called. Rejecting access");
|
logger.debug("Pre-authenticated entry point called. Rejecting access");
|
||||||
}
|
}
|
||||||
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
HttpServletResponse httpResponse = (HttpServletResponse) response;
|
||||||
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
|
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return order;
|
return order;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOrder(int i) {
|
public void setOrder(int i) {
|
||||||
order = i;
|
order = i;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,50 +27,50 @@ import org.springframework.util.Assert;
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*/
|
*/
|
||||||
public class RequestHeaderPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
|
public class RequestHeaderPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
|
||||||
private String principalRequestHeader = "SM_USER";
|
private String principalRequestHeader = "SM_USER";
|
||||||
private String credentialsRequestHeader;
|
private String credentialsRequestHeader;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read and returns the header named by <tt>principalRequestHeader</tt> from the request.
|
* Read and returns the header named by <tt>principalRequestHeader</tt> from the request.
|
||||||
*
|
*
|
||||||
* @throws PreAuthenticatedCredentialsNotFoundException if the header is missing
|
* @throws PreAuthenticatedCredentialsNotFoundException if the header is missing
|
||||||
*/
|
*/
|
||||||
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
|
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
|
||||||
String principal = request.getHeader(principalRequestHeader);
|
String principal = request.getHeader(principalRequestHeader);
|
||||||
|
|
||||||
if (principal == null) {
|
if (principal == null) {
|
||||||
throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader
|
throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader
|
||||||
+ " header not found in request.");
|
+ " header not found in request.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return principal;
|
return principal;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Credentials aren't usually applicable, but if a <tt>credentialsRequestHeader</tt> is set, this
|
* 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.
|
* will be read and used as the credentials value. Otherwise a dummy value will be used.
|
||||||
*/
|
*/
|
||||||
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
|
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
|
||||||
if (credentialsRequestHeader != null) {
|
if (credentialsRequestHeader != null) {
|
||||||
String credentials = request.getHeader(credentialsRequestHeader);
|
String credentials = request.getHeader(credentialsRequestHeader);
|
||||||
|
|
||||||
return credentials;
|
return credentials;
|
||||||
}
|
}
|
||||||
|
|
||||||
return "N/A";
|
return "N/A";
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPrincipalRequestHeader(String principalRequestHeader) {
|
public void setPrincipalRequestHeader(String principalRequestHeader) {
|
||||||
Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
|
Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
|
||||||
this.principalRequestHeader = principalRequestHeader;
|
this.principalRequestHeader = principalRequestHeader;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setCredentialsRequestHeader(String credentialsRequestHeader) {
|
public void setCredentialsRequestHeader(String credentialsRequestHeader) {
|
||||||
Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null");
|
Assert.hasText(credentialsRequestHeader, "credentialsRequestHeader must not be empty or null");
|
||||||
this.credentialsRequestHeader = credentialsRequestHeader;
|
this.credentialsRequestHeader = credentialsRequestHeader;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return FilterChainOrder.PRE_AUTH_FILTER;
|
return FilterChainOrder.PRE_AUTH_FILTER;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,10 +15,10 @@ import org.apache.commons.logging.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
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>
|
* <p>
|
||||||
* See Spring Security JIRA SEC-477.
|
* See Spring Security Jira SEC-477.
|
||||||
*
|
*
|
||||||
* @author Ruud Senden
|
* @author Ruud Senden
|
||||||
* @author Stephane Manciot
|
* @author Stephane Manciot
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
|
@ -35,11 +35,11 @@ final class WASSecurityHelper {
|
||||||
private static Method getSecurityName = null;
|
private static Method getSecurityName = null;
|
||||||
|
|
||||||
// SEC-803
|
// SEC-803
|
||||||
private static Class wsCredentialClass = null;
|
private static Class<?> wsCredentialClass = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the security name for the given subject.
|
* Get the security name for the given subject.
|
||||||
*
|
*
|
||||||
* @param subject
|
* @param subject
|
||||||
* The subject for which to retrieve the security name
|
* The subject for which to retrieve the security name
|
||||||
* @return String the security name for the given subject
|
* @return String the security name for the given subject
|
||||||
|
@ -64,7 +64,7 @@ final class WASSecurityHelper {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the current RunAs subject.
|
* Get the current RunAs subject.
|
||||||
*
|
*
|
||||||
* @return Subject the current RunAs subject
|
* @return Subject the current RunAs subject
|
||||||
*/
|
*/
|
||||||
private static final Subject getRunAsSubject() {
|
private static final Subject getRunAsSubject() {
|
||||||
|
@ -75,7 +75,7 @@ final class WASSecurityHelper {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the WebSphere group names for the given subject.
|
* Get the WebSphere group names for the given subject.
|
||||||
*
|
*
|
||||||
* @param subject
|
* @param subject
|
||||||
* The subject for which to retrieve the WebSphere group names
|
* The subject for which to retrieve the WebSphere group names
|
||||||
* @return the WebSphere group names for the given subject
|
* @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.
|
* Get the WebSphere group names for the given security name.
|
||||||
*
|
*
|
||||||
* @param securityName
|
* @param securityName
|
||||||
* The securityname for which to retrieve the WebSphere group names
|
* The securityname for which to retrieve the WebSphere group names
|
||||||
* @return the WebSphere group names for the given security name
|
* @return the WebSphere group names for the given security name
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private static final String[] getWebSphereGroups(final String securityName) {
|
private static final String[] getWebSphereGroups(final String securityName) {
|
||||||
Context ic = null;
|
Context ic = null;
|
||||||
try {
|
try {
|
||||||
|
@ -129,7 +130,7 @@ final class WASSecurityHelper {
|
||||||
public static final String getCurrentUserName() {
|
public static final String getCurrentUserName() {
|
||||||
return getSecurityName(getRunAsSubject());
|
return getSecurityName(getRunAsSubject());
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Object invokeMethod(Method method, Object instance, Object[] args)
|
private static final Object invokeMethod(Method method, Object instance, Object[] args)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
|
@ -148,9 +149,9 @@ final class WASSecurityHelper {
|
||||||
|
|
||||||
private static final Method getMethod(String className, String methodName, String[] parameterTypeNames) {
|
private static final Method getMethod(String className, String methodName, String[] parameterTypeNames) {
|
||||||
try {
|
try {
|
||||||
Class c = Class.forName(className);
|
Class<?> c = Class.forName(className);
|
||||||
final int len = parameterTypeNames.length;
|
final int len = parameterTypeNames.length;
|
||||||
Class[] parameterTypes = new Class[len];
|
Class<?>[] parameterTypes = new Class[len];
|
||||||
for (int i = 0; i < len; i++) {
|
for (int i = 0; i < len; i++) {
|
||||||
parameterTypes[i] = Class.forName(parameterTypeNames[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);
|
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);
|
throw new RuntimeException("Required class"+className+" not found",e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Method getRunAsSubjectMethod() {
|
private static final Method getRunAsSubjectMethod() {
|
||||||
if (getRunAsSubject == null) {
|
if (getRunAsSubject == null) {
|
||||||
|
@ -184,22 +185,22 @@ final class WASSecurityHelper {
|
||||||
}
|
}
|
||||||
return getSecurityName;
|
return getSecurityName;
|
||||||
}
|
}
|
||||||
|
|
||||||
// SEC-803
|
// SEC-803
|
||||||
private static final Class getWSCredentialClass() {
|
private static final Class<?> getWSCredentialClass() {
|
||||||
if (wsCredentialClass == null) {
|
if (wsCredentialClass == null) {
|
||||||
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
|
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
|
||||||
}
|
}
|
||||||
return wsCredentialClass;
|
return wsCredentialClass;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final Class getClass(String className) {
|
private static final Class<?> getClass(String className) {
|
||||||
try {
|
try {
|
||||||
return Class.forName(className);
|
return Class.forName(className);
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
logger.error("Required class " + className + " not found");
|
logger.error("Required class " + className + " not found");
|
||||||
throw new RuntimeException("Required class " + className + " not found",e);
|
throw new RuntimeException("Required class " + className + " not found",e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,78 +19,78 @@ import org.springframework.util.Assert;
|
||||||
* @since 1.0
|
* @since 1.0
|
||||||
*/
|
*/
|
||||||
public class WebSphere2SpringSecurityPropagationInterceptor implements MethodInterceptor {
|
public class WebSphere2SpringSecurityPropagationInterceptor implements MethodInterceptor {
|
||||||
private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class);
|
private static final Log LOG = LogFactory.getLog(WebSphere2SpringSecurityPropagationInterceptor.class);
|
||||||
private AuthenticationManager authenticationManager = null;
|
private AuthenticationManager authenticationManager = null;
|
||||||
private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource();
|
private AuthenticationDetailsSource authenticationDetailsSource = new WebSpherePreAuthenticatedAuthenticationDetailsSource();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authenticate with Spring Security based on WebSphere credentials before proceeding with method
|
* Authenticate with Spring Security based on WebSphere credentials before proceeding with method
|
||||||
* invocation, and clean up the Spring Security Context after method invocation finishes.
|
* invocation, and clean up the Spring Security Context after method invocation finishes.
|
||||||
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
|
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
|
||||||
*/
|
*/
|
||||||
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
|
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
|
||||||
try {
|
try {
|
||||||
LOG.debug("Performing Spring Security authentication with WebSphere credentials");
|
LOG.debug("Performing Spring Security authentication with WebSphere credentials");
|
||||||
authenticateSpringSecurityWithWASCredentials(this);
|
authenticateSpringSecurityWithWASCredentials(this);
|
||||||
LOG.debug("Proceeding with method invocation");
|
LOG.debug("Proceeding with method invocation");
|
||||||
return methodInvocation.proceed();
|
return methodInvocation.proceed();
|
||||||
} finally {
|
} finally {
|
||||||
LOG.debug("Clearing Spring Security security context");
|
LOG.debug("Clearing Spring Security security context");
|
||||||
clearSpringSecurityContext();
|
clearSpringSecurityContext();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve the current WebSphere credentials and authenticate them with Spring Security
|
* Retrieve the current WebSphere credentials and authenticate them with Spring Security
|
||||||
* using the pre-authenticated authentication provider.
|
* using the pre-authenticated authentication provider.
|
||||||
* @param aContext The context to use for building the authentication details.
|
* @param aContext The context to use for building the authentication details.
|
||||||
*/
|
*/
|
||||||
private final void authenticateSpringSecurityWithWASCredentials(Object aContext)
|
private final void authenticateSpringSecurityWithWASCredentials(Object aContext)
|
||||||
{
|
{
|
||||||
Assert.notNull(authenticationManager);
|
Assert.notNull(authenticationManager);
|
||||||
Assert.notNull(authenticationDetailsSource);
|
Assert.notNull(authenticationDetailsSource);
|
||||||
|
|
||||||
String userName = WASSecurityHelper.getCurrentUserName();
|
String userName = WASSecurityHelper.getCurrentUserName();
|
||||||
if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); }
|
if (LOG.isDebugEnabled()) { LOG.debug("Creating authentication request for user "+userName); }
|
||||||
PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null);
|
PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(userName,null);
|
||||||
authRequest.setDetails(authenticationDetailsSource.buildDetails(null));
|
authRequest.setDetails(authenticationDetailsSource.buildDetails(null));
|
||||||
if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); }
|
if (LOG.isDebugEnabled()) { LOG.debug("Authentication request for user "+userName+": "+authRequest); }
|
||||||
Authentication authResponse = authenticationManager.authenticate(authRequest);
|
Authentication authResponse = authenticationManager.authenticate(authRequest);
|
||||||
if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); }
|
if (LOG.isDebugEnabled()) { LOG.debug("Authentication response for user "+userName+": "+authResponse); }
|
||||||
SecurityContextHolder.getContext().setAuthentication(authResponse);
|
SecurityContextHolder.getContext().setAuthentication(authResponse);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear the Spring Security Context
|
* Clear the Spring Security Context
|
||||||
*/
|
*/
|
||||||
private final void clearSpringSecurityContext()
|
private final void clearSpringSecurityContext()
|
||||||
{
|
{
|
||||||
SecurityContextHolder.clearContext();
|
SecurityContextHolder.clearContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return Returns the authenticationManager.
|
* @return Returns the authenticationManager.
|
||||||
*/
|
*/
|
||||||
public AuthenticationManager getAuthenticationManager() {
|
public AuthenticationManager getAuthenticationManager() {
|
||||||
return authenticationManager;
|
return authenticationManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param authenticationManager The authenticationManager to set.
|
* @param authenticationManager The authenticationManager to set.
|
||||||
*/
|
*/
|
||||||
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
|
||||||
this.authenticationManager = authenticationManager;
|
this.authenticationManager = authenticationManager;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* @return Returns the authenticationDetailsSource.
|
* @return Returns the authenticationDetailsSource.
|
||||||
*/
|
*/
|
||||||
public AuthenticationDetailsSource getAuthenticationDetailsSource() {
|
public AuthenticationDetailsSource getAuthenticationDetailsSource() {
|
||||||
return authenticationDetailsSource;
|
return authenticationDetailsSource;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* @param authenticationDetailsSource The authenticationDetailsSource to set.
|
* @param authenticationDetailsSource The authenticationDetailsSource to set.
|
||||||
*/
|
*/
|
||||||
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
|
public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {
|
||||||
this.authenticationDetailsSource = authenticationDetailsSource;
|
this.authenticationDetailsSource = authenticationDetailsSource;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -70,8 +70,7 @@ public class WebSpherePreAuthenticatedAuthenticationDetailsSource extends Authen
|
||||||
List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
|
List<String> webSphereGroups = Arrays.asList(WASSecurityHelper.getGroupsForCurrentUser());
|
||||||
List<GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
|
List<GrantedAuthority> userGas = webSphereGroups2GrantedAuthoritiesMapper.getGrantedAuthorities(webSphereGroups);
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: "
|
logger.debug("WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas);
|
||||||
+ Arrays.asList(userGas));
|
|
||||||
}
|
}
|
||||||
return userGas;
|
return userGas;
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,12 +13,12 @@ import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritie
|
||||||
* @author Ruud Senden
|
* @author Ruud Senden
|
||||||
*/
|
*/
|
||||||
public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource extends WebSpherePreAuthenticatedAuthenticationDetailsSource {
|
public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource extends WebSpherePreAuthenticatedAuthenticationDetailsSource {
|
||||||
/**
|
/**
|
||||||
* Public constructor which overrides the default AuthenticationDetails
|
* Public constructor which overrides the default AuthenticationDetails
|
||||||
* class to be used.
|
* class to be used.
|
||||||
*/
|
*/
|
||||||
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() {
|
public WebSpherePreAuthenticatedWebAuthenticationDetailsSource() {
|
||||||
super();
|
super();
|
||||||
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
|
super.setClazz(PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,16 +8,16 @@ import java.util.Iterator;
|
||||||
import java.util.Map;
|
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
|
* @author Luke Taylor
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
|
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) {
|
public synchronized void createNewToken(PersistentRememberMeToken token) {
|
||||||
PersistentRememberMeToken current = (PersistentRememberMeToken) seriesTokens.get(token.getSeries());
|
PersistentRememberMeToken current = seriesTokens.get(token.getSeries());
|
||||||
|
|
||||||
if (current != null) {
|
if (current != null) {
|
||||||
throw new DataIntegrityViolationException("Series Id '"+ token.getSeries() +"' already exists!");
|
throw new DataIntegrityViolationException("Series Id '"+ token.getSeries() +"' already exists!");
|
||||||
|
@ -41,7 +41,7 @@ public class InMemoryTokenRepositoryImpl implements PersistentTokenRepository {
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void removeUserTokens(String username) {
|
public synchronized void removeUserTokens(String username) {
|
||||||
Iterator series = seriesTokens.keySet().iterator();
|
Iterator<String> series = seriesTokens.keySet().iterator();
|
||||||
|
|
||||||
while (series.hasNext()) {
|
while (series.hasNext()) {
|
||||||
Object seriesId = series.next();
|
Object seriesId = series.next();
|
||||||
|
|
|
@ -48,10 +48,10 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
|
||||||
private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL;
|
private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL;
|
||||||
private boolean createTableOnStartup;
|
private boolean createTableOnStartup;
|
||||||
|
|
||||||
protected MappingSqlQuery tokensBySeriesMapping;
|
private MappingSqlQuery<PersistentRememberMeToken> tokensBySeriesMapping;
|
||||||
protected SqlUpdate insertToken;
|
private SqlUpdate insertToken;
|
||||||
protected SqlUpdate updateToken;
|
private SqlUpdate updateToken;
|
||||||
protected SqlUpdate removeUserTokens;
|
private SqlUpdate removeUserTokens;
|
||||||
|
|
||||||
protected void initDao() {
|
protected void initDao() {
|
||||||
tokensBySeriesMapping = new TokensBySeriesMapping(getDataSource());
|
tokensBySeriesMapping = new TokensBySeriesMapping(getDataSource());
|
||||||
|
@ -111,14 +111,14 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements Persisten
|
||||||
|
|
||||||
//~ Inner Classes ==================================================================================================
|
//~ Inner Classes ==================================================================================================
|
||||||
|
|
||||||
protected class TokensBySeriesMapping extends MappingSqlQuery {
|
private class TokensBySeriesMapping extends MappingSqlQuery<PersistentRememberMeToken> {
|
||||||
protected TokensBySeriesMapping(DataSource ds) {
|
protected TokensBySeriesMapping(DataSource ds) {
|
||||||
super(ds, tokensBySeriesSql);
|
super(ds, tokensBySeriesSql);
|
||||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||||
compile();
|
compile();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
protected PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||||
PersistentRememberMeToken token =
|
PersistentRememberMeToken token =
|
||||||
new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4));
|
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) {
|
public UpdateToken(DataSource ds) {
|
||||||
super(ds, updateTokenSql);
|
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) {
|
public InsertToken(DataSource ds) {
|
||||||
super(ds, insertTokenSql);
|
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) {
|
public RemoveUserTokens(DataSource ds) {
|
||||||
super(ds, removeUserTokensSql);
|
super(ds, removeUserTokensSql);
|
||||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||||
|
|
|
@ -63,9 +63,9 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.notNull(authenticationManager, "authenticationManager must be specified");
|
Assert.notNull(authenticationManager, "authenticationManager must be specified");
|
||||||
Assert.notNull(rememberMeServices, "rememberMeServices must be specified");
|
Assert.notNull(rememberMeServices, "rememberMeServices must be specified");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||||
throws IOException, ServletException {
|
throws IOException, ServletException {
|
||||||
|
@ -76,7 +76,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
|
||||||
if (rememberMeAuth != null) {
|
if (rememberMeAuth != null) {
|
||||||
// Attempt authenticaton via AuthenticationManager
|
// Attempt authenticaton via AuthenticationManager
|
||||||
try {
|
try {
|
||||||
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
|
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
|
||||||
|
|
||||||
// Store to SecurityContextHolder
|
// Store to SecurityContextHolder
|
||||||
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
|
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
|
||||||
|
@ -122,7 +122,7 @@ public class RememberMeProcessingFilter extends SpringSecurityFilter implements
|
||||||
* <tt>autoLogin</tt> method and the <tt>AuthenticationManager</tt>.
|
* <tt>autoLogin</tt> method and the <tt>AuthenticationManager</tt>.
|
||||||
*/
|
*/
|
||||||
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
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.
|
* token is present in the request and <tt>autoLogin</tt> returns null.
|
||||||
*/
|
*/
|
||||||
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
|
||||||
AuthenticationException failed) {
|
AuthenticationException failed) {
|
||||||
}
|
}
|
||||||
|
|
||||||
public RememberMeServices getRememberMeServices() {
|
public RememberMeServices getRememberMeServices() {
|
||||||
|
|
|
@ -26,8 +26,9 @@ import java.util.TimeZone;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <p>Utility class to generate HTTP dates.</p>
|
* Utility class to generate HTTP dates.
|
||||||
* <p>This class is based on code in Apache Tomcat.</p>
|
* <p>
|
||||||
|
* This class is based on code in Apache Tomcat.
|
||||||
*
|
*
|
||||||
* @author Remy Maucherat
|
* @author Remy Maucherat
|
||||||
* @author Andrey Grebnev
|
* @author Andrey Grebnev
|
||||||
|
@ -46,7 +47,7 @@ public class FastHttpDateFormat {
|
||||||
new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
|
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");
|
protected static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");
|
||||||
|
|
||||||
static {
|
static {
|
||||||
|
@ -64,10 +65,10 @@ public class FastHttpDateFormat {
|
||||||
protected static String currentDate = null;
|
protected static String currentDate = null;
|
||||||
|
|
||||||
/** Formatter cache. */
|
/** Formatter cache. */
|
||||||
protected static final HashMap formatCache = new HashMap();
|
protected static final HashMap<Long,String> formatCache = new HashMap<Long,String>();
|
||||||
|
|
||||||
/** Parser cache. */
|
/** Parser cache. */
|
||||||
protected static final HashMap parseCache = new HashMap();
|
protected static final HashMap<String,Long> parseCache = new HashMap<String,Long>();
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
|
@ -84,7 +85,7 @@ public class FastHttpDateFormat {
|
||||||
Long longValue = new Long(value);
|
Long longValue = new Long(value);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
cachedDate = (String) formatCache.get(longValue);
|
cachedDate = formatCache.get(longValue);
|
||||||
} catch (Exception e) {}
|
} catch (Exception e) {}
|
||||||
|
|
||||||
if (cachedDate != null) {
|
if (cachedDate != null) {
|
||||||
|
@ -163,7 +164,7 @@ public class FastHttpDateFormat {
|
||||||
* @param value The string to parse
|
* @param value The string to parse
|
||||||
* @param threadLocalformats Array of formats to use for parsing. If <code>null</code>, HTTP formats are used.
|
* @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) {
|
public static final long parseDate(String value, DateFormat[] threadLocalformats) {
|
||||||
Long cachedDate = null;
|
Long cachedDate = null;
|
||||||
|
@ -205,6 +206,7 @@ public class FastHttpDateFormat {
|
||||||
* @param key Key to be updated
|
* @param key Key to be updated
|
||||||
* @param value New value
|
* @param value New value
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
private static void updateCache(HashMap cache, Object key, Object value) {
|
private static void updateCache(HashMap cache, Object key, Object value) {
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -12,13 +12,13 @@ import org.springframework.security.Authentication;
|
||||||
*/
|
*/
|
||||||
public interface AuthenticationUserDetailsService {
|
public interface AuthenticationUserDetailsService {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param token The pre-authenticated authentication token
|
* @param token The pre-authenticated authentication token
|
||||||
* @return UserDetails for the given authentication token, never null.
|
* @return UserDetails for the given authentication token, never null.
|
||||||
* @throws UsernameNotFoundException
|
* @throws UsernameNotFoundException
|
||||||
* if no user details can be found for the given authentication
|
* if no user details can be found for the given authentication
|
||||||
* token
|
* token
|
||||||
*/
|
*/
|
||||||
UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException;
|
UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException;
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,33 +14,33 @@ import org.springframework.util.Assert;
|
||||||
* @since 2.0
|
* @since 2.0
|
||||||
*/
|
*/
|
||||||
public class UserDetailsByNameServiceWrapper implements AuthenticationUserDetailsService, InitializingBean {
|
public class UserDetailsByNameServiceWrapper implements AuthenticationUserDetailsService, InitializingBean {
|
||||||
private UserDetailsService userDetailsService = null;
|
private UserDetailsService userDetailsService = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether all required properties have been set.
|
* Check whether all required properties have been set.
|
||||||
*
|
*
|
||||||
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
|
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
|
||||||
*/
|
*/
|
||||||
public void afterPropertiesSet() throws Exception {
|
public void afterPropertiesSet() throws Exception {
|
||||||
Assert.notNull(userDetailsService, "UserDetailsService must be set");
|
Assert.notNull(userDetailsService, "UserDetailsService must be set");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the UserDetails object from the wrapped UserDetailsService
|
* Get the UserDetails object from the wrapped UserDetailsService
|
||||||
* implementation
|
* implementation
|
||||||
*/
|
*/
|
||||||
public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException,
|
public UserDetails loadUserDetails(Authentication authentication) throws UsernameNotFoundException,
|
||||||
DataAccessException {
|
DataAccessException {
|
||||||
return userDetailsService.loadUserByUsername(authentication.getName());
|
return userDetailsService.loadUserByUsername(authentication.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the wrapped UserDetailsService implementation
|
* Set the wrapped UserDetailsService implementation
|
||||||
*
|
*
|
||||||
* @param aUserDetailsService
|
* @param aUserDetailsService
|
||||||
* The wrapped UserDetailsService to set
|
* The wrapped UserDetailsService to set
|
||||||
*/
|
*/
|
||||||
public void setUserDetailsService(UserDetailsService aUserDetailsService) {
|
public void setUserDetailsService(UserDetailsService aUserDetailsService) {
|
||||||
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.
|
* Executes the SQL <tt>usersByUsernameQuery</tt> and returns a list of UserDetails objects.
|
||||||
* There should normally only be one matching user.
|
* There should normally only be one matching user.
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
protected List<UserDetails> loadUsersByUsername(String username) {
|
protected List<UserDetails> loadUsersByUsername(String username) {
|
||||||
return getJdbcTemplate().query(usersByUsernameQuery, new String[] {username}, new RowMapper() {
|
return getJdbcTemplate().query(usersByUsernameQuery, new String[] {username}, new RowMapper() {
|
||||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
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
|
* @return a list of GrantedAuthority objects for the user
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
protected List<GrantedAuthority> loadUserAuthorities(String username) {
|
protected List<GrantedAuthority> loadUserAuthorities(String username) {
|
||||||
return getJdbcTemplate().query(authoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
|
return getJdbcTemplate().query(authoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
|
||||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
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
|
* @return a list of GrantedAuthority objects for the user
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
|
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
|
||||||
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
|
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery, new String[] {username}, new RowMapper() {
|
||||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||||
|
|
|
@ -189,7 +189,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||||
|
|
||||||
String username = currentUser.getName();
|
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) {
|
if (authenticationManager != null) {
|
||||||
logger.debug("Reauthenticating user '"+ username + "' for password change request.");
|
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 + "'");
|
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));
|
SecurityContextHolder.getContext().setAuthentication(createNewAuthentication(currentUser, newPassword));
|
||||||
|
|
||||||
|
@ -218,7 +218,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean userExists(String username) {
|
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) {
|
if (users.size() > 1) {
|
||||||
throw new IncorrectResultSizeDataAccessException("More than one user found with name '" + username + "'", 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 " +
|
logger.debug("Creating new group '" + groupName + "' with authorities " +
|
||||||
AuthorityUtils.authorityListToSet(authorities));
|
AuthorityUtils.authorityListToSet(authorities));
|
||||||
|
|
||||||
getJdbcTemplate().update(insertGroupSql, new String[] {groupName});
|
getJdbcTemplate().update(insertGroupSql, new Object[] {groupName});
|
||||||
|
|
||||||
final int groupId = findGroupId(groupName);
|
final int groupId = findGroupId(groupName);
|
||||||
|
|
||||||
|
@ -280,7 +280,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||||
Assert.hasText(oldName);
|
Assert.hasText(oldName);
|
||||||
Assert.hasText(newName);
|
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) {
|
public void addUserToGroup(final String username, final String groupName) {
|
||||||
|
@ -316,6 +316,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa
|
||||||
userCache.removeUserFromCache(username);
|
userCache.removeUserFromCache(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public List<GrantedAuthority> findGroupAuthorities(String groupName) {
|
public List<GrantedAuthority> findGroupAuthorities(String groupName) {
|
||||||
logger.debug("Loading authorities for group '" + groupName + "'");
|
logger.debug("Loading authorities for group '" + groupName + "'");
|
||||||
Assert.hasText(groupName);
|
Assert.hasText(groupName);
|
||||||
|
|
|
@ -29,19 +29,19 @@ import org.springframework.ldap.core.DirContextOperations;
|
||||||
* @version $Id$
|
* @version $Id$
|
||||||
*/
|
*/
|
||||||
public class InetOrgPerson extends Person {
|
public class InetOrgPerson extends Person {
|
||||||
private String carLicense;
|
private String carLicense;
|
||||||
// Person.cn
|
// Person.cn
|
||||||
private String destinationIndicator;
|
private String destinationIndicator;
|
||||||
private String departmentNumber;
|
private String departmentNumber;
|
||||||
// Person.description
|
// Person.description
|
||||||
private String displayName;
|
private String displayName;
|
||||||
private String employeeNumber;
|
private String employeeNumber;
|
||||||
private String homePhone;
|
private String homePhone;
|
||||||
private String homePostalAddress;
|
private String homePostalAddress;
|
||||||
private String initials;
|
private String initials;
|
||||||
private String mail;
|
private String mail;
|
||||||
private String mobile;
|
private String mobile;
|
||||||
private String o;
|
private String o;
|
||||||
private String ou;
|
private String ou;
|
||||||
private String postalAddress;
|
private String postalAddress;
|
||||||
private String postalCode;
|
private String postalCode;
|
||||||
|
@ -49,7 +49,7 @@ public class InetOrgPerson extends Person {
|
||||||
private String street;
|
private String street;
|
||||||
// Person.sn
|
// Person.sn
|
||||||
// Person.telephoneNumber
|
// Person.telephoneNumber
|
||||||
private String title;
|
private String title;
|
||||||
private String uid;
|
private String uid;
|
||||||
|
|
||||||
public String getUid() {
|
public String getUid() {
|
||||||
|
@ -65,7 +65,7 @@ public class InetOrgPerson extends Person {
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getInitials() {
|
public String getInitials() {
|
||||||
return initials;
|
return initials;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDestinationIndicator() {
|
public String getDestinationIndicator() {
|
||||||
|
@ -73,58 +73,58 @@ public class InetOrgPerson extends Person {
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getO() {
|
public String getO() {
|
||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getOu() {
|
public String getOu() {
|
||||||
return ou;
|
return ou;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTitle() {
|
public String getTitle() {
|
||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getCarLicense() {
|
public String getCarLicense() {
|
||||||
return carLicense;
|
return carLicense;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDepartmentNumber() {
|
public String getDepartmentNumber() {
|
||||||
return departmentNumber;
|
return departmentNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getDisplayName() {
|
public String getDisplayName() {
|
||||||
return displayName;
|
return displayName;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getHomePhone() {
|
public String getHomePhone() {
|
||||||
return homePhone;
|
return homePhone;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getRoomNumber() {
|
public String getRoomNumber() {
|
||||||
return roomNumber;
|
return roomNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getHomePostalAddress() {
|
public String getHomePostalAddress() {
|
||||||
return homePostalAddress;
|
return homePostalAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getMobile() {
|
public String getMobile() {
|
||||||
return mobile;
|
return mobile;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPostalAddress() {
|
public String getPostalAddress() {
|
||||||
return postalAddress;
|
return postalAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getPostalCode() {
|
public String getPostalCode() {
|
||||||
return postalCode;
|
return postalCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getStreet() {
|
public String getStreet() {
|
||||||
return street;
|
return street;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void populateContext(DirContextAdapter adapter) {
|
protected void populateContext(DirContextAdapter adapter) {
|
||||||
super.populateContext(adapter);
|
super.populateContext(adapter);
|
||||||
adapter.setAttributeValue("carLicense", carLicense);
|
adapter.setAttributeValue("carLicense", carLicense);
|
||||||
adapter.setAttributeValue("departmentNumber", departmentNumber);
|
adapter.setAttributeValue("departmentNumber", departmentNumber);
|
||||||
|
@ -172,7 +172,7 @@ public class InetOrgPerson extends Person {
|
||||||
setUid(copyMe.getUid());
|
setUid(copyMe.getUid());
|
||||||
}
|
}
|
||||||
|
|
||||||
public Essence(DirContextOperations ctx) {
|
public Essence(DirContextOperations ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
setCarLicense(ctx.getStringAttribute("carLicense"));
|
setCarLicense(ctx.getStringAttribute("carLicense"));
|
||||||
setDepartmentNumber(ctx.getStringAttribute("departmentNumber"));
|
setDepartmentNumber(ctx.getStringAttribute("departmentNumber"));
|
||||||
|
@ -235,8 +235,8 @@ public class InetOrgPerson extends Person {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDepartmentNumber(String departmentNumber) {
|
public void setDepartmentNumber(String departmentNumber) {
|
||||||
((InetOrgPerson) instance).departmentNumber = departmentNumber;
|
((InetOrgPerson) instance).departmentNumber = departmentNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDisplayName(String displayName) {
|
public void setDisplayName(String displayName) {
|
||||||
((InetOrgPerson) instance).displayName = displayName;
|
((InetOrgPerson) instance).displayName = displayName;
|
||||||
|
@ -255,23 +255,23 @@ public class InetOrgPerson extends Person {
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setStreet(String street) {
|
public void setStreet(String street) {
|
||||||
((InetOrgPerson) instance).street = street;
|
((InetOrgPerson) instance).street = street;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPostalCode(String postalCode) {
|
public void setPostalCode(String postalCode) {
|
||||||
((InetOrgPerson) instance).postalCode = postalCode;
|
((InetOrgPerson) instance).postalCode = postalCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPostalAddress(String postalAddress) {
|
public void setPostalAddress(String postalAddress) {
|
||||||
((InetOrgPerson) instance).postalAddress = postalAddress;
|
((InetOrgPerson) instance).postalAddress = postalAddress;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setMobile(String mobile) {
|
public void setMobile(String mobile) {
|
||||||
((InetOrgPerson) instance).mobile = mobile;
|
((InetOrgPerson) instance).mobile = mobile;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHomePostalAddress(String homePostalAddress) {
|
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.DirContext;
|
||||||
import javax.naming.directory.ModificationItem;
|
import javax.naming.directory.ModificationItem;
|
||||||
import javax.naming.directory.SearchControls;
|
import javax.naming.directory.SearchControls;
|
||||||
|
import javax.naming.directory.SearchResult;
|
||||||
import javax.naming.ldap.LdapContext;
|
import javax.naming.ldap.LdapContext;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
|
@ -107,7 +108,7 @@ public class LdapUserDetailsManager implements UserDetailsManager {
|
||||||
public Object mapFromAttributes(Attributes attributes) throws NamingException {
|
public Object mapFromAttributes(Attributes attributes) throws NamingException {
|
||||||
Attribute roleAttr = attributes.get(groupRoleAttributeName);
|
Attribute roleAttr = attributes.get(groupRoleAttributeName);
|
||||||
|
|
||||||
NamingEnumeration ne = roleAttr.getAll();
|
NamingEnumeration<?> ne = roleAttr.getAll();
|
||||||
// assert ne.hasMore();
|
// assert ne.hasMore();
|
||||||
Object group = ne.next();
|
Object group = ne.next();
|
||||||
String role = group.toString();
|
String role = group.toString();
|
||||||
|
@ -204,9 +205,10 @@ public class LdapUserDetailsManager implements UserDetailsManager {
|
||||||
* @param username the user whose roles are required.
|
* @param username the user whose roles are required.
|
||||||
* @return the granted authorities returned by the group search
|
* @return the granted authorities returned by the group search
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
|
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
|
||||||
SearchExecutor se = new SearchExecutor() {
|
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);
|
DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
|
||||||
SearchControls ctrls = new SearchControls();
|
SearchControls ctrls = new SearchControls();
|
||||||
ctrls.setReturningAttributes(new String[] {groupRoleAttributeName});
|
ctrls.setReturningAttributes(new String[] {groupRoleAttributeName});
|
||||||
|
@ -257,9 +259,9 @@ public class LdapUserDetailsManager implements UserDetailsManager {
|
||||||
copyToContext(user, ctx);
|
copyToContext(user, ctx);
|
||||||
|
|
||||||
// Remove the objectclass attribute from the list of mods (if present).
|
// 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()) {
|
while(modIt.hasNext()) {
|
||||||
ModificationItem mod = (ModificationItem) modIt.next();
|
ModificationItem mod = (ModificationItem) modIt.next();
|
||||||
Attribute a = mod.getAttribute();
|
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);
|
// template.rebind(dn, ctx, null);
|
||||||
// Remove the old authorities and replace them with the new one
|
// Remove the old authorities and replace them with the new one
|
||||||
|
|
|
@ -38,7 +38,7 @@ public class UserMap {
|
||||||
|
|
||||||
//~ Instance fields ================================================================================================
|
//~ Instance fields ================================================================================================
|
||||||
|
|
||||||
private Map userMap = new HashMap();
|
private Map<String, UserDetails> userMap = new HashMap<String, UserDetails>();
|
||||||
|
|
||||||
//~ Methods ========================================================================================================
|
//~ Methods ========================================================================================================
|
||||||
|
|
||||||
|
@ -66,7 +66,7 @@ public class UserMap {
|
||||||
* @throws UsernameNotFoundException if the user could not be found
|
* @throws UsernameNotFoundException if the user could not be found
|
||||||
*/
|
*/
|
||||||
public UserDetails getUser(String username) throws UsernameNotFoundException {
|
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) {
|
if (result == null) {
|
||||||
throw new UsernameNotFoundException("Could not find user: " + username, username);
|
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)
|
* @param users {@link Map} <{@link String}, {@link UserDetails}> with pairs (username, userdetails)
|
||||||
* @since 1.1
|
* @since 1.1
|
||||||
*/
|
*/
|
||||||
public void setUsers(Map users) {
|
public void setUsers(Map<String, UserDetails> users) {
|
||||||
this.userMap = 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