Always use 'this.' when accessing fields

Apply an Eclipse cleanup rules to ensure that fields are always accessed
using `this.`. This aligns with the style used by Spring Framework and
helps users quickly see the difference between a local and member
variable.

Issue gh-8945
This commit is contained in:
Phillip Webb 2020-07-26 11:51:05 -07:00 committed by Rob Winch
parent 6894ff5d12
commit 8866fa6fb0
793 changed files with 8689 additions and 8459 deletions

View File

@ -135,7 +135,7 @@ public class AclEntryVoter extends AbstractAclVoter {
* which will be the domain object used for ACL evaluation * which will be the domain object used for ACL evaluation
*/ */
protected String getInternalMethod() { protected String getInternalMethod() {
return internalMethod; return this.internalMethod;
} }
public void setInternalMethod(String internalMethod) { public void setInternalMethod(String internalMethod) {
@ -143,7 +143,7 @@ public class AclEntryVoter extends AbstractAclVoter {
} }
protected String getProcessConfigAttribute() { protected String getProcessConfigAttribute() {
return processConfigAttribute; return this.processConfigAttribute;
} }
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) {
@ -181,41 +181,41 @@ public class AclEntryVoter extends AbstractAclVoter {
} }
// Evaluate if we are required to use an inner domain object // Evaluate if we are required to use an inner domain object
if (StringUtils.hasText(internalMethod)) { if (StringUtils.hasText(this.internalMethod)) {
try { try {
Class<?> clazz = domainObject.getClass(); Class<?> clazz = domainObject.getClass();
Method method = clazz.getMethod(internalMethod, new Class[0]); Method method = clazz.getMethod(this.internalMethod, new Class[0]);
domainObject = method.invoke(domainObject); domainObject = method.invoke(domainObject);
} }
catch (NoSuchMethodException nsme) { catch (NoSuchMethodException nsme) {
throw new AuthorizationServiceException("Object of class '" + domainObject.getClass() throw new AuthorizationServiceException("Object of class '" + domainObject.getClass()
+ "' does not provide the requested internalMethod: " + internalMethod); + "' does not provide the requested internalMethod: " + this.internalMethod);
} }
catch (IllegalAccessException iae) { catch (IllegalAccessException iae) {
logger.debug("IllegalAccessException", iae); logger.debug("IllegalAccessException", iae);
throw new AuthorizationServiceException( throw new AuthorizationServiceException(
"Problem invoking internalMethod: " + internalMethod + " for object: " + domainObject); "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject);
} }
catch (InvocationTargetException ite) { catch (InvocationTargetException ite) {
logger.debug("InvocationTargetException", ite); logger.debug("InvocationTargetException", ite);
throw new AuthorizationServiceException( throw new AuthorizationServiceException(
"Problem invoking internalMethod: " + internalMethod + " for object: " + domainObject); "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject);
} }
} }
// Obtain the OID applicable to the domain object // Obtain the OID applicable to the domain object
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal // Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication); List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
Acl acl; Acl acl;
try { try {
// Lookup only ACLs for SIDs we're interested in // Lookup only ACLs for SIDs we're interested in
acl = aclService.readAclById(objectIdentity, sids); acl = this.aclService.readAclById(objectIdentity, sids);
} }
catch (NotFoundException nfe) { catch (NotFoundException nfe) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
@ -226,7 +226,7 @@ public class AclEntryVoter extends AbstractAclVoter {
} }
try { try {
if (acl.isGranted(requirePermission, sids, false)) { if (acl.isGranted(this.requirePermission, sids, false)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Voting to grant access"); logger.debug("Voting to grant access");
} }

View File

@ -63,17 +63,17 @@ public class AclPermissionCacheOptimizer implements PermissionCacheOptimizer {
if (domainObject == null) { if (domainObject == null) {
continue; continue;
} }
ObjectIdentity oid = oidRetrievalStrategy.getObjectIdentity(domainObject); ObjectIdentity oid = this.oidRetrievalStrategy.getObjectIdentity(domainObject);
oidsToCache.add(oid); oidsToCache.add(oid);
} }
List<Sid> sids = sidRetrievalStrategy.getSids(authentication); List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("Eagerly loading Acls for " + oidsToCache.size() + " objects"); this.logger.debug("Eagerly loading Acls for " + oidsToCache.size() + " objects");
} }
aclService.readAclsById(oidsToCache, sids); this.aclService.readAclsById(oidsToCache, sids);
} }
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) {

View File

@ -75,49 +75,49 @@ public class AclPermissionEvaluator implements PermissionEvaluator {
return false; return false;
} }
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
return checkPermission(authentication, objectIdentity, permission); return checkPermission(authentication, objectIdentity, permission);
} }
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
Object permission) { Object permission) {
ObjectIdentity objectIdentity = objectIdentityGenerator.createObjectIdentity(targetId, targetType); ObjectIdentity objectIdentity = this.objectIdentityGenerator.createObjectIdentity(targetId, targetType);
return checkPermission(authentication, objectIdentity, permission); return checkPermission(authentication, objectIdentity, permission);
} }
private boolean checkPermission(Authentication authentication, ObjectIdentity oid, Object permission) { private boolean checkPermission(Authentication authentication, ObjectIdentity oid, Object permission) {
// Obtain the SIDs applicable to the principal // Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication); List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
List<Permission> requiredPermission = resolvePermission(permission); List<Permission> requiredPermission = resolvePermission(permission);
final boolean debug = logger.isDebugEnabled(); final boolean debug = this.logger.isDebugEnabled();
if (debug) { if (debug) {
logger.debug("Checking permission '" + permission + "' for object '" + oid + "'"); this.logger.debug("Checking permission '" + permission + "' for object '" + oid + "'");
} }
try { try {
// Lookup only ACLs for SIDs we're interested in // Lookup only ACLs for SIDs we're interested in
Acl acl = aclService.readAclById(oid, sids); Acl acl = this.aclService.readAclById(oid, sids);
if (acl.isGranted(requiredPermission, sids, false)) { if (acl.isGranted(requiredPermission, sids, false)) {
if (debug) { if (debug) {
logger.debug("Access is granted"); this.logger.debug("Access is granted");
} }
return true; return true;
} }
if (debug) { if (debug) {
logger.debug("Returning false - ACLs returned, but insufficient permissions for this principal"); this.logger.debug("Returning false - ACLs returned, but insufficient permissions for this principal");
} }
} }
catch (NotFoundException nfe) { catch (NotFoundException nfe) {
if (debug) { if (debug) {
logger.debug("Returning false - no ACLs apply for this principal"); this.logger.debug("Returning false - no ACLs apply for this principal");
} }
} }
@ -127,7 +127,7 @@ public class AclPermissionEvaluator implements PermissionEvaluator {
List<Permission> resolvePermission(Object permission) { List<Permission> resolvePermission(Object permission) {
if (permission instanceof Integer) { if (permission instanceof Integer) {
return Arrays.asList(permissionFactory.buildFromMask((Integer) permission)); return Arrays.asList(this.permissionFactory.buildFromMask((Integer) permission));
} }
if (permission instanceof Permission) { if (permission instanceof Permission) {
@ -143,10 +143,10 @@ public class AclPermissionEvaluator implements PermissionEvaluator {
Permission p; Permission p;
try { try {
p = permissionFactory.buildFromName(permString); p = this.permissionFactory.buildFromName(permString);
} }
catch (IllegalArgumentException notfound) { catch (IllegalArgumentException notfound) {
p = permissionFactory.buildFromName(permString.toUpperCase(Locale.ENGLISH)); p = this.permissionFactory.buildFromName(permString.toUpperCase(Locale.ENGLISH));
} }
if (p != null) { if (p != null) {

View File

@ -68,21 +68,21 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
} }
protected Class<?> getProcessDomainObjectClass() { protected Class<?> getProcessDomainObjectClass() {
return processDomainObjectClass; return this.processDomainObjectClass;
} }
protected boolean hasPermission(Authentication authentication, Object domainObject) { protected boolean hasPermission(Authentication authentication, Object domainObject) {
// Obtain the OID applicable to the domain object // Obtain the OID applicable to the domain object
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal // Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication); List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
try { try {
// Lookup only ACLs for SIDs we're interested in // Lookup only ACLs for SIDs we're interested in
Acl acl = aclService.readAclById(objectIdentity, sids); Acl acl = this.aclService.readAclById(objectIdentity, sids);
return acl.isGranted(requirePermission, sids, false); return acl.isGranted(this.requirePermission, sids, false);
} }
catch (NotFoundException ignore) { catch (NotFoundException ignore) {
return false; return false;
@ -110,7 +110,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
} }
public boolean supports(ConfigAttribute attribute) { public boolean supports(ConfigAttribute attribute) {
return processConfigAttribute.equals(attribute.getAttribute()); return this.processConfigAttribute.equals(attribute.getAttribute());
} }
/** /**

View File

@ -103,7 +103,7 @@ public class AclEntryAfterInvocationProvider extends AbstractAclProvider impleme
logger.debug("Denying access"); logger.debug("Denying access");
throw new AccessDeniedException(messages.getMessage("AclEntryAfterInvocationProvider.noPermission", throw new AccessDeniedException(this.messages.getMessage("AclEntryAfterInvocationProvider.noPermission",
new Object[] { authentication.getName(), returnedObject }, new Object[] { authentication.getName(), returnedObject },
"Authentication {0} has NO permissions to the domain object {1}")); "Authentication {0} has NO permissions to the domain object {1}"));
} }

View File

@ -45,7 +45,7 @@ class ArrayFilterer<T> implements Filterer<T> {
// Collect the removed objects to a HashSet so that // Collect the removed objects to a HashSet so that
// it is fast to lookup them when a filtered array // it is fast to lookup them when a filtered array
// is constructed. // is constructed.
removeList = new HashSet<>(); this.removeList = new HashSet<>();
} }
/** /**
@ -55,14 +55,14 @@ class ArrayFilterer<T> implements Filterer<T> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T[] getFilteredObject() { public T[] getFilteredObject() {
// Recreate an array of same type and filter the removed objects. // Recreate an array of same type and filter the removed objects.
int originalSize = list.length; int originalSize = this.list.length;
int sizeOfResultingList = originalSize - removeList.size(); int sizeOfResultingList = originalSize - this.removeList.size();
T[] filtered = (T[]) Array.newInstance(list.getClass().getComponentType(), sizeOfResultingList); T[] filtered = (T[]) Array.newInstance(this.list.getClass().getComponentType(), sizeOfResultingList);
for (int i = 0, j = 0; i < list.length; i++) { for (int i = 0, j = 0; i < this.list.length; i++) {
T object = list[i]; T object = this.list[i];
if (!removeList.contains(object)) { if (!this.removeList.contains(object)) {
filtered[j] = object; filtered[j] = object;
j++; j++;
} }
@ -85,14 +85,14 @@ class ArrayFilterer<T> implements Filterer<T> {
private int index = 0; private int index = 0;
public boolean hasNext() { public boolean hasNext() {
return index < list.length; return this.index < ArrayFilterer.this.list.length;
} }
public T next() { public T next() {
if (!hasNext()) { if (!hasNext()) {
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
return list[index++]; return ArrayFilterer.this.list[this.index++];
} }
public void remove() { public void remove() {
@ -106,7 +106,7 @@ class ArrayFilterer<T> implements Filterer<T> {
* @see org.springframework.security.acls.afterinvocation.Filterer#remove(java.lang.Object) * @see org.springframework.security.acls.afterinvocation.Filterer#remove(java.lang.Object)
*/ */
public void remove(T object) { public void remove(T object) {
removeList.add(object); this.removeList.add(object);
} }
} }

View File

@ -48,7 +48,7 @@ class CollectionFilterer<T> implements Filterer<T> {
// to the method may not necessarily be re-constructable (as // to the method may not necessarily be re-constructable (as
// the Collection(collection) constructor is not guaranteed and // the Collection(collection) constructor is not guaranteed and
// manually adding may lose sort order or other capabilities) // manually adding may lose sort order or other capabilities)
removeList = new HashSet<>(); this.removeList = new HashSet<>();
} }
/** /**
@ -57,20 +57,20 @@ class CollectionFilterer<T> implements Filterer<T> {
*/ */
public Object getFilteredObject() { public Object getFilteredObject() {
// Now the Iterator has ended, remove Objects from Collection // Now the Iterator has ended, remove Objects from Collection
Iterator<T> removeIter = removeList.iterator(); Iterator<T> removeIter = this.removeList.iterator();
int originalSize = collection.size(); int originalSize = this.collection.size();
while (removeIter.hasNext()) { while (removeIter.hasNext()) {
collection.remove(removeIter.next()); this.collection.remove(removeIter.next());
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Original collection contained " + originalSize + " elements; now contains " logger.debug("Original collection contained " + originalSize + " elements; now contains "
+ collection.size() + " elements"); + this.collection.size() + " elements");
} }
return collection; return this.collection;
} }
/** /**
@ -78,7 +78,7 @@ class CollectionFilterer<T> implements Filterer<T> {
* @see org.springframework.security.acls.afterinvocation.Filterer#iterator() * @see org.springframework.security.acls.afterinvocation.Filterer#iterator()
*/ */
public Iterator<T> iterator() { public Iterator<T> iterator() {
return collection.iterator(); return this.collection.iterator();
} }
/** /**
@ -86,7 +86,7 @@ class CollectionFilterer<T> implements Filterer<T> {
* @see org.springframework.security.acls.afterinvocation.Filterer#remove(java.lang.Object) * @see org.springframework.security.acls.afterinvocation.Filterer#remove(java.lang.Object)
*/ */
public void remove(T object) { public void remove(T object) {
removeList.add(object); this.removeList.add(object);
} }
} }

View File

@ -65,15 +65,15 @@ public abstract class AbstractPermission implements Permission {
} }
public final int getMask() { public final int getMask() {
return mask; return this.mask;
} }
public String getPattern() { public String getPattern() {
return AclFormattingUtils.printBinary(mask, code); return AclFormattingUtils.printBinary(this.mask, this.code);
} }
public final String toString() { public final String toString() {
return this.getClass().getSimpleName() + "[" + getPattern() + "=" + mask + "]"; return this.getClass().getSimpleName() + "[" + getPattern() + "=" + this.mask + "]";
} }
public final int hashCode() { public final int hashCode() {

View File

@ -134,37 +134,37 @@ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAcce
@Override @Override
public Acl getAcl() { public Acl getAcl() {
return acl; return this.acl;
} }
@Override @Override
public Serializable getId() { public Serializable getId() {
return id; return this.id;
} }
@Override @Override
public Permission getPermission() { public Permission getPermission() {
return permission; return this.permission;
} }
@Override @Override
public Sid getSid() { public Sid getSid() {
return sid; return this.sid;
} }
@Override @Override
public boolean isAuditFailure() { public boolean isAuditFailure() {
return auditFailure; return this.auditFailure;
} }
@Override @Override
public boolean isAuditSuccess() { public boolean isAuditSuccess() {
return auditSuccess; return this.auditSuccess;
} }
@Override @Override
public boolean isGranting() { public boolean isGranting() {
return granting; return this.granting;
} }
void setAuditFailure(boolean auditFailure) { void setAuditFailure(boolean auditFailure) {

View File

@ -68,12 +68,12 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
Assert.isTrue(auths != null && (auths.length == 3 || auths.length == 1), Assert.isTrue(auths != null && (auths.length == 3 || auths.length == 1),
"One or three GrantedAuthority instances required"); "One or three GrantedAuthority instances required");
if (auths.length == 3) { if (auths.length == 3) {
gaTakeOwnership = auths[0]; this.gaTakeOwnership = auths[0];
gaModifyAuditing = auths[1]; this.gaModifyAuditing = auths[1];
gaGeneralChanges = auths[2]; this.gaGeneralChanges = auths[2];
} }
else { else {
gaTakeOwnership = gaModifyAuditing = gaGeneralChanges = auths[0]; this.gaTakeOwnership = this.gaModifyAuditing = this.gaGeneralChanges = auths[0];
} }
} }
@ -117,7 +117,7 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
} }
// Try to get permission via ACEs within the ACL // Try to get permission via ACEs within the ACL
List<Sid> sids = sidRetrievalStrategy.getSids(authentication); List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication);
if (acl.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), sids, false)) { if (acl.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), sids, false)) {
return; return;

View File

@ -121,10 +121,10 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
@Override @Override
public void deleteAce(int aceIndex) throws NotFoundException { public void deleteAce(int aceIndex) throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
verifyAceIndexExists(aceIndex); verifyAceIndexExists(aceIndex);
synchronized (aces) { synchronized (this.aces) {
this.aces.remove(aceIndex); this.aces.remove(aceIndex);
} }
} }
@ -135,14 +135,14 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
} }
if (aceIndex >= this.aces.size()) { if (aceIndex >= this.aces.size()) {
throw new NotFoundException("aceIndex must refer to an index of the AccessControlEntry list. " throw new NotFoundException("aceIndex must refer to an index of the AccessControlEntry list. "
+ "List size is " + aces.size() + ", index was " + aceIndex); + "List size is " + this.aces.size() + ", index was " + aceIndex);
} }
} }
@Override @Override
public void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting) public void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting)
throws NotFoundException { throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.notNull(permission, "Permission required"); Assert.notNull(permission, "Permission required");
Assert.notNull(sid, "Sid required"); Assert.notNull(sid, "Sid required");
if (atIndexLocation < 0) { if (atIndexLocation < 0) {
@ -155,7 +155,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
AccessControlEntryImpl ace = new AccessControlEntryImpl(null, this, sid, permission, granting, false, false); AccessControlEntryImpl ace = new AccessControlEntryImpl(null, this, sid, permission, granting, false, false);
synchronized (aces) { synchronized (this.aces) {
this.aces.add(atIndexLocation, ace); this.aces.add(atIndexLocation, ace);
} }
} }
@ -164,7 +164,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
public List<AccessControlEntry> getEntries() { public List<AccessControlEntry> getEntries() {
// Can safely return AccessControlEntry directly, as they're immutable outside the // Can safely return AccessControlEntry directly, as they're immutable outside the
// ACL package // ACL package
return new ArrayList<>(aces); return new ArrayList<>(this.aces);
} }
@Override @Override
@ -174,12 +174,12 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
@Override @Override
public ObjectIdentity getObjectIdentity() { public ObjectIdentity getObjectIdentity() {
return objectIdentity; return this.objectIdentity;
} }
@Override @Override
public boolean isEntriesInheriting() { public boolean isEntriesInheriting() {
return entriesInheriting; return this.entriesInheriting;
} }
/** /**
@ -198,7 +198,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
throw new UnloadedSidException("ACL was not loaded for one or more SID"); throw new UnloadedSidException("ACL was not loaded for one or more SID");
} }
return permissionGrantingStrategy.isGranted(this, permission, sids, administrativeMode); return this.permissionGrantingStrategy.isGranted(this, permission, sids, administrativeMode);
} }
@Override @Override
@ -213,7 +213,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
for (Sid sid : sids) { for (Sid sid : sids) {
boolean found = false; boolean found = false;
for (Sid loadedSid : loadedSids) { for (Sid loadedSid : this.loadedSids) {
if (sid.equals(loadedSid)) { if (sid.equals(loadedSid)) {
// this SID is OK // this SID is OK
found = true; found = true;
@ -232,13 +232,13 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
@Override @Override
public void setEntriesInheriting(boolean entriesInheriting) { public void setEntriesInheriting(boolean entriesInheriting) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
this.entriesInheriting = entriesInheriting; this.entriesInheriting = entriesInheriting;
} }
@Override @Override
public void setOwner(Sid newOwner) { public void setOwner(Sid newOwner) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_OWNERSHIP); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.notNull(newOwner, "Owner required"); Assert.notNull(newOwner, "Owner required");
this.owner = newOwner; this.owner = newOwner;
} }
@ -250,34 +250,34 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
@Override @Override
public void setParent(Acl newParent) { public void setParent(Acl newParent) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.isTrue(newParent == null || !newParent.equals(this), "Cannot be the parent of yourself"); Assert.isTrue(newParent == null || !newParent.equals(this), "Cannot be the parent of yourself");
this.parentAcl = newParent; this.parentAcl = newParent;
} }
@Override @Override
public Acl getParentAcl() { public Acl getParentAcl() {
return parentAcl; return this.parentAcl;
} }
@Override @Override
public void updateAce(int aceIndex, Permission permission) throws NotFoundException { public void updateAce(int aceIndex, Permission permission) throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
verifyAceIndexExists(aceIndex); verifyAceIndexExists(aceIndex);
synchronized (aces) { synchronized (this.aces) {
AccessControlEntryImpl ace = (AccessControlEntryImpl) aces.get(aceIndex); AccessControlEntryImpl ace = (AccessControlEntryImpl) this.aces.get(aceIndex);
ace.setPermission(permission); ace.setPermission(permission);
} }
} }
@Override @Override
public void updateAuditing(int aceIndex, boolean auditSuccess, boolean auditFailure) { public void updateAuditing(int aceIndex, boolean auditSuccess, boolean auditFailure) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_AUDITING); this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_AUDITING);
verifyAceIndexExists(aceIndex); verifyAceIndexExists(aceIndex);
synchronized (aces) { synchronized (this.aces) {
AccessControlEntryImpl ace = (AccessControlEntryImpl) aces.get(aceIndex); AccessControlEntryImpl ace = (AccessControlEntryImpl) this.aces.get(aceIndex);
ace.setAuditSuccess(auditSuccess); ace.setAuditSuccess(auditSuccess);
ace.setAuditFailure(auditFailure); ace.setAuditFailure(auditFailure);
} }
@ -342,7 +342,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
int count = 0; int count = 0;
for (AccessControlEntry ace : aces) { for (AccessControlEntry ace : this.aces) {
count++; count++;
if (count == 1) { if (count == 1) {

View File

@ -103,21 +103,21 @@ public class DefaultPermissionFactory implements PermissionFactory {
Integer mask = perm.getMask(); Integer mask = 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), Assert.isTrue(!this.registeredPermissionsByInteger.containsKey(mask),
() -> "An existing Permission already provides mask " + mask); () -> "An existing Permission already provides mask " + mask);
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), Assert.isTrue(!this.registeredPermissionsByName.containsKey(permissionName),
() -> "An existing Permission already provides name '" + permissionName + "'"); () -> "An existing Permission already provides name '" + permissionName + "'");
// Register the new Permission // Register the new Permission
registeredPermissionsByInteger.put(mask, perm); this.registeredPermissionsByInteger.put(mask, perm);
registeredPermissionsByName.put(permissionName, perm); this.registeredPermissionsByName.put(permissionName, perm);
} }
public Permission buildFromMask(int mask) { public Permission buildFromMask(int mask) {
if (registeredPermissionsByInteger.containsKey(mask)) { if (this.registeredPermissionsByInteger.containsKey(mask)) {
// The requested mask has an exact match against a statically-defined // The requested mask has an exact match against a statically-defined
// Permission, so return it // Permission, so return it
return registeredPermissionsByInteger.get(mask); return this.registeredPermissionsByInteger.get(mask);
} }
// To get this far, we have to use a CumulativePermission // To get this far, we have to use a CumulativePermission
@ -127,7 +127,7 @@ public class DefaultPermissionFactory implements PermissionFactory {
int permissionToCheck = 1 << i; int permissionToCheck = 1 << i;
if ((mask & permissionToCheck) == permissionToCheck) { if ((mask & permissionToCheck) == permissionToCheck) {
Permission p = registeredPermissionsByInteger.get(permissionToCheck); Permission p = this.registeredPermissionsByInteger.get(permissionToCheck);
if (p == null) { if (p == null) {
throw new IllegalStateException( throw new IllegalStateException(
@ -141,7 +141,7 @@ public class DefaultPermissionFactory implements PermissionFactory {
} }
public Permission buildFromName(String name) { public Permission buildFromName(String name) {
Permission p = registeredPermissionsByName.get(name); Permission p = this.registeredPermissionsByName.get(name);
if (p == null) { if (p == null) {
throw new IllegalArgumentException("Unknown permission '" + name + "'"); throw new IllegalArgumentException("Unknown permission '" + name + "'");

View File

@ -90,7 +90,7 @@ public class DefaultPermissionGrantingStrategy implements PermissionGrantingStra
if (ace.isGranting()) { if (ace.isGranting()) {
// Success // Success
if (!administrativeMode) { if (!administrativeMode) {
auditLogger.logIfNeeded(true, ace); this.auditLogger.logIfNeeded(true, ace);
} }
return true; return true;
@ -120,7 +120,7 @@ public class DefaultPermissionGrantingStrategy implements PermissionGrantingStra
// We found an ACE to reject the request at this point, as no // We found an ACE to reject the request at this point, as no
// other ACEs were found that granted a different permission // other ACEs were found that granted a different permission
if (!administrativeMode) { if (!administrativeMode) {
auditLogger.logIfNeeded(false, firstRejection); this.auditLogger.logIfNeeded(false, firstRejection);
} }
return false; return false;

View File

@ -61,8 +61,8 @@ public class EhCacheBasedAclCache implements AclCache {
MutableAcl acl = getFromCache(pk); MutableAcl acl = getFromCache(pk);
if (acl != null) { if (acl != null) {
cache.remove(acl.getId()); this.cache.remove(acl.getId());
cache.remove(acl.getObjectIdentity()); this.cache.remove(acl.getObjectIdentity());
} }
} }
@ -72,8 +72,8 @@ public class EhCacheBasedAclCache implements AclCache {
MutableAcl acl = getFromCache(objectIdentity); MutableAcl acl = getFromCache(objectIdentity);
if (acl != null) { if (acl != null) {
cache.remove(acl.getId()); this.cache.remove(acl.getId());
cache.remove(acl.getObjectIdentity()); this.cache.remove(acl.getObjectIdentity());
} }
} }
@ -83,7 +83,7 @@ public class EhCacheBasedAclCache implements AclCache {
Element element = null; Element element = null;
try { try {
element = cache.get(objectIdentity); element = this.cache.get(objectIdentity);
} }
catch (CacheException ignored) { catch (CacheException ignored) {
} }
@ -101,7 +101,7 @@ public class EhCacheBasedAclCache implements AclCache {
Element element = null; Element element = null;
try { try {
element = cache.get(pk); element = this.cache.get(pk);
} }
catch (CacheException ignored) { catch (CacheException ignored) {
} }
@ -131,8 +131,8 @@ public class EhCacheBasedAclCache implements AclCache {
putInCache((MutableAcl) acl.getParentAcl()); putInCache((MutableAcl) acl.getParentAcl());
} }
cache.put(new Element(acl.getObjectIdentity(), acl)); this.cache.put(new Element(acl.getObjectIdentity(), acl));
cache.put(new Element(acl.getId(), acl)); this.cache.put(new Element(acl.getId(), acl));
} }
private MutableAcl initializeTransientFields(MutableAcl value) { private MutableAcl initializeTransientFields(MutableAcl value) {
@ -148,7 +148,7 @@ public class EhCacheBasedAclCache implements AclCache {
} }
public void clearCache() { public void clearCache() {
cache.removeAll(); this.cache.removeAll();
} }
} }

View File

@ -62,7 +62,7 @@ public class GrantedAuthoritySid implements Sid {
} }
public String getGrantedAuthority() { public String getGrantedAuthority() {
return grantedAuthority; return this.grantedAuthority;
} }
@Override @Override

View File

@ -69,7 +69,7 @@ public class ObjectIdentityImpl implements ObjectIdentity {
Assert.notNull(object, "object cannot be null"); Assert.notNull(object, "object cannot be null");
Class<?> typeClass = ClassUtils.getUserClass(object.getClass()); Class<?> typeClass = ClassUtils.getUserClass(object.getClass());
type = typeClass.getName(); this.type = typeClass.getName();
Object result; Object result;
@ -105,30 +105,30 @@ public class ObjectIdentityImpl implements ObjectIdentity {
ObjectIdentityImpl other = (ObjectIdentityImpl) arg0; ObjectIdentityImpl other = (ObjectIdentityImpl) arg0;
if (identifier instanceof Number && other.identifier instanceof Number) { if (this.identifier instanceof Number && other.identifier instanceof Number) {
// Integers and Longs with same value should be considered equal // Integers and Longs with same value should be considered equal
if (((Number) identifier).longValue() != ((Number) other.identifier).longValue()) { if (((Number) this.identifier).longValue() != ((Number) other.identifier).longValue()) {
return false; return false;
} }
} }
else { else {
// Use plain equality for other serializable types // Use plain equality for other serializable types
if (!identifier.equals(other.identifier)) { if (!this.identifier.equals(other.identifier)) {
return false; return false;
} }
} }
return type.equals(other.type); return this.type.equals(other.type);
} }
@Override @Override
public Serializable getIdentifier() { public Serializable getIdentifier() {
return identifier; return this.identifier;
} }
@Override @Override
public String getType() { public String getType() {
return type; return this.type;
} }
/** /**

View File

@ -62,7 +62,7 @@ public class PrincipalSid implements Sid {
} }
public String getPrincipal() { public String getPrincipal() {
return principal; return this.principal;
} }
@Override @Override

View File

@ -52,7 +52,7 @@ public class SidRetrievalStrategyImpl implements SidRetrievalStrategy {
} }
public List<Sid> getSids(Authentication authentication) { public List<Sid> getSids(Authentication authentication) {
Collection<? extends GrantedAuthority> authorities = roleHierarchy Collection<? extends GrantedAuthority> authorities = this.roleHierarchy
.getReachableGrantedAuthorities(authentication.getAuthorities()); .getReachableGrantedAuthorities(authentication.getAuthorities());
List<Sid> sids = new ArrayList<>(authorities.size() + 1); List<Sid> sids = new ArrayList<>(authorities.size() + 1);

View File

@ -62,8 +62,8 @@ public class SpringCacheBasedAclCache implements AclCache {
MutableAcl acl = getFromCache(pk); MutableAcl acl = getFromCache(pk);
if (acl != null) { if (acl != null) {
cache.evict(acl.getId()); this.cache.evict(acl.getId());
cache.evict(acl.getObjectIdentity()); this.cache.evict(acl.getObjectIdentity());
} }
} }
@ -73,8 +73,8 @@ public class SpringCacheBasedAclCache implements AclCache {
MutableAcl acl = getFromCache(objectIdentity); MutableAcl acl = getFromCache(objectIdentity);
if (acl != null) { if (acl != null) {
cache.evict(acl.getId()); this.cache.evict(acl.getId());
cache.evict(acl.getObjectIdentity()); this.cache.evict(acl.getObjectIdentity());
} }
} }
@ -97,12 +97,12 @@ public class SpringCacheBasedAclCache implements AclCache {
putInCache((MutableAcl) acl.getParentAcl()); putInCache((MutableAcl) acl.getParentAcl());
} }
cache.put(acl.getObjectIdentity(), acl); this.cache.put(acl.getObjectIdentity(), acl);
cache.put(acl.getId(), acl); this.cache.put(acl.getId(), acl);
} }
private MutableAcl getFromCache(Object key) { private MutableAcl getFromCache(Object key) {
Cache.ValueWrapper element = cache.get(key); Cache.ValueWrapper element = this.cache.get(key);
if (element == null) { if (element == null) {
return null; return null;
@ -124,7 +124,7 @@ public class SpringCacheBasedAclCache implements AclCache {
} }
public void clearCache() { public void clearCache() {
cache.clear(); this.cache.clear();
} }
} }

View File

@ -109,11 +109,11 @@ class AclClassIdUtils {
} }
private <T> boolean canConvertFromStringTo(Class<T> targetType) { private <T> boolean canConvertFromStringTo(Class<T> targetType) {
return conversionService.canConvert(String.class, targetType); return this.conversionService.canConvert(String.class, targetType);
} }
private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) { private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) {
return conversionService.convert(identifier, targetType); return this.conversionService.convert(identifier, targetType);
} }
/** /**
@ -128,8 +128,8 @@ class AclClassIdUtils {
*/ */
private Long convertToLong(Serializable identifier) { private Long convertToLong(Serializable identifier) {
Long idAsLong; Long idAsLong;
if (conversionService.canConvert(identifier.getClass(), Long.class)) { if (this.conversionService.canConvert(identifier.getClass(), Long.class)) {
idAsLong = conversionService.convert(identifier, Long.class); idAsLong = this.conversionService.convert(identifier, Long.class);
} }
else { else {
idAsLong = Long.valueOf(identifier.toString()); idAsLong = Long.valueOf(identifier.toString());

View File

@ -156,21 +156,21 @@ public class BasicLookupStrategy implements LookupStrategy {
Assert.notNull(aclCache, "AclCache required"); Assert.notNull(aclCache, "AclCache required");
Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required");
Assert.notNull(grantingStrategy, "grantingStrategy required"); Assert.notNull(grantingStrategy, "grantingStrategy required");
jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(dataSource);
this.aclCache = aclCache; this.aclCache = aclCache;
this.aclAuthorizationStrategy = aclAuthorizationStrategy; this.aclAuthorizationStrategy = aclAuthorizationStrategy;
this.grantingStrategy = grantingStrategy; this.grantingStrategy = grantingStrategy;
this.aclClassIdUtils = new AclClassIdUtils(); this.aclClassIdUtils = new AclClassIdUtils();
fieldAces.setAccessible(true); this.fieldAces.setAccessible(true);
fieldAcl.setAccessible(true); this.fieldAcl.setAccessible(true);
} }
private String computeRepeatingSql(String repeatingSql, int requiredRepetitions) { private String computeRepeatingSql(String repeatingSql, int requiredRepetitions) {
assert requiredRepetitions > 0 : "requiredRepetitions must be > 0"; assert requiredRepetitions > 0 : "requiredRepetitions must be > 0";
final String startSql = selectClause; final String startSql = this.selectClause;
final String endSql = orderByClause; final String endSql = this.orderByClause;
StringBuilder sqlStringBldr = new StringBuilder( StringBuilder sqlStringBldr = new StringBuilder(
startSql.length() + endSql.length() + requiredRepetitions * (repeatingSql.length() + 4)); startSql.length() + endSql.length() + requiredRepetitions * (repeatingSql.length() + 4));
@ -192,7 +192,7 @@ public class BasicLookupStrategy implements LookupStrategy {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private List<AccessControlEntryImpl> readAces(AclImpl acl) { private List<AccessControlEntryImpl> readAces(AclImpl acl) {
try { try {
return (List<AccessControlEntryImpl>) fieldAces.get(acl); return (List<AccessControlEntryImpl>) this.fieldAces.get(acl);
} }
catch (IllegalAccessException e) { catch (IllegalAccessException e) {
throw new IllegalStateException("Could not obtain AclImpl.aces field", e); throw new IllegalStateException("Could not obtain AclImpl.aces field", e);
@ -201,7 +201,7 @@ public class BasicLookupStrategy implements LookupStrategy {
private void setAclOnAce(AccessControlEntryImpl ace, AclImpl acl) { private void setAclOnAce(AccessControlEntryImpl ace, AclImpl acl) {
try { try {
fieldAcl.set(ace, acl); this.fieldAcl.set(ace, acl);
} }
catch (IllegalAccessException e) { catch (IllegalAccessException e) {
throw new IllegalStateException("Could not or set AclImpl on AccessControlEntryImpl fields", e); throw new IllegalStateException("Could not or set AclImpl on AccessControlEntryImpl fields", e);
@ -210,7 +210,7 @@ public class BasicLookupStrategy implements LookupStrategy {
private void setAces(AclImpl acl, List<AccessControlEntryImpl> aces) { private void setAces(AclImpl acl, List<AccessControlEntryImpl> aces) {
try { try {
fieldAces.set(acl, aces); this.fieldAces.set(acl, aces);
} }
catch (IllegalAccessException e) { catch (IllegalAccessException e) {
throw new IllegalStateException("Could not set AclImpl entries", e); throw new IllegalStateException("Could not set AclImpl entries", e);
@ -228,9 +228,9 @@ public class BasicLookupStrategy implements LookupStrategy {
Assert.notNull(acls, "ACLs are required"); Assert.notNull(acls, "ACLs are required");
Assert.notEmpty(findNow, "Items to find now required"); Assert.notEmpty(findNow, "Items to find now required");
String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size()); String sql = computeRepeatingSql(this.lookupPrimaryKeysWhereClause, findNow.size());
Set<Long> parentsToLookup = jdbcTemplate.query(sql, ps -> { Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, ps -> {
int i = 0; int i = 0;
for (Long toFind : findNow) { for (Long toFind : findNow) {
@ -265,7 +265,7 @@ public class BasicLookupStrategy implements LookupStrategy {
* automatically create entries if required) * automatically create entries if required)
*/ */
public final Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) { public final Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) {
Assert.isTrue(batchSize >= 1, "BatchSize must be >= 1"); Assert.isTrue(this.batchSize >= 1, "BatchSize must be >= 1");
Assert.notEmpty(objects, "Objects to lookup required"); Assert.notEmpty(objects, "Objects to lookup required");
// Map<ObjectIdentity,Acl> // Map<ObjectIdentity,Acl>
@ -288,7 +288,7 @@ public class BasicLookupStrategy implements LookupStrategy {
// Check cache for the present ACL entry // Check cache for the present ACL entry
if (!aclFound) { if (!aclFound) {
Acl acl = aclCache.getFromCache(oid); Acl acl = this.aclCache.getFromCache(oid);
// Ensure any cached element supports all the requested SIDs // Ensure any cached element supports all the requested SIDs
// (they should always, as our base impl doesn't filter on SID) // (they should always, as our base impl doesn't filter on SID)
@ -321,7 +321,7 @@ public class BasicLookupStrategy implements LookupStrategy {
// Add the loaded batch to the cache // Add the loaded batch to the cache
for (Acl loadedAcl : loadedBatch.values()) { for (Acl loadedAcl : loadedBatch.values()) {
aclCache.putInCache((AclImpl) loadedAcl); this.aclCache.putInCache((AclImpl) loadedAcl);
} }
currentBatchToLoad.clear(); currentBatchToLoad.clear();
@ -354,9 +354,9 @@ public class BasicLookupStrategy implements LookupStrategy {
// Make the "acls" map contain all requested objectIdentities // Make the "acls" map contain all requested objectIdentities
// (including markers to each parent in the hierarchy) // (including markers to each parent in the hierarchy)
String sql = computeRepeatingSql(lookupObjectIdentitiesWhereClause, objectIdentities.size()); String sql = computeRepeatingSql(this.lookupObjectIdentitiesWhereClause, objectIdentities.size());
Set<Long> parentsToLookup = jdbcTemplate.query(sql, ps -> { Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, ps -> {
int i = 0; int i = 0;
for (ObjectIdentity oid : objectIdentities) { for (ObjectIdentity oid : objectIdentities) {
// Determine prepared statement values for this iteration // Determine prepared statement values for this iteration
@ -421,8 +421,8 @@ public class BasicLookupStrategy implements LookupStrategy {
} }
// Now we have the parent (if there is one), create the true AclImpl // Now we have the parent (if there is one), create the true AclImpl
AclImpl result = new AclImpl(inputAcl.getObjectIdentity(), inputAcl.getId(), aclAuthorizationStrategy, AclImpl result = new AclImpl(inputAcl.getObjectIdentity(), inputAcl.getId(), this.aclAuthorizationStrategy,
grantingStrategy, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner()); this.grantingStrategy, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner());
// Copy the "aces" from the input to the destination // Copy the "aces" from the input to the destination
@ -548,27 +548,27 @@ public class BasicLookupStrategy implements LookupStrategy {
while (rs.next()) { while (rs.next()) {
// Convert current row into an Acl (albeit with a StubAclParent) // Convert current row into an Acl (albeit with a StubAclParent)
convertCurrentResultIntoObject(acls, rs); convertCurrentResultIntoObject(this.acls, rs);
// Figure out if this row means we need to lookup another parent // Figure out if this row means we need to lookup another parent
long parentId = rs.getLong("parent_object"); long parentId = rs.getLong("parent_object");
if (parentId != 0) { if (parentId != 0) {
// See if it's already in the "acls" // See if it's already in the "acls"
if (acls.containsKey(parentId)) { if (this.acls.containsKey(parentId)) {
continue; // skip this while iteration continue; // skip this while iteration
} }
// Now try to find it in the cache // Now try to find it in the cache
MutableAcl cached = aclCache.getFromCache(parentId); MutableAcl cached = BasicLookupStrategy.this.aclCache.getFromCache(parentId);
if ((cached == null) || !cached.isSidLoaded(sids)) { if ((cached == null) || !cached.isSidLoaded(this.sids)) {
parentIdsToLookup.add(parentId); parentIdsToLookup.add(parentId);
} }
else { else {
// Pop into the acls map, so our convert method doesn't // Pop into the acls map, so our convert method doesn't
// need to deal with an unsynchronized AclCache // need to deal with an unsynchronized AclCache
acls.put(cached.getId(), cached); this.acls.put(cached.getId(), cached);
} }
} }
} }
@ -597,7 +597,7 @@ public class BasicLookupStrategy implements LookupStrategy {
// If the Java type is a String, check to see if we can convert it to the // If the Java type is a String, check to see if we can convert it to the
// target id type, e.g. UUID. // target id type, e.g. UUID.
Serializable identifier = (Serializable) rs.getObject("object_id_identity"); Serializable identifier = (Serializable) rs.getObject("object_id_identity");
identifier = aclClassIdUtils.identifierFrom(identifier, rs); identifier = BasicLookupStrategy.this.aclClassIdUtils.identifierFrom(identifier, rs);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(rs.getString("class"), identifier); ObjectIdentity objectIdentity = new ObjectIdentityImpl(rs.getString("class"), identifier);
Acl parentAcl = null; Acl parentAcl = null;
@ -610,8 +610,8 @@ public class BasicLookupStrategy implements LookupStrategy {
boolean entriesInheriting = rs.getBoolean("entries_inheriting"); boolean entriesInheriting = rs.getBoolean("entries_inheriting");
Sid owner = createSid(rs.getBoolean("acl_principal"), rs.getString("acl_sid")); Sid owner = createSid(rs.getBoolean("acl_principal"), rs.getString("acl_sid"));
acl = new AclImpl(objectIdentity, id, aclAuthorizationStrategy, grantingStrategy, parentAcl, null, acl = new AclImpl(objectIdentity, id, BasicLookupStrategy.this.aclAuthorizationStrategy,
entriesInheriting, owner); BasicLookupStrategy.this.grantingStrategy, parentAcl, null, entriesInheriting, owner);
acls.put(id, acl); acls.put(id, acl);
} }
@ -624,7 +624,7 @@ public class BasicLookupStrategy implements LookupStrategy {
Sid recipient = createSid(rs.getBoolean("ace_principal"), rs.getString("ace_sid")); Sid recipient = createSid(rs.getBoolean("ace_principal"), rs.getString("ace_sid"));
int mask = rs.getInt("mask"); int mask = rs.getInt("mask");
Permission permission = permissionFactory.buildFromMask(mask); Permission permission = BasicLookupStrategy.this.permissionFactory.buildFromMask(mask);
boolean granting = rs.getBoolean("granting"); boolean granting = rs.getBoolean("granting");
boolean auditSuccess = rs.getBoolean("audit_success"); boolean auditSuccess = rs.getBoolean("audit_success");
boolean auditFailure = rs.getBoolean("audit_failure"); boolean auditFailure = rs.getBoolean("audit_failure");
@ -657,7 +657,7 @@ public class BasicLookupStrategy implements LookupStrategy {
} }
public Long getId() { public Long getId() {
return id; return this.id;
} }
public ObjectIdentity getObjectIdentity() { public ObjectIdentity getObjectIdentity() {

View File

@ -92,10 +92,10 @@ public class JdbcAclService implements AclService {
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) { public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() }; Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() };
List<ObjectIdentity> objects = jdbcOperations.query(findChildrenSql, args, (rs, rowNum) -> { List<ObjectIdentity> objects = this.jdbcOperations.query(this.findChildrenSql, args, (rs, rowNum) -> {
String javaType = rs.getString("class"); String javaType = rs.getString("class");
Serializable identifier = (Serializable) rs.getObject("obj_id"); Serializable identifier = (Serializable) rs.getObject("obj_id");
identifier = aclClassIdUtils.identifierFrom(identifier, rs); identifier = this.aclClassIdUtils.identifierFrom(identifier, rs);
return new ObjectIdentityImpl(javaType, identifier); return new ObjectIdentityImpl(javaType, identifier);
}); });
@ -124,7 +124,7 @@ public class JdbcAclService implements AclService {
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids)
throws NotFoundException { throws NotFoundException {
Map<ObjectIdentity, Acl> result = lookupStrategy.readAclsById(objects, sids); Map<ObjectIdentity, Acl> result = this.lookupStrategy.readAclsById(objects, sids);
// Check every requested object identity was found (throw NotFoundException if // Check every requested object identity was found (throw NotFoundException if
// needed) // needed)
@ -163,7 +163,7 @@ public class JdbcAclService implements AclService {
} }
protected boolean isAclClassIdSupported() { protected boolean isAclClassIdSupported() {
return aclClassIdSupported; return this.aclClassIdSupported;
} }
} }

View File

@ -136,7 +136,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
if (acl.getEntries().isEmpty()) { if (acl.getEntries().isEmpty()) {
return; return;
} }
jdbcOperations.batchUpdate(insertEntry, new BatchPreparedStatementSetter() { this.jdbcOperations.batchUpdate(this.insertEntry, new BatchPreparedStatementSetter() {
public int getBatchSize() { public int getBatchSize() {
return acl.getEntries().size(); return acl.getEntries().size();
} }
@ -168,7 +168,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
protected void createObjectIdentity(ObjectIdentity object, Sid owner) { protected void createObjectIdentity(ObjectIdentity object, Sid owner) {
Long sidId = createOrRetrieveSidPrimaryKey(owner, true); Long sidId = createOrRetrieveSidPrimaryKey(owner, true);
Long classId = createOrRetrieveClassPrimaryKey(object.getType(), true, object.getIdentifier().getClass()); Long classId = createOrRetrieveClassPrimaryKey(object.getType(), true, object.getIdentifier().getClass());
jdbcOperations.update(insertObjectIdentity, classId, object.getIdentifier().toString(), sidId, Boolean.TRUE); this.jdbcOperations.update(this.insertObjectIdentity, classId, object.getIdentifier().toString(), sidId,
Boolean.TRUE);
} }
/** /**
@ -179,7 +180,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
* @return the primary key or null if not found * @return the primary key or null if not found
*/ */
protected Long createOrRetrieveClassPrimaryKey(String type, boolean allowCreate, Class idType) { protected Long createOrRetrieveClassPrimaryKey(String type, boolean allowCreate, Class idType) {
List<Long> classIds = jdbcOperations.queryForList(selectClassPrimaryKey, new Object[] { type }, Long.class); List<Long> classIds = this.jdbcOperations.queryForList(this.selectClassPrimaryKey, new Object[] { type },
Long.class);
if (!classIds.isEmpty()) { if (!classIds.isEmpty()) {
return classIds.get(0); return classIds.get(0);
@ -187,13 +189,13 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
if (allowCreate) { if (allowCreate) {
if (!isAclClassIdSupported()) { if (!isAclClassIdSupported()) {
jdbcOperations.update(insertClass, type); this.jdbcOperations.update(this.insertClass, type);
} }
else { else {
jdbcOperations.update(insertClass, type, idType.getCanonicalName()); this.jdbcOperations.update(this.insertClass, type, idType.getCanonicalName());
} }
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running");
return jdbcOperations.queryForObject(classIdentityQuery, Long.class); return this.jdbcOperations.queryForObject(this.classIdentityQuery, Long.class);
} }
return null; return null;
@ -238,17 +240,17 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*/ */
protected Long createOrRetrieveSidPrimaryKey(String sidName, boolean sidIsPrincipal, boolean allowCreate) { protected Long createOrRetrieveSidPrimaryKey(String sidName, boolean sidIsPrincipal, boolean allowCreate) {
List<Long> sidIds = jdbcOperations.queryForList(selectSidPrimaryKey, new Object[] { sidIsPrincipal, sidName }, List<Long> sidIds = this.jdbcOperations.queryForList(this.selectSidPrimaryKey,
Long.class); new Object[] { sidIsPrincipal, sidName }, Long.class);
if (!sidIds.isEmpty()) { if (!sidIds.isEmpty()) {
return sidIds.get(0); return sidIds.get(0);
} }
if (allowCreate) { if (allowCreate) {
jdbcOperations.update(insertSid, sidIsPrincipal, sidName); this.jdbcOperations.update(this.insertSid, sidIsPrincipal, sidName);
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running");
return jdbcOperations.queryForObject(sidIdentityQuery, Long.class); return this.jdbcOperations.queryForObject(this.sidIdentityQuery, Long.class);
} }
return null; return null;
@ -267,7 +269,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
} }
} }
else { else {
if (!foreignKeysInDatabase) { if (!this.foreignKeysInDatabase) {
// We need to perform a manual verification for what a FK would normally // We need to perform a manual verification for what a FK would normally
// do // 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
@ -288,7 +290,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
deleteObjectIdentity(oidPrimaryKey); deleteObjectIdentity(oidPrimaryKey);
// Clear the cache // Clear the cache
aclCache.evictFromCache(objectIdentity); this.aclCache.evictFromCache(objectIdentity);
} }
/** /**
@ -297,7 +299,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) {
jdbcOperations.update(deleteEntryByObjectIdentityForeignKey, oidPrimaryKey); this.jdbcOperations.update(this.deleteEntryByObjectIdentityForeignKey, oidPrimaryKey);
} }
/** /**
@ -310,7 +312,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*/ */
protected void deleteObjectIdentity(Long oidPrimaryKey) { protected void deleteObjectIdentity(Long oidPrimaryKey) {
// Delete the acl_object_identity row // Delete the acl_object_identity row
jdbcOperations.update(deleteObjectIdentityByPrimaryKey, oidPrimaryKey); this.jdbcOperations.update(this.deleteObjectIdentityByPrimaryKey, oidPrimaryKey);
} }
/** /**
@ -322,7 +324,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*/ */
protected Long retrieveObjectIdentityPrimaryKey(ObjectIdentity oid) { protected Long retrieveObjectIdentityPrimaryKey(ObjectIdentity oid) {
try { try {
return jdbcOperations.queryForObject(selectObjectIdentityPrimaryKey, Long.class, oid.getType(), return this.jdbcOperations.queryForObject(this.selectObjectIdentityPrimaryKey, Long.class, oid.getType(),
oid.getIdentifier().toString()); oid.getIdentifier().toString());
} }
catch (DataAccessException notFound) { catch (DataAccessException notFound) {
@ -364,7 +366,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
clearCacheIncludingChildren(child); clearCacheIncludingChildren(child);
} }
} }
aclCache.evictFromCache(objectIdentity); this.aclCache.evictFromCache(objectIdentity);
} }
/** /**
@ -388,7 +390,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
Assert.notNull(acl.getOwner(), "Owner is required in this implementation"); Assert.notNull(acl.getOwner(), "Owner is required in this implementation");
Long ownerSid = createOrRetrieveSidPrimaryKey(acl.getOwner(), true); Long ownerSid = createOrRetrieveSidPrimaryKey(acl.getOwner(), true);
int count = jdbcOperations.update(updateObjectIdentity, parentId, ownerSid, acl.isEntriesInheriting(), int count = this.jdbcOperations.update(this.updateObjectIdentity, parentId, ownerSid, acl.isEntriesInheriting(),
acl.getId()); acl.getId());
if (count != 1) { if (count != 1) {

View File

@ -27,7 +27,7 @@ public final class TargetObjectWithUUID {
private UUID id; private UUID id;
public UUID getId() { public UUID getId() {
return id; return this.id;
} }
public void setId(UUID id) { public void setId(UUID id) {

View File

@ -46,9 +46,9 @@ public class AclAuthorizationStrategyImplTests {
@Before @Before
public void setup() { public void setup() {
authority = new SimpleGrantedAuthority("ROLE_AUTH"); this.authority = new SimpleGrantedAuthority("ROLE_AUTH");
TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar", TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar",
Arrays.asList(authority)); Arrays.asList(this.authority));
authentication.setAuthenticated(true); authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
} }
@ -61,8 +61,8 @@ public class AclAuthorizationStrategyImplTests {
// gh-4085 // gh-4085
@Test @Test
public void securityCheckWhenCustomAuthorityThenNameIsUsed() { public void securityCheckWhenCustomAuthorityThenNameIsUsed() {
strategy = new AclAuthorizationStrategyImpl(new CustomAuthority()); this.strategy = new AclAuthorizationStrategyImpl(new CustomAuthority());
strategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL); this.strategy.securityCheck(this.acl, AclAuthorizationStrategy.CHANGE_GENERAL);
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
@ -70,7 +70,7 @@ public class AclAuthorizationStrategyImplTests {
@Override @Override
public String getAuthority() { public String getAuthority() {
return authority.getAuthority(); return AclAuthorizationStrategyImplTests.this.authority.getAuthority();
} }
} }

View File

@ -83,12 +83,12 @@ public class AclImplTests {
@Before @Before
public void setUp() { public void setUp() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
authzStrategy = mock(AclAuthorizationStrategy.class); this.authzStrategy = mock(AclAuthorizationStrategy.class);
mockAuditLogger = mock(AuditLogger.class); this.mockAuditLogger = mock(AuditLogger.class);
pgs = new DefaultPermissionGrantingStrategy(mockAuditLogger); this.pgs = new DefaultPermissionGrantingStrategy(this.mockAuditLogger);
auth.setAuthenticated(true); this.auth.setAuthenticated(true);
permissionFactory = new DefaultPermissionFactory(); this.permissionFactory = new DefaultPermissionFactory();
} }
@After @After
@ -99,41 +99,43 @@ public class AclImplTests {
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullObjectIdentity() { public void constructorsRejectNullObjectIdentity() {
try { try {
new AclImpl(null, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
new AclImpl(null, 1, authzStrategy, mockAuditLogger); new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger);
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullId() { public void constructorsRejectNullId() {
try { try {
new AclImpl(objectIdentity, null, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); new AclImpl(this.objectIdentity, null, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
new AclImpl(objectIdentity, null, authzStrategy, mockAuditLogger); new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullAclAuthzStrategy() { public void constructorsRejectNullAclAuthzStrategy() {
try { try {
new AclImpl(objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(mockAuditLogger), null, null, new AclImpl(this.objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null,
true, new PrincipalSid("joe")); null, true, new PrincipalSid("joe"));
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
new AclImpl(objectIdentity, 1, null, mockAuditLogger); new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger);
} }
@Test @Test
public void insertAceRejectsNullParameters() { public void insertAceRejectsNullParameters() {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
try { try {
acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true); acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
@ -150,7 +152,8 @@ public class AclImplTests {
@Test @Test
public void insertAceAddsElementAtCorrectIndex() { public void insertAceAddsElementAtCorrectIndex() {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
// Insert one permission // Insert one permission
@ -186,7 +189,8 @@ public class AclImplTests {
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void insertAceFailsForNonExistentElement() { public void insertAceFailsForNonExistentElement() {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
// Insert one permission // Insert one permission
@ -198,7 +202,8 @@ public class AclImplTests {
@Test @Test
public void deleteAceKeepsInitialOrdering() { public void deleteAceKeepsInitialOrdering() {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
// Add several permissions // Add several permissions
@ -233,7 +238,8 @@ public class AclImplTests {
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl( AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL")); new SimpleGrantedAuthority("ROLE_GENERAL"));
MutableAcl acl = new AclImpl(objectIdentity, (1), strategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
try { try {
acl.deleteAce(99); acl.deleteAce(99);
fail("It should have thrown NotFoundException"); fail("It should have thrown NotFoundException");
@ -244,7 +250,8 @@ public class AclImplTests {
@Test @Test
public void isGrantingRejectsEmptyParameters() { public void isGrantingRejectsEmptyParameters() {
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
Sid ben = new PrincipalSid("ben"); Sid ben = new PrincipalSid("ben");
try { try {
acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false); acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false);
@ -268,7 +275,8 @@ public class AclImplTests {
ObjectIdentity rootOid = new ObjectIdentityImpl(TARGET_CLASS, 100); ObjectIdentity rootOid = new ObjectIdentityImpl(TARGET_CLASS, 100);
// Create an ACL which owner is not the authenticated principal // Create an ACL which owner is not the authenticated principal
MutableAcl rootAcl = new AclImpl(rootOid, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe")); MutableAcl rootAcl = new AclImpl(rootOid, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
// Grant some permissions // Grant some permissions
rootAcl.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), false); rootAcl.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), false);
@ -314,11 +322,12 @@ public class AclImplTests {
// Create ACLs // Create ACLs
PrincipalSid joe = new PrincipalSid("joe"); PrincipalSid joe = new PrincipalSid("joe");
MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, authzStrategy, pgs, null, null, false, joe); MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, this.authzStrategy, this.pgs, null, null, false,
MutableAcl parentAcl1 = new AclImpl(parentOid1, 2, authzStrategy, pgs, null, null, true, joe); joe);
MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, authzStrategy, pgs, null, null, true, joe); MutableAcl parentAcl1 = new AclImpl(parentOid1, 2, this.authzStrategy, this.pgs, null, null, true, joe);
MutableAcl childAcl1 = new AclImpl(childOid1, 4, authzStrategy, pgs, null, null, true, joe); MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, this.authzStrategy, this.pgs, null, null, true, joe);
MutableAcl childAcl2 = new AclImpl(childOid2, 4, authzStrategy, pgs, null, null, false, joe); MutableAcl childAcl1 = new AclImpl(childOid1, 4, this.authzStrategy, this.pgs, null, null, true, joe);
MutableAcl childAcl2 = new AclImpl(childOid2, 4, this.authzStrategy, this.pgs, null, null, false, joe);
// Create hierarchies // Create hierarchies
childAcl2.setParent(childAcl1); childAcl2.setParent(childAcl1);
@ -376,7 +385,8 @@ public class AclImplTests {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL"); Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL");
auth.setAuthenticated(true); auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
@ -404,7 +414,8 @@ public class AclImplTests {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_AUDITING", "ROLE_GENERAL"); Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_AUDITING", "ROLE_GENERAL");
auth.setAuthenticated(true); auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, false, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
@ -432,8 +443,10 @@ public class AclImplTests {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, (100)); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, (100));
ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, (101)); ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, (101));
MutableAcl acl = new AclImpl(identity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); MutableAcl acl = new AclImpl(identity, 1, this.authzStrategy, this.pgs, null, null, true,
MutableAcl parentAcl = new AclImpl(identity2, 2, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); new PrincipalSid("joe"));
MutableAcl parentAcl = new AclImpl(identity2, 2, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
@ -459,7 +472,7 @@ public class AclImplTests {
@Test @Test
public void isSidLoadedBehavesAsExpected() { public void isSidLoadedBehavesAsExpected() {
List<Sid> loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED")); List<Sid> loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED"));
MutableAcl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, loadedSids, true, MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, loadedSids, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
assertThat(acl.isSidLoaded(loadedSids)).isTrue(); assertThat(acl.isSidLoaded(loadedSids)).isTrue();
@ -482,19 +495,22 @@ public class AclImplTests {
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() { public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true); acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true);
} }
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() { public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() {
AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.deleteAce(-1); acl.deleteAce(-1);
} }
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() { public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() {
AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
// Insert at zero, OK. // Insert at zero, OK.
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1 // Size is now 1
@ -504,7 +520,8 @@ public class AclImplTests {
// SEC-1151 // SEC-1151
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() { public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() {
AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, pgs, null, null, true, new PrincipalSid("joe")); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe"));
acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true);
// Size is now 1 // Size is now 1
acl.deleteAce(1); acl.deleteAce(1);
@ -513,9 +530,9 @@ public class AclImplTests {
// SEC-1795 // SEC-1795
@Test @Test
public void changingParentIsSuccessful() { public void changingParentIsSuccessful() {
AclImpl parentAcl = new AclImpl(objectIdentity, 1L, authzStrategy, mockAuditLogger); AclImpl parentAcl = new AclImpl(this.objectIdentity, 1L, this.authzStrategy, this.mockAuditLogger);
AclImpl childAcl = new AclImpl(objectIdentity, 2L, authzStrategy, mockAuditLogger); AclImpl childAcl = new AclImpl(this.objectIdentity, 2L, this.authzStrategy, this.mockAuditLogger);
AclImpl changeParentAcl = new AclImpl(objectIdentity, 3L, authzStrategy, mockAuditLogger); AclImpl changeParentAcl = new AclImpl(this.objectIdentity, 3L, this.authzStrategy, this.mockAuditLogger);
childAcl.setParent(parentAcl); childAcl.setParent(parentAcl);
childAcl.setParent(changeParentAcl); childAcl.setParent(changeParentAcl);
@ -524,10 +541,11 @@ public class AclImplTests {
// SEC-2342 // SEC-2342
@Test @Test
public void maskPermissionGrantingStrategy() { public void maskPermissionGrantingStrategy() {
DefaultPermissionGrantingStrategy maskPgs = new MaskPermissionGrantingStrategy(mockAuditLogger); DefaultPermissionGrantingStrategy maskPgs = new MaskPermissionGrantingStrategy(this.mockAuditLogger);
MockAclService service = new MockAclService(); MockAclService service = new MockAclService();
AclImpl acl = new AclImpl(objectIdentity, 1, authzStrategy, maskPgs, null, null, true, new PrincipalSid("joe")); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, maskPgs, null, null, true,
Permission permission = permissionFactory new PrincipalSid("joe"));
Permission permission = this.permissionFactory
.buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask()); .buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask());
Sid sid = new PrincipalSid("ben"); Sid sid = new PrincipalSid("ben");
acl.insertAce(0, permission, sid, true); acl.insertAce(0, permission, sid, true);

View File

@ -46,52 +46,52 @@ public class AuditLoggerTests {
@Before @Before
public void setUp() { public void setUp() {
logger = new ConsoleAuditLogger(); this.logger = new ConsoleAuditLogger();
ace = mock(AuditableAccessControlEntry.class); this.ace = mock(AuditableAccessControlEntry.class);
console = System.out; this.console = System.out;
System.setOut(new PrintStream(bytes)); System.setOut(new PrintStream(this.bytes));
} }
@After @After
public void tearDown() { public void tearDown() {
System.setOut(console); System.setOut(this.console);
bytes.reset(); this.bytes.reset();
} }
@Test @Test
public void nonAuditableAceIsIgnored() { public void nonAuditableAceIsIgnored() {
AccessControlEntry ace = mock(AccessControlEntry.class); AccessControlEntry ace = mock(AccessControlEntry.class);
logger.logIfNeeded(true, ace); this.logger.logIfNeeded(true, ace);
assertThat(bytes.size()).isZero(); assertThat(this.bytes.size()).isZero();
} }
@Test @Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() { public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() {
when(ace.isAuditSuccess()).thenReturn(false); when(this.ace.isAuditSuccess()).thenReturn(false);
logger.logIfNeeded(true, ace); this.logger.logIfNeeded(true, this.ace);
assertThat(bytes.size()).isZero(); assertThat(this.bytes.size()).isZero();
} }
@Test @Test
public void successIsLoggedIfAceRequiresSuccessAudit() { public void successIsLoggedIfAceRequiresSuccessAudit() {
when(ace.isAuditSuccess()).thenReturn(true); when(this.ace.isAuditSuccess()).thenReturn(true);
logger.logIfNeeded(true, ace); this.logger.logIfNeeded(true, this.ace);
assertThat(bytes.toString()).startsWith("GRANTED due to ACE"); assertThat(this.bytes.toString()).startsWith("GRANTED due to ACE");
} }
@Test @Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() { public void failureIsntLoggedIfAceDoesntRequireFailureAudit() {
when(ace.isAuditFailure()).thenReturn(false); when(this.ace.isAuditFailure()).thenReturn(false);
logger.logIfNeeded(false, ace); this.logger.logIfNeeded(false, this.ace);
assertThat(bytes.size()).isZero(); assertThat(this.bytes.size()).isZero();
} }
@Test @Test
public void failureIsLoggedIfAceRequiresFailureAudit() { public void failureIsLoggedIfAceRequiresFailureAudit() {
when(ace.isAuditFailure()).thenReturn(true); when(this.ace.isAuditFailure()).thenReturn(true);
logger.logIfNeeded(false, ace); this.logger.logIfNeeded(false, this.ace);
assertThat(bytes.toString()).startsWith("DENIED due to ACE"); assertThat(this.bytes.toString()).startsWith("DENIED due to ACE");
} }
} }

View File

@ -179,7 +179,7 @@ public class ObjectIdentityImplTests {
private Object id; private Object id;
public Object getId() { public Object getId() {
return id; return this.id;
} }
public void setId(Object id) { public void setId(Object id) {
@ -193,7 +193,7 @@ public class ObjectIdentityImplTests {
private Object id; private Object id;
public Object getId() { public Object getId() {
return id; return this.id;
} }
public void setId(Object id) { public void setId(Object id) {

View File

@ -47,7 +47,7 @@ public class ObjectIdentityRetrievalStrategyImplTests {
private Object id; private Object id;
public Object getId() { public Object getId() {
return id; return this.id;
} }
public void setId(Object id) { public void setId(Object id) {

View File

@ -33,12 +33,12 @@ public class PermissionTests {
@Before @Before
public void createPermissionfactory() { public void createPermissionfactory() {
permissionFactory = new DefaultPermissionFactory(); this.permissionFactory = new DefaultPermissionFactory();
} }
@Test @Test
public void basePermissionTest() { public void basePermissionTest() {
Permission p = permissionFactory.buildFromName("WRITE"); Permission p = this.permissionFactory.buildFromName("WRITE");
assertThat(p).isNotNull(); assertThat(p).isNotNull();
} }
@ -54,13 +54,13 @@ public class PermissionTests {
@Test @Test
public void fromInteger() { public void fromInteger() {
Permission permission = permissionFactory.buildFromMask(7); Permission permission = this.permissionFactory.buildFromMask(7);
permission = permissionFactory.buildFromMask(4); permission = this.permissionFactory.buildFromMask(4);
} }
@Test @Test
public void stringConversion() { public void stringConversion() {
permissionFactory.registerPublicPermissions(SpecialPermission.class); this.permissionFactory.registerPublicPermissions(SpecialPermission.class);
assertThat(BasePermission.READ.toString()).isEqualTo("BasePermission[...............................R=1]"); assertThat(BasePermission.READ.toString()).isEqualTo("BasePermission[...............................R=1]");

View File

@ -109,9 +109,9 @@ public abstract class AbstractBasicLookupStrategyTests {
@Before @Before
public void initializeBeans() { public void initializeBeans() {
strategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(), this.strategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger())); new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
strategy.setPermissionFactory(new DefaultPermissionFactory()); this.strategy.setPermissionFactory(new DefaultPermissionFactory());
} }
protected AclAuthorizationStrategy aclAuthStrategy() { protected AclAuthorizationStrategy aclAuthStrategy() {
@ -159,7 +159,7 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L);
// Objects were put in cache // Objects were put in cache
strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null); this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
// Let's empty the database to force acls retrieval from cache // Let's empty the database to force acls retrieval from cache
emptyDatabase(); emptyDatabase();
@ -299,8 +299,8 @@ public abstract class AbstractBasicLookupStrategyTests {
List<Sid> sids = Arrays.asList(BEN_SID); List<Sid> sids = Arrays.asList(BEN_SID);
List<ObjectIdentity> childOids = Arrays.asList(childOid); List<ObjectIdentity> childOids = Arrays.asList(childOid);
strategy.setBatchSize(6); this.strategy.setBatchSize(6);
Map<ObjectIdentity, Acl> foundAcls = strategy.readAclsById(childOids, sids); Map<ObjectIdentity, Acl> foundAcls = this.strategy.readAclsById(childOids, sids);
Acl foundChildAcl = foundAcls.get(childOid); Acl foundChildAcl = foundAcls.get(childOid);
assertThat(foundChildAcl).isNotNull(); assertThat(foundChildAcl).isNotNull();
@ -313,7 +313,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// cache // cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid); List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try { try {
foundAcls = strategy.readAclsById(allOids, sids); foundAcls = this.strategy.readAclsById(allOids, sids);
} }
catch (NotFoundException notExpected) { catch (NotFoundException notExpected) {
@ -333,12 +333,12 @@ public abstract class AbstractBasicLookupStrategyTests {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
} }
@Test @Test
public void testCreatePrincipalSid() { public void testCreatePrincipalSid() {
Sid result = strategy.createSid(true, "sid"); Sid result = this.strategy.createSid(true, "sid");
assertThat(result.getClass()).isEqualTo(PrincipalSid.class); assertThat(result.getClass()).isEqualTo(PrincipalSid.class);
assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid"); assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid");
@ -346,7 +346,7 @@ public abstract class AbstractBasicLookupStrategyTests {
@Test @Test
public void testCreateGrantedAuthority() { public void testCreateGrantedAuthority() {
Sid result = strategy.createSid(false, "sid"); Sid result = this.strategy.createSid(false, "sid");
assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class); assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class);
assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid"); assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid");

View File

@ -56,13 +56,13 @@ public class AclClassIdUtilsTests {
@Before @Before
public void setUp() { public void setUp() {
aclClassIdUtils = new AclClassIdUtils(); this.aclClassIdUtils = new AclClassIdUtils();
} }
@Test @Test
public void shouldReturnLongIfIdentifierIsLong() throws SQLException { public void shouldReturnLongIfIdentifierIsLong() throws SQLException {
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -71,7 +71,7 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongIfIdentifierIsBigInteger() throws SQLException { public void shouldReturnLongIfIdentifierIsBigInteger() throws SQLException {
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(BIGINT_IDENTIFIER, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(BIGINT_IDENTIFIER, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -80,10 +80,10 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongIfClassIdTypeIsNull() throws SQLException { public void shouldReturnLongIfClassIdTypeIsNull() throws SQLException {
// given // given
given(resultSet.getString("class_id_type")).willReturn(null); given(this.resultSet.getString("class_id_type")).willReturn(null);
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -92,10 +92,10 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongIfNoClassIdTypeColumn() throws SQLException { public void shouldReturnLongIfNoClassIdTypeColumn() throws SQLException {
// given // given
given(resultSet.getString("class_id_type")).willThrow(SQLException.class); given(this.resultSet.getString("class_id_type")).willThrow(SQLException.class);
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -104,10 +104,10 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongIfTypeClassNotFound() throws SQLException { public void shouldReturnLongIfTypeClassNotFound() throws SQLException {
// given // given
given(resultSet.getString("class_id_type")).willReturn("com.example.UnknownType"); given(this.resultSet.getString("class_id_type")).willReturn("com.example.UnknownType");
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -116,12 +116,12 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongEvenIfCustomConversionServiceDoesNotSupportLongConversion() throws SQLException { public void shouldReturnLongEvenIfCustomConversionServiceDoesNotSupportLongConversion() throws SQLException {
// given // given
given(resultSet.getString("class_id_type")).willReturn("java.lang.Long"); given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long");
given(conversionService.canConvert(String.class, Long.class)).willReturn(false); given(this.conversionService.canConvert(String.class, Long.class)).willReturn(false);
aclClassIdUtils.setConversionService(conversionService); this.aclClassIdUtils.setConversionService(this.conversionService);
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -130,10 +130,10 @@ public class AclClassIdUtilsTests {
@Test @Test
public void shouldReturnLongWhenLongClassIdType() throws SQLException { public void shouldReturnLongWhenLongClassIdType() throws SQLException {
// given // given
given(resultSet.getString("class_id_type")).willReturn("java.lang.Long"); given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long");
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER);
@ -143,10 +143,10 @@ public class AclClassIdUtilsTests {
public void shouldReturnUUIDWhenUUIDClassIdType() throws SQLException { public void shouldReturnUUIDWhenUUIDClassIdType() throws SQLException {
// given // given
UUID identifier = UUID.randomUUID(); UUID identifier = UUID.randomUUID();
given(resultSet.getString("class_id_type")).willReturn("java.util.UUID"); given(this.resultSet.getString("class_id_type")).willReturn("java.util.UUID");
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(identifier.toString(), resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier.toString(), this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(identifier); assertThat(newIdentifier).isEqualTo(identifier);
@ -156,10 +156,10 @@ public class AclClassIdUtilsTests {
public void shouldReturnStringWhenStringClassIdType() throws SQLException { public void shouldReturnStringWhenStringClassIdType() throws SQLException {
// given // given
String identifier = "MY_STRING_IDENTIFIER"; String identifier = "MY_STRING_IDENTIFIER";
given(resultSet.getString("class_id_type")).willReturn("java.lang.String"); given(this.resultSet.getString("class_id_type")).willReturn("java.lang.String");
// when // when
Serializable newIdentifier = aclClassIdUtils.identifierFrom(identifier, resultSet); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier, this.resultSet);
// then // then
assertThat(newIdentifier).isEqualTo(identifier); assertThat(newIdentifier).isEqualTo(identifier);
@ -174,7 +174,7 @@ public class AclClassIdUtilsTests {
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNullConversionServiceInSetter() { public void shouldNotAcceptNullConversionServiceInSetter() {
// when // when
aclClassIdUtils.setConversionService(null); this.aclClassIdUtils.setConversionService(null);
} }
} }

View File

@ -50,7 +50,7 @@ public class BasicLookupStrategyTestsDbHelper {
// Use a different connection url so the tests can run in parallel // Use a different connection url so the tests can run in parallel
String connectionUrl; String connectionUrl;
String sqlClassPathResource; String sqlClassPathResource;
if (!withAclClassIdType) { if (!this.withAclClassIdType) {
connectionUrl = "jdbc:hsqldb:mem:lookupstrategytest"; connectionUrl = "jdbc:hsqldb:mem:lookupstrategytest";
sqlClassPathResource = ACL_SCHEMA_SQL_FILE; sqlClassPathResource = ACL_SCHEMA_SQL_FILE;
} }
@ -59,21 +59,21 @@ public class BasicLookupStrategyTestsDbHelper {
sqlClassPathResource = ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID; sqlClassPathResource = ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID;
} }
dataSource = new SingleConnectionDataSource(connectionUrl, "sa", "", true); this.dataSource = new SingleConnectionDataSource(connectionUrl, "sa", "", true);
dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); this.dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
jdbcTemplate = new JdbcTemplate(dataSource); this.jdbcTemplate = new JdbcTemplate(this.dataSource);
Resource resource = new ClassPathResource(sqlClassPathResource); Resource resource = new ClassPathResource(sqlClassPathResource);
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
jdbcTemplate.execute(sql); this.jdbcTemplate.execute(sql);
} }
public JdbcTemplate getJdbcTemplate() { public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate; return this.jdbcTemplate;
} }
public SingleConnectionDataSource getDataSource() { public SingleConnectionDataSource getDataSource() {
return dataSource; return this.dataSource;
} }
} }

View File

@ -70,11 +70,11 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Before @Before
public void initializeBeans() { public void initializeBeans() {
super.initializeBeans(); super.initializeBeans();
uuidEnabledStrategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(), this.uuidEnabledStrategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(),
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger())); new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()));
uuidEnabledStrategy.setPermissionFactory(new DefaultPermissionFactory()); this.uuidEnabledStrategy.setPermissionFactory(new DefaultPermissionFactory());
uuidEnabledStrategy.setAclClassIdSupported(true); this.uuidEnabledStrategy.setAclClassIdSupported(true);
uuidEnabledStrategy.setConversionService(new DefaultConversionService()); this.uuidEnabledStrategy.setConversionService(new DefaultConversionService());
} }
@Before @Before
@ -93,7 +93,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Test @Test
public void testReadObjectIdentityUsingUuidType() { public void testReadObjectIdentityUsingUuidType() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_UUID); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_UUID);
Map<ObjectIdentity, Acl> foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
Arrays.asList(BEN_SID)); Arrays.asList(BEN_SID));
Assert.assertEquals(1, foundAcls.size()); Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid)); Assert.assertNotNull(foundAcls.get(oid));
@ -102,7 +102,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Test @Test
public void testReadObjectIdentityUsingLongTypeWithConversionServiceEnabled() { public void testReadObjectIdentityUsingLongTypeWithConversionServiceEnabled() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
Map<ObjectIdentity, Acl> foundAcls = uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid),
Arrays.asList(BEN_SID)); Arrays.asList(BEN_SID));
Assert.assertEquals(1, foundAcls.size()); Assert.assertEquals(1, foundAcls.size());
Assert.assertNotNull(foundAcls.get(oid)); Assert.assertNotNull(foundAcls.get(oid));
@ -111,7 +111,7 @@ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLooku
@Test(expected = ConversionFailedException.class) @Test(expected = ConversionFailedException.class)
public void testReadObjectIdentityUsingNonUuidInDatabase() { public void testReadObjectIdentityUsingNonUuidInDatabase() {
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID);
uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID));
} }
} }

View File

@ -78,7 +78,8 @@ public class EhCacheBasedAclCacheTests {
@Before @Before
public void setup() { public void setup() {
myCache = new EhCacheBasedAclCache(cache, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), this.myCache = new EhCacheBasedAclCache(this.cache,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()),
new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER")));
ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L);
@ -86,7 +87,7 @@ public class EhCacheBasedAclCacheTests {
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL")); new SimpleGrantedAuthority("ROLE_GENERAL"));
acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); this.acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
} }
@After @After
@ -104,7 +105,7 @@ public class EhCacheBasedAclCacheTests {
public void methodsRejectNullParameters() { public void methodsRejectNullParameters() {
try { try {
Serializable id = null; Serializable id = null;
myCache.evictFromCache(id); this.myCache.evictFromCache(id);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -112,7 +113,7 @@ public class EhCacheBasedAclCacheTests {
try { try {
ObjectIdentity obj = null; ObjectIdentity obj = null;
myCache.evictFromCache(obj); this.myCache.evictFromCache(obj);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -120,7 +121,7 @@ public class EhCacheBasedAclCacheTests {
try { try {
Serializable id = null; Serializable id = null;
myCache.getFromCache(id); this.myCache.getFromCache(id);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -128,7 +129,7 @@ public class EhCacheBasedAclCacheTests {
try { try {
ObjectIdentity obj = null; ObjectIdentity obj = null;
myCache.getFromCache(obj); this.myCache.getFromCache(obj);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -136,7 +137,7 @@ public class EhCacheBasedAclCacheTests {
try { try {
MutableAcl acl = null; MutableAcl acl = null;
myCache.putInCache(acl); this.myCache.putInCache(acl);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -150,7 +151,7 @@ public class EhCacheBasedAclCacheTests {
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(this.acl);
oos.close(); oos.close();
FileInputStream fis = new FileInputStream(file); FileInputStream fis = new FileInputStream(file);
@ -158,7 +159,7 @@ public class EhCacheBasedAclCacheTests {
MutableAcl retrieved = (MutableAcl) ois.readObject(); MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close(); ois.close();
assertThat(retrieved).isEqualTo(acl); assertThat(retrieved).isEqualTo(this.acl);
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved); Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
assertThat(retrieved1).isNull(); assertThat(retrieved1).isNull();
@ -169,20 +170,20 @@ public class EhCacheBasedAclCacheTests {
@Test @Test
public void clearCache() { public void clearCache() {
myCache.clearCache(); this.myCache.clearCache();
verify(cache).removeAll(); verify(this.cache).removeAll();
} }
@Test @Test
public void putInCache() { public void putInCache() {
myCache.putInCache(acl); this.myCache.putInCache(this.acl);
verify(cache, times(2)).put(element.capture()); verify(this.cache, times(2)).put(this.element.capture());
assertThat(element.getValue().getKey()).isEqualTo(acl.getId()); assertThat(this.element.getValue().getKey()).isEqualTo(this.acl.getId());
assertThat(element.getValue().getObjectValue()).isEqualTo(acl); assertThat(this.element.getValue().getObjectValue()).isEqualTo(this.acl);
assertThat(element.getAllValues().get(0).getKey()).isEqualTo(acl.getObjectIdentity()); assertThat(this.element.getAllValues().get(0).getKey()).isEqualTo(this.acl.getObjectIdentity());
assertThat(element.getAllValues().get(0).getObjectValue()).isEqualTo(acl); assertThat(this.element.getAllValues().get(0).getObjectValue()).isEqualTo(this.acl);
} }
@Test @Test
@ -196,13 +197,13 @@ public class EhCacheBasedAclCacheTests {
new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"),
new SimpleGrantedAuthority("ROLE_GENERAL")); new SimpleGrantedAuthority("ROLE_GENERAL"));
MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger());
acl.setParent(parentAcl); this.acl.setParent(parentAcl);
myCache.putInCache(acl); this.myCache.putInCache(this.acl);
verify(cache, times(4)).put(element.capture()); verify(this.cache, times(4)).put(this.element.capture());
List<Element> allValues = element.getAllValues(); List<Element> allValues = this.element.getAllValues();
assertThat(allValues.get(0).getKey()).isEqualTo(parentAcl.getObjectIdentity()); assertThat(allValues.get(0).getKey()).isEqualTo(parentAcl.getObjectIdentity());
assertThat(allValues.get(0).getObjectValue()).isEqualTo(parentAcl); assertThat(allValues.get(0).getObjectValue()).isEqualTo(parentAcl);
@ -210,30 +211,30 @@ public class EhCacheBasedAclCacheTests {
assertThat(allValues.get(1).getKey()).isEqualTo(parentAcl.getId()); assertThat(allValues.get(1).getKey()).isEqualTo(parentAcl.getId());
assertThat(allValues.get(1).getObjectValue()).isEqualTo(parentAcl); assertThat(allValues.get(1).getObjectValue()).isEqualTo(parentAcl);
assertThat(allValues.get(2).getKey()).isEqualTo(acl.getObjectIdentity()); assertThat(allValues.get(2).getKey()).isEqualTo(this.acl.getObjectIdentity());
assertThat(allValues.get(2).getObjectValue()).isEqualTo(acl); assertThat(allValues.get(2).getObjectValue()).isEqualTo(this.acl);
assertThat(allValues.get(3).getKey()).isEqualTo(acl.getId()); assertThat(allValues.get(3).getKey()).isEqualTo(this.acl.getId());
assertThat(allValues.get(3).getObjectValue()).isEqualTo(acl); assertThat(allValues.get(3).getObjectValue()).isEqualTo(this.acl);
} }
@Test @Test
public void getFromCacheSerializable() { public void getFromCacheSerializable() {
when(cache.get(acl.getId())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
assertThat(myCache.getFromCache(acl.getId())).isEqualTo(acl); assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
} }
@Test @Test
public void getFromCacheSerializablePopulatesTransient() { public void getFromCacheSerializablePopulatesTransient() {
when(cache.get(acl.getId())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
myCache.putInCache(acl); this.myCache.putInCache(this.acl);
ReflectionTestUtils.setField(acl, "permissionGrantingStrategy", null); ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null);
ReflectionTestUtils.setField(acl, "aclAuthorizationStrategy", null); ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null);
MutableAcl fromCache = myCache.getFromCache(acl.getId()); MutableAcl fromCache = this.myCache.getFromCache(this.acl.getId());
assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull(); assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull(); assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
@ -241,21 +242,21 @@ public class EhCacheBasedAclCacheTests {
@Test @Test
public void getFromCacheObjectIdentity() { public void getFromCacheObjectIdentity() {
when(cache.get(acl.getId())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
assertThat(myCache.getFromCache(acl.getId())).isEqualTo(acl); assertThat(this.myCache.getFromCache(this.acl.getId())).isEqualTo(this.acl);
} }
@Test @Test
public void getFromCacheObjectIdentityPopulatesTransient() { public void getFromCacheObjectIdentityPopulatesTransient() {
when(cache.get(acl.getObjectIdentity())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getObjectIdentity())).thenReturn(new Element(this.acl.getId(), this.acl));
myCache.putInCache(acl); this.myCache.putInCache(this.acl);
ReflectionTestUtils.setField(acl, "permissionGrantingStrategy", null); ReflectionTestUtils.setField(this.acl, "permissionGrantingStrategy", null);
ReflectionTestUtils.setField(acl, "aclAuthorizationStrategy", null); ReflectionTestUtils.setField(this.acl, "aclAuthorizationStrategy", null);
MutableAcl fromCache = myCache.getFromCache(acl.getObjectIdentity()); MutableAcl fromCache = this.myCache.getFromCache(this.acl.getObjectIdentity());
assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull(); assertThat(ReflectionTestUtils.getField(fromCache, "aclAuthorizationStrategy")).isNotNull();
assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull(); assertThat(ReflectionTestUtils.getField(fromCache, "permissionGrantingStrategy")).isNotNull();
@ -263,22 +264,22 @@ public class EhCacheBasedAclCacheTests {
@Test @Test
public void evictCacheSerializable() { public void evictCacheSerializable() {
when(cache.get(acl.getObjectIdentity())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getObjectIdentity())).thenReturn(new Element(this.acl.getId(), this.acl));
myCache.evictFromCache(acl.getObjectIdentity()); this.myCache.evictFromCache(this.acl.getObjectIdentity());
verify(cache).remove(acl.getId()); verify(this.cache).remove(this.acl.getId());
verify(cache).remove(acl.getObjectIdentity()); verify(this.cache).remove(this.acl.getObjectIdentity());
} }
@Test @Test
public void evictCacheObjectIdentity() { public void evictCacheObjectIdentity() {
when(cache.get(acl.getId())).thenReturn(new Element(acl.getId(), acl)); when(this.cache.get(this.acl.getId())).thenReturn(new Element(this.acl.getId(), this.acl));
myCache.evictFromCache(acl.getId()); this.myCache.evictFromCache(this.acl.getId());
verify(cache).remove(acl.getId()); verify(this.cache).remove(this.acl.getId());
verify(cache).remove(acl.getObjectIdentity()); verify(this.cache).remove(this.acl.getObjectIdentity());
} }
} }

View File

@ -74,30 +74,30 @@ public class JdbcAclServiceTests {
@Before @Before
public void setUp() { public void setUp() {
aclService = new JdbcAclService(jdbcOperations, lookupStrategy); this.aclService = new JdbcAclService(this.jdbcOperations, this.lookupStrategy);
aclServiceIntegration = new JdbcAclService(embeddedDatabase, lookupStrategy); this.aclServiceIntegration = new JdbcAclService(this.embeddedDatabase, this.lookupStrategy);
} }
@Before @Before
public void setUpEmbeddedDatabase() { public void setUpEmbeddedDatabase() {
embeddedDatabase = new EmbeddedDatabaseBuilder()// this.embeddedDatabase = new EmbeddedDatabaseBuilder()//
.addScript("createAclSchemaWithAclClassIdType.sql").addScript("db/sql/test_data_hierarchy.sql").build(); .addScript("createAclSchemaWithAclClassIdType.sql").addScript("db/sql/test_data_hierarchy.sql").build();
} }
@After @After
public void tearDownEmbeddedDatabase() { public void tearDownEmbeddedDatabase() {
embeddedDatabase.shutdown(); this.embeddedDatabase.shutdown();
} }
// SEC-1898 // SEC-1898
@Test(expected = NotFoundException.class) @Test(expected = NotFoundException.class)
public void readAclByIdMissingAcl() { public void readAclByIdMissingAcl() {
Map<ObjectIdentity, Acl> result = new HashMap<>(); Map<ObjectIdentity, Acl> result = new HashMap<>();
when(lookupStrategy.readAclsById(anyList(), anyList())).thenReturn(result); when(this.lookupStrategy.readAclsById(anyList(), anyList())).thenReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1); ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1);
List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user")); List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user"));
aclService.readAclById(objectIdentity, sids); this.aclService.readAclById(objectIdentity, sids);
} }
@Test @Test
@ -105,10 +105,10 @@ public class JdbcAclServiceTests {
List<ObjectIdentity> result = new ArrayList<>(); List<ObjectIdentity> result = new ArrayList<>();
result.add(new ObjectIdentityImpl(Object.class, "5577")); result.add(new ObjectIdentityImpl(Object.class, "5577"));
Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" }; Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" };
when(jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).thenReturn(result); when(this.jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).thenReturn(result);
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = aclService.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577");
} }
@ -117,7 +117,7 @@ public class JdbcAclServiceTests {
public void findNoChildren() { public void findNoChildren() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = aclService.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities).isNull(); assertThat(objectIdentities).isNull();
} }
@ -125,7 +125,7 @@ public class JdbcAclServiceTests {
public void findChildrenWithoutIdType() { public void findChildrenWithoutIdType() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L);
List<ObjectIdentity> objectIdentities = aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L);
@ -135,7 +135,7 @@ public class JdbcAclServiceTests {
public void findChildrenForUnknownObject() { public void findChildrenForUnknownObject() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 33); ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 33);
List<ObjectIdentity> objectIdentities = aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities).isNull(); assertThat(objectIdentities).isNull();
} }
@ -143,7 +143,7 @@ public class JdbcAclServiceTests {
public void findChildrenOfIdTypeLong() { public void findChildrenOfIdTypeLong() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL");
List<ObjectIdentity> objectIdentities = aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(2); assertThat(objectIdentities.size()).isEqualTo(2);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L);
@ -155,8 +155,8 @@ public class JdbcAclServiceTests {
public void findChildrenOfIdTypeString() { public void findChildrenOfIdTypeString() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); assertThat(objectIdentities.get(0).getType()).isEqualTo("location");
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL");
@ -166,8 +166,8 @@ public class JdbcAclServiceTests {
public void findChildrenOfIdTypeUUID() { public void findChildrenOfIdTypeUUID() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L);
aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.size()).isEqualTo(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter"); assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter");
assertThat(objectIdentities.get(0).getIdentifier()) assertThat(objectIdentities.get(0).getIdentifier())
@ -179,7 +179,7 @@ public class JdbcAclServiceTests {
private Object id; private Object id;
public Object getId() { public Object getId() {
return id; return this.id;
} }
public void setId(Object id) { public void setId(Object id) {
@ -193,7 +193,7 @@ public class JdbcAclServiceTests {
private Object id; private Object id;
public Object getId() { public Object getId() {
return id; return this.id;
} }
public void setId(Object id) { public void setId(Object id) {

View File

@ -99,15 +99,15 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
} }
protected ObjectIdentity getTopParentOid() { protected ObjectIdentity getTopParentOid() {
return topParentOid; return this.topParentOid;
} }
protected ObjectIdentity getMiddleParentOid() { protected ObjectIdentity getMiddleParentOid() {
return middleParentOid; return this.middleParentOid;
} }
protected ObjectIdentity getChildOid() { protected ObjectIdentity getChildOid() {
return childOid; return this.childOid;
} }
protected String getTargetClass() { protected String getTargetClass() {
@ -117,7 +117,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@BeforeTransaction @BeforeTransaction
public void createTables() throws Exception { public void createTables() throws Exception {
try { try {
new DatabaseSeeder(dataSource, new ClassPathResource(getSqlClassPathResource())); new DatabaseSeeder(this.dataSource, new ClassPathResource(getSqlClassPathResource()));
// new DatabaseSeeder(dataSource, new // new DatabaseSeeder(dataSource, new
// ClassPathResource("createAclSchemaPostgres.sql")); // ClassPathResource("createAclSchemaPostgres.sql"));
} }
@ -130,39 +130,39 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@AfterTransaction @AfterTransaction
public void clearContextAndData() { public void clearContextAndData() {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
jdbcTemplate.execute("drop table acl_entry"); this.jdbcTemplate.execute("drop table acl_entry");
jdbcTemplate.execute("drop table acl_object_identity"); this.jdbcTemplate.execute("drop table acl_object_identity");
jdbcTemplate.execute("drop table acl_class"); this.jdbcTemplate.execute("drop table acl_class");
jdbcTemplate.execute("drop table acl_sid"); this.jdbcTemplate.execute("drop table acl_sid");
aclCache.clearCache(); this.aclCache.clearCache();
} }
@Test @Test
@Transactional @Transactional
public void testLifecycle() { public void testLifecycle() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
MutableAcl topParent = jdbcMutableAclService.createAcl(getTopParentOid()); MutableAcl topParent = this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl middleParent = jdbcMutableAclService.createAcl(getMiddleParentOid()); MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
MutableAcl child = jdbcMutableAclService.createAcl(getChildOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
// Specify the inheritance hierarchy // Specify the inheritance hierarchy
middleParent.setParent(topParent); middleParent.setParent(topParent);
child.setParent(middleParent); child.setParent(middleParent);
// Now let's add a couple of permissions // Now let's add a couple of permissions
topParent.insertAce(0, BasePermission.READ, new PrincipalSid(auth), true); topParent.insertAce(0, BasePermission.READ, new PrincipalSid(this.auth), true);
topParent.insertAce(1, BasePermission.WRITE, new PrincipalSid(auth), false); topParent.insertAce(1, BasePermission.WRITE, new PrincipalSid(this.auth), false);
middleParent.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), true); middleParent.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), true);
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), false); child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false);
// Explicitly save the changed ACL // Explicitly save the changed ACL
jdbcMutableAclService.updateAcl(topParent); this.jdbcMutableAclService.updateAcl(topParent);
jdbcMutableAclService.updateAcl(middleParent); this.jdbcMutableAclService.updateAcl(middleParent);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
// Let's check if we can read them back correctly // Let's check if we can read them back correctly
Map<ObjectIdentity, Acl> map = jdbcMutableAclService Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService
.readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid())); .readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid()));
assertThat(map).hasSize(3); assertThat(map).hasSize(3);
@ -190,7 +190,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
List<Permission> read = Arrays.asList(BasePermission.READ); List<Permission> read = Arrays.asList(BasePermission.READ);
List<Permission> write = Arrays.asList(BasePermission.WRITE); List<Permission> write = Arrays.asList(BasePermission.WRITE);
List<Permission> delete = Arrays.asList(BasePermission.DELETE); List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(auth)); List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth));
assertThat(topParent.isGranted(read, pSid, false)).isTrue(); assertThat(topParent.isGranted(read, pSid, false)).isTrue();
assertThat(topParent.isGranted(write, pSid, false)).isFalse(); assertThat(topParent.isGranted(write, pSid, false)).isFalse();
@ -212,8 +212,8 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
// Next change the child so it doesn't inherit permissions from above // Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false); child.setEntriesInheriting(false);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) jdbcMutableAclService.readAclById(getChildOid()); child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.isEntriesInheriting()).isFalse(); assertThat(child.isEntriesInheriting()).isFalse();
// Check the child permissions no longer inherit // Check the child permissions no longer inherit
@ -237,14 +237,14 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
// Let's add an identical permission to the child, but it'll appear AFTER the // Let's add an identical permission to the child, but it'll appear AFTER the
// current permission, so has no impact // current permission, so has no impact
child.insertAce(1, BasePermission.DELETE, new PrincipalSid(auth), true); child.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
// Let's also add another permission to the child // Let's also add another permission to the child
child.insertAce(2, BasePermission.CREATE, new PrincipalSid(auth), true); child.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true);
// Save the changed child // Save the changed child
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) jdbcMutableAclService.readAclById(getChildOid()); child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.getEntries()).hasSize(3); assertThat(child.getEntries()).hasSize(3);
// Output permissions // Output permissions
@ -262,7 +262,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
// non-granting // non-granting
AccessControlEntry entry = child.getEntries().get(0); AccessControlEntry entry = child.getEntries().get(0);
assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask()); assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask());
assertThat(entry.getSid()).isEqualTo(new PrincipalSid(auth)); assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth));
assertThat(entry.isGranting()).isFalse(); assertThat(entry.isGranting()).isFalse();
assertThat(entry.getId()).isNotNull(); assertThat(entry.getId()).isNotNull();
@ -270,7 +270,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
child.deleteAce(0); child.deleteAce(0);
// Save and check it worked // Save and check it worked
child = jdbcMutableAclService.updateAcl(child); child = this.jdbcMutableAclService.updateAcl(child);
assertThat(child.getEntries()).hasSize(2); assertThat(child.getEntries()).hasSize(2);
assertThat(child.isGranted(delete, pSid, false)).isTrue(); assertThat(child.isGranted(delete, pSid, false)).isTrue();
@ -283,38 +283,38 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
@Transactional @Transactional
public void deleteAclAlsoDeletesChildren() { public void deleteAclAlsoDeletesChildren() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
jdbcMutableAclService.createAcl(getTopParentOid()); this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl middleParent = jdbcMutableAclService.createAcl(getMiddleParentOid()); MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
MutableAcl child = jdbcMutableAclService.createAcl(getChildOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
child.setParent(middleParent); child.setParent(middleParent);
jdbcMutableAclService.updateAcl(middleParent); this.jdbcMutableAclService.updateAcl(middleParent);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
// Check the childOid really is a child of middleParentOid // Check the childOid really is a child of middleParentOid
Acl childAcl = jdbcMutableAclService.readAclById(getChildOid()); Acl childAcl = this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Delete the mid-parent and test if the child was deleted, as well // Delete the mid-parent and test if the child was deleted, as well
jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true); this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true);
try { try {
jdbcMutableAclService.readAclById(getMiddleParentOid()); this.jdbcMutableAclService.readAclById(getMiddleParentOid());
fail("It should have thrown NotFoundException"); fail("It should have thrown NotFoundException");
} }
catch (NotFoundException expected) { catch (NotFoundException expected) {
} }
try { try {
jdbcMutableAclService.readAclById(getChildOid()); this.jdbcMutableAclService.readAclById(getChildOid());
fail("It should have thrown NotFoundException"); fail("It should have thrown NotFoundException");
} }
catch (NotFoundException expected) { catch (NotFoundException expected) {
} }
Acl acl = jdbcMutableAclService.readAclById(getTopParentOid()); Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid());
assertThat(acl).isNotNull(); assertThat(acl).isNotNull();
assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity()); assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity());
} }
@ -322,21 +322,21 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
public void constructorRejectsNullParameters() { public void constructorRejectsNullParameters() {
try { try {
new JdbcMutableAclService(null, lookupStrategy, aclCache); new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new JdbcMutableAclService(dataSource, null, aclCache); new JdbcMutableAclService(this.dataSource, null, this.aclCache);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new JdbcMutableAclService(dataSource, lookupStrategy, null); new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -346,7 +346,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
public void createAclRejectsNullParameter() { public void createAclRejectsNullParameter() {
try { try {
jdbcMutableAclService.createAcl(null); this.jdbcMutableAclService.createAcl(null);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -356,12 +356,12 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
@Transactional @Transactional
public void createAclForADuplicateDomainObject() { public void createAclForADuplicateDomainObject() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
jdbcMutableAclService.createAcl(duplicateOid); this.jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time // Try to add the same object second time
try { try {
jdbcMutableAclService.createAcl(duplicateOid); this.jdbcMutableAclService.createAcl(duplicateOid);
fail("It should have thrown AlreadyExistsException"); fail("It should have thrown AlreadyExistsException");
} }
catch (AlreadyExistsException expected) { catch (AlreadyExistsException expected) {
@ -372,7 +372,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Transactional @Transactional
public void deleteAclRejectsNullParameters() { public void deleteAclRejectsNullParameters() {
try { try {
jdbcMutableAclService.deleteAcl(null, true); this.jdbcMutableAclService.deleteAcl(null, true);
fail("It should have thrown IllegalArgumentException"); fail("It should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -382,25 +382,25 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
@Transactional @Transactional
public void deleteAclWithChildrenThrowsException() { public void deleteAclWithChildrenThrowsException() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
MutableAcl parent = jdbcMutableAclService.createAcl(getTopParentOid()); MutableAcl parent = this.jdbcMutableAclService.createAcl(getTopParentOid());
MutableAcl child = jdbcMutableAclService.createAcl(getMiddleParentOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getMiddleParentOid());
// Specify the inheritance hierarchy // Specify the inheritance hierarchy
child.setParent(parent); child.setParent(parent);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
try { try {
jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK this.jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK
// checking in the // checking in the
// class, not database // class, not database
jdbcMutableAclService.deleteAcl(getTopParentOid(), false); this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false);
fail("It should have thrown ChildrenExistException"); fail("It should have thrown ChildrenExistException");
} }
catch (ChildrenExistException expected) { catch (ChildrenExistException expected) {
} }
finally { finally {
jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the this.jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the
// default // default
} }
} }
@ -408,31 +408,31 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
@Transactional @Transactional
public void deleteAclRemovesRowsFromDatabase() { public void deleteAclRemovesRowsFromDatabase() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
MutableAcl child = jdbcMutableAclService.createAcl(getChildOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid());
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), false); child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
// Remove the child and check all related database rows were removed accordingly // Remove the child and check all related database rows were removed accordingly
jdbcMutableAclService.deleteAcl(getChildOid(), false); this.jdbcMutableAclService.deleteAcl(getChildOid(), false);
assertThat(jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] { getTargetClass() })).hasSize(1); assertThat(this.jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] { getTargetClass() })).hasSize(1);
assertThat(jdbcTemplate.queryForList("select * from acl_object_identity")).isEmpty(); assertThat(this.jdbcTemplate.queryForList("select * from acl_object_identity")).isEmpty();
assertThat(jdbcTemplate.queryForList("select * from acl_entry")).isEmpty(); assertThat(this.jdbcTemplate.queryForList("select * from acl_entry")).isEmpty();
// Check the cache // Check the cache
assertThat(aclCache.getFromCache(getChildOid())).isNull(); assertThat(this.aclCache.getFromCache(getChildOid())).isNull();
assertThat(aclCache.getFromCache(102L)).isNull(); assertThat(this.aclCache.getFromCache(102L)).isNull();
} }
/** SEC-1107 */ /** SEC-1107 */
@Test @Test
@Transactional @Transactional
public void identityWithIntegerIdIsSupportedByCreateAcl() { public void identityWithIntegerIdIsSupportedByCreateAcl() {
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101);
jdbcMutableAclService.createAcl(oid); this.jdbcMutableAclService.createAcl(oid);
assertThat(jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 101L))).isNotNull(); assertThat(this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 101L))).isNotNull();
} }
/** /**
@ -448,21 +448,21 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
ObjectIdentity parentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity parentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L);
ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 105L); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 105L);
MutableAcl parent = jdbcMutableAclService.createAcl(parentOid); MutableAcl parent = this.jdbcMutableAclService.createAcl(parentOid);
MutableAcl child = jdbcMutableAclService.createAcl(childOid); MutableAcl child = this.jdbcMutableAclService.createAcl(childOid);
child.setParent(parent); child.setParent(parent);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
parent = (AclImpl) jdbcMutableAclService.readAclById(parentOid); parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid);
parent.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), true); parent.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), true);
jdbcMutableAclService.updateAcl(parent); this.jdbcMutableAclService.updateAcl(parent);
parent = (AclImpl) jdbcMutableAclService.readAclById(parentOid); parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid);
parent.insertAce(1, BasePermission.READ, new PrincipalSid("scott"), true); parent.insertAce(1, BasePermission.READ, new PrincipalSid("scott"), true);
jdbcMutableAclService.updateAcl(parent); this.jdbcMutableAclService.updateAcl(parent);
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid); child = (MutableAcl) this.jdbcMutableAclService.readAclById(childOid);
parent = (MutableAcl) child.getParentAcl(); parent = (MutableAcl) child.getParentAcl();
assertThat(parent.getEntries()).hasSize(2) assertThat(parent.getEntries()).hasSize(2)
@ -483,18 +483,18 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS, 1L); ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS, 1L);
MutableAcl parent = jdbcMutableAclService.createAcl(rootObject); MutableAcl parent = this.jdbcMutableAclService.createAcl(rootObject);
MutableAcl child = jdbcMutableAclService.createAcl(new ObjectIdentityImpl(TARGET_CLASS, 2L)); MutableAcl child = this.jdbcMutableAclService.createAcl(new ObjectIdentityImpl(TARGET_CLASS, 2L));
child.setParent(parent); child.setParent(parent);
jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true); parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
jdbcMutableAclService.updateAcl(parent); this.jdbcMutableAclService.updateAcl(parent);
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true); parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
jdbcMutableAclService.updateAcl(parent); this.jdbcMutableAclService.updateAcl(parent);
child = (MutableAcl) jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 2L)); child = (MutableAcl) this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 2L));
parent = (MutableAcl) child.getParentAcl(); parent = (MutableAcl) child.getParentAcl();
@ -513,7 +513,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
SecurityContextHolder.getContext().setAuthentication(auth); SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 110L); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 110L);
MutableAcl topParent = jdbcMutableAclService.createAcl(topParentOid); MutableAcl topParent = this.jdbcMutableAclService.createAcl(topParentOid);
// Add an ACE permission entry // Add an ACE permission entry
Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION); Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION);
@ -523,7 +523,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
assertThat(topParent.getEntries()).hasSize(1); assertThat(topParent.getEntries()).hasSize(1);
// Explicitly save the changed ACL // Explicitly save the changed ACL
topParent = jdbcMutableAclService.updateAcl(topParent); topParent = this.jdbcMutableAclService.updateAcl(topParent);
// Check the mask was retrieved correctly // Check the mask was retrieved correctly
assertThat(topParent.getEntries().get(0).getPermission().getMask()).isEqualTo(17); assertThat(topParent.getEntries().get(0).getPermission().getMask()).isEqualTo(17);
@ -535,7 +535,7 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
public void testProcessingCustomSid() { public void testProcessingCustomSid() {
CustomJdbcMutableAclService customJdbcMutableAclService = spy( CustomJdbcMutableAclService customJdbcMutableAclService = spy(
new CustomJdbcMutableAclService(dataSource, lookupStrategy, aclCache)); new CustomJdbcMutableAclService(this.dataSource, this.lookupStrategy, this.aclCache));
CustomSid customSid = new CustomSid("Custom sid"); CustomSid customSid = new CustomSid("Custom sid");
when(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).thenReturn(1L); when(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).thenReturn(1L);
@ -574,11 +574,11 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
} }
protected Authentication getAuth() { protected Authentication getAuth() {
return auth; return this.auth;
} }
protected JdbcMutableAclService getJdbcMutableAclService() { protected JdbcMutableAclService getJdbcMutableAclService() {
return jdbcMutableAclService; return this.jdbcMutableAclService;
} }
} }

View File

@ -52,17 +52,17 @@ public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServ
@Override @Override
protected ObjectIdentity getTopParentOid() { protected ObjectIdentity getTopParentOid() {
return topParentOid; return this.topParentOid;
} }
@Override @Override
protected ObjectIdentity getMiddleParentOid() { protected ObjectIdentity getMiddleParentOid() {
return middleParentOid; return this.middleParentOid;
} }
@Override @Override
protected ObjectIdentity getChildOid() { protected ObjectIdentity getChildOid() {
return childOid; return this.childOid;
} }
@Override @Override

View File

@ -31,7 +31,7 @@ public class CustomSid implements Sid {
} }
public String getSid() { public String getSid() {
return sid; return this.sid;
} }
public void setSid(String sid) { public void setSid(String sid) {

View File

@ -48,7 +48,7 @@ public class SidRetrievalStrategyTests {
@Test @Test
public void correctSidsAreRetrieved() { public void correctSidsAreRetrieved() {
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl(); SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
List<Sid> sids = retrStrategy.getSids(authentication); List<Sid> sids = retrStrategy.getSids(this.authentication);
assertThat(sids).isNotNull(); assertThat(sids).isNotNull();
assertThat(sids).hasSize(4); assertThat(sids).hasSize(4);
@ -72,7 +72,7 @@ public class SidRetrievalStrategyTests {
when(rh.getReachableGrantedAuthorities(anyCollection())).thenReturn(rhAuthorities); when(rh.getReachableGrantedAuthorities(anyCollection())).thenReturn(rhAuthorities);
SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh); SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh);
List<Sid> sids = strat.getSids(authentication); List<Sid> sids = strat.getSids(this.authentication);
assertThat(sids).hasSize(2); assertThat(sids).hasSize(2);
assertThat(sids.get(0)).isNotNull(); assertThat(sids.get(0)).isNotNull();
assertThat(sids.get(0) instanceof PrincipalSid).isTrue(); assertThat(sids.get(0) instanceof PrincipalSid).isTrue();

View File

@ -249,7 +249,7 @@ public class SidTests {
@Override @Override
public String getName() { public String getName() {
return principal.getName(); return this.principal.getName();
} }
} }
@ -263,7 +263,7 @@ public class SidTests {
} }
String getName() { String getName() {
return name; return this.name;
} }
} }

View File

@ -75,15 +75,15 @@ public class AnnotationSecurityAspectTests {
@Before @Before
public final void setUp() { public final void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
interceptor = new AspectJMethodSecurityInterceptor(); this.interceptor = new AspectJMethodSecurityInterceptor();
AccessDecisionVoter[] voters = new AccessDecisionVoter[] { new RoleVoter(), AccessDecisionVoter[] voters = new AccessDecisionVoter[] { new RoleVoter(),
new PreInvocationAuthorizationAdviceVoter(new ExpressionBasedPreInvocationAdvice()) }; new PreInvocationAuthorizationAdviceVoter(new ExpressionBasedPreInvocationAdvice()) };
adm = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(voters)); this.adm = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(voters));
interceptor.setAccessDecisionManager(adm); this.interceptor.setAccessDecisionManager(this.adm);
interceptor.setAuthenticationManager(authman); this.interceptor.setAuthenticationManager(this.authman);
interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource()); this.interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource());
AnnotationSecurityAspect secAspect = AnnotationSecurityAspect.aspectOf(); AnnotationSecurityAspect secAspect = AnnotationSecurityAspect.aspectOf();
secAspect.setSecurityInterceptor(interceptor); secAspect.setSecurityInterceptor(this.interceptor);
} }
@After @After
@ -93,59 +93,59 @@ public class AnnotationSecurityAspectTests {
@Test @Test
public void securedInterfaceMethodAllowsAllAccess() { public void securedInterfaceMethodAllowsAllAccess() {
secured.securedMethod(); this.secured.securedMethod();
} }
@Test(expected = AuthenticationCredentialsNotFoundException.class) @Test(expected = AuthenticationCredentialsNotFoundException.class)
public void securedClassMethodDeniesUnauthenticatedAccess() { public void securedClassMethodDeniesUnauthenticatedAccess() {
secured.securedClassMethod(); this.secured.securedClassMethod();
} }
@Test @Test
public void securedClassMethodAllowsAccessToRoleA() { public void securedClassMethodAllowsAccessToRoleA() {
SecurityContextHolder.getContext().setAuthentication(anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
secured.securedClassMethod(); this.secured.securedClassMethod();
} }
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
public void internalPrivateCallIsIntercepted() { public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
try { try {
secured.publicCallsPrivate(); this.secured.publicCallsPrivate();
fail("Expected AccessDeniedException"); fail("Expected AccessDeniedException");
} }
catch (AccessDeniedException expected) { catch (AccessDeniedException expected) {
} }
securedSub.publicCallsPrivate(); this.securedSub.publicCallsPrivate();
} }
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
public void protectedMethodIsIntercepted() { public void protectedMethodIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
secured.protectedMethod(); this.secured.protectedMethod();
} }
@Test @Test
public void overriddenProtectedMethodIsNotIntercepted() { public void overriddenProtectedMethodIsNotIntercepted() {
// AspectJ doesn't inherit annotations // AspectJ doesn't inherit annotations
securedSub.protectedMethod(); this.securedSub.protectedMethod();
} }
// SEC-1262 // SEC-1262
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
public void denyAllPreAuthorizeDeniesAccess() { public void denyAllPreAuthorizeDeniesAccess() {
configureForElAnnotations(); configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
prePostSecured.denyAllMethod(); this.prePostSecured.denyAllMethod();
} }
@Test @Test
public void postFilterIsApplied() { public void postFilterIsApplied() {
configureForElAnnotations(); configureForElAnnotations();
SecurityContextHolder.getContext().setAuthentication(anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
List<String> objects = prePostSecured.postFilterMethod(); List<String> objects = this.prePostSecured.postFilterMethod();
assertThat(objects).hasSize(2); assertThat(objects).hasSize(2);
assertThat(objects.contains("apple")).isTrue(); assertThat(objects.contains("apple")).isTrue();
assertThat(objects.contains("aubergine")).isTrue(); assertThat(objects.contains("aubergine")).isTrue();
@ -153,12 +153,12 @@ public class AnnotationSecurityAspectTests {
private void configureForElAnnotations() { private void configureForElAnnotations() {
DefaultMethodSecurityExpressionHandler eh = new DefaultMethodSecurityExpressionHandler(); DefaultMethodSecurityExpressionHandler eh = new DefaultMethodSecurityExpressionHandler();
interceptor.setSecurityMetadataSource( this.interceptor.setSecurityMetadataSource(
new PrePostAnnotationSecurityMetadataSource(new ExpressionBasedAnnotationAttributeFactory(eh))); new PrePostAnnotationSecurityMetadataSource(new ExpressionBasedAnnotationAttributeFactory(eh)));
interceptor.setAccessDecisionManager(adm); this.interceptor.setAccessDecisionManager(this.adm);
AfterInvocationProviderManager aim = new AfterInvocationProviderManager(); AfterInvocationProviderManager aim = new AfterInvocationProviderManager();
aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(new ExpressionBasedPostInvocationAdvice(eh)))); aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(new ExpressionBasedPostInvocationAdvice(eh))));
interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
} }
} }

View File

@ -164,7 +164,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
} }
public UserDetails getUserDetails() { public UserDetails getUserDetails() {
return userDetails; return this.userDetails;
} }
@Override @Override

View File

@ -37,11 +37,11 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
private Ehcache cache; private Ehcache cache;
public void afterPropertiesSet() { public void afterPropertiesSet() {
Assert.notNull(cache, "cache mandatory"); Assert.notNull(this.cache, "cache mandatory");
} }
public CasAuthenticationToken getByTicketId(final String serviceTicket) { public CasAuthenticationToken getByTicketId(final String serviceTicket) {
final Element element = cache.get(serviceTicket); final Element element = this.cache.get(serviceTicket);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket); logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket);
@ -51,7 +51,7 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
} }
public Ehcache getCache() { public Ehcache getCache() {
return cache; return this.cache;
} }
public void putTicketInCache(final CasAuthenticationToken token) { public void putTicketInCache(final CasAuthenticationToken token) {
@ -61,7 +61,7 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
logger.debug("Cache put: " + element.getKey()); logger.debug("Cache put: " + element.getKey());
} }
cache.put(element); this.cache.put(element);
} }
public void removeTicketFromCache(final CasAuthenticationToken token) { public void removeTicketFromCache(final CasAuthenticationToken token) {
@ -73,7 +73,7 @@ public class EhCacheBasedTicketCache implements StatelessTicketCache, Initializi
} }
public void removeTicketFromCache(final String serviceTicket) { public void removeTicketFromCache(final String serviceTicket) {
cache.remove(serviceTicket); this.cache.remove(serviceTicket);
} }
public void setCache(final Ehcache cache) { public void setCache(final Ehcache cache) {

View File

@ -40,7 +40,7 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache {
} }
public CasAuthenticationToken getByTicketId(final String serviceTicket) { public CasAuthenticationToken getByTicketId(final String serviceTicket) {
final Cache.ValueWrapper element = serviceTicket != null ? cache.get(serviceTicket) : null; final Cache.ValueWrapper element = serviceTicket != null ? this.cache.get(serviceTicket) : null;
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket); logger.debug("Cache hit: " + (element != null) + "; service ticket: " + serviceTicket);
@ -56,7 +56,7 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache {
logger.debug("Cache put: " + key); logger.debug("Cache put: " + key);
} }
cache.put(key, token); this.cache.put(key, token);
} }
public void removeTicketFromCache(final CasAuthenticationToken token) { public void removeTicketFromCache(final CasAuthenticationToken token) {
@ -68,7 +68,7 @@ public class SpringCacheBasedTicketCache implements StatelessTicketCache {
} }
public void removeTicketFromCache(final String serviceTicket) { public void removeTicketFromCache(final String serviceTicket) {
cache.evict(serviceTicket); this.cache.evict(serviceTicket);
} }
} }

View File

@ -217,15 +217,15 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
return; return;
} }
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult); this.logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
} }
SecurityContextHolder.getContext().setAuthentication(authResult); SecurityContextHolder.getContext().setAuthentication(authResult);
// Fire event // Fire event
if (this.eventPublisher != null) { if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
} }
chain.doFilter(request, response); chain.doFilter(request, response);
@ -237,7 +237,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
// if the request is a proxy request process it and return null to indicate the // if the request is a proxy request process it and return null to indicate the
// request has been processed // request has been processed
if (proxyReceptorRequest(request)) { if (proxyReceptorRequest(request)) {
logger.debug("Responding to proxy receptor request"); this.logger.debug("Responding to proxy receptor request");
CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage);
return null; return null;
} }
@ -247,14 +247,14 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
String password = obtainArtifact(request); String password = obtainArtifact(request);
if (password == null) { if (password == null) {
logger.debug("Failed to obtain an artifact (cas ticket)"); this.logger.debug("Failed to obtain an artifact (cas ticket)");
password = ""; password = "";
} }
final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
password); password);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
return this.getAuthenticationManager().authenticate(authRequest); return this.getAuthenticationManager().authenticate(authRequest);
} }
@ -265,7 +265,7 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
* @return if present the artifact from the {@link HttpServletRequest}, else null * @return if present the artifact from the {@link HttpServletRequest}, else null
*/ */
protected String obtainArtifact(HttpServletRequest request) { protected String obtainArtifact(HttpServletRequest request) {
return request.getParameter(artifactParameter); return request.getParameter(this.artifactParameter);
} }
/** /**
@ -275,8 +275,8 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
final boolean serviceTicketRequest = serviceTicketRequest(request, response); final boolean serviceTicketRequest = serviceTicketRequest(request, response);
final boolean result = serviceTicketRequest || proxyReceptorRequest(request) final boolean result = serviceTicketRequest || proxyReceptorRequest(request)
|| (proxyTicketRequest(serviceTicketRequest, request)); || (proxyTicketRequest(serviceTicketRequest, request));
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("requiresAuthentication = " + result); this.logger.debug("requiresAuthentication = " + result);
} }
return result; return result;
} }
@ -321,8 +321,8 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
*/ */
private boolean serviceTicketRequest(final HttpServletRequest request, final HttpServletResponse response) { private boolean serviceTicketRequest(final HttpServletRequest request, final HttpServletResponse response) {
boolean result = super.requiresAuthentication(request, response); boolean result = super.requiresAuthentication(request, response);
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("serviceTicketRequest = " + result); this.logger.debug("serviceTicketRequest = " + result);
} }
return result; return result;
} }
@ -336,9 +336,9 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
if (serviceTicketRequest) { if (serviceTicketRequest) {
return false; return false;
} }
final boolean result = authenticateAllArtifacts && obtainArtifact(request) != null && !authenticated(); final boolean result = this.authenticateAllArtifacts && obtainArtifact(request) != null && !authenticated();
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("proxyTicketRequest = " + result); this.logger.debug("proxyTicketRequest = " + result);
} }
return result; return result;
} }
@ -359,9 +359,9 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
* @return * @return
*/ */
private boolean proxyReceptorRequest(final HttpServletRequest request) { private boolean proxyReceptorRequest(final HttpServletRequest request) {
final boolean result = proxyReceptorConfigured() && proxyReceptorMatcher.matches(request); final boolean result = proxyReceptorConfigured() && this.proxyReceptorMatcher.matches(request);
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("proxyReceptorRequest = " + result); this.logger.debug("proxyReceptorRequest = " + result);
} }
return result; return result;
} }
@ -372,9 +372,9 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
* @return * @return
*/ */
private boolean proxyReceptorConfigured() { private boolean proxyReceptorConfigured() {
final boolean result = this.proxyGrantingTicketStorage != null && proxyReceptorMatcher != null; final boolean result = this.proxyGrantingTicketStorage != null && this.proxyReceptorMatcher != null;
if (logger.isDebugEnabled()) { if (this.logger.isDebugEnabled()) {
logger.debug("proxyReceptorConfigured = " + result); this.logger.debug("proxyReceptorConfigured = " + result);
} }
return result; return result;
} }
@ -401,10 +401,10 @@ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFil
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException { AuthenticationException exception) throws IOException, ServletException {
if (serviceTicketRequest(request, response)) { if (serviceTicketRequest(request, response)) {
serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception); this.serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception);
} }
else { else {
proxyFailureHandler.onAuthenticationFailure(request, response, exception); CasAuthenticationFilter.this.proxyFailureHandler.onAuthenticationFailure(request, response, exception);
} }
} }

View File

@ -62,14 +62,14 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
* @see org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails#getServiceUrl() * @see org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails#getServiceUrl()
*/ */
public String getServiceUrl() { public String getServiceUrl() {
return serviceUrl; return this.serviceUrl;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = super.hashCode(); int result = super.hashCode();
result = prime * result + serviceUrl.hashCode(); result = prime * result + this.serviceUrl.hashCode();
return result; return result;
} }
@ -82,7 +82,7 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
return false; return false;
} }
ServiceAuthenticationDetails that = (ServiceAuthenticationDetails) obj; ServiceAuthenticationDetails that = (ServiceAuthenticationDetails) obj;
return serviceUrl.equals(that.getServiceUrl()); return this.serviceUrl.equals(that.getServiceUrl());
} }
@Override @Override
@ -90,7 +90,7 @@ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
result.append(super.toString()); result.append(super.toString());
result.append("ServiceUrl: "); result.append("ServiceUrl: ");
result.append(serviceUrl); result.append(this.serviceUrl);
return result.toString(); return result.toString();
} }

View File

@ -70,7 +70,8 @@ public class ServiceAuthenticationDetailsSource
*/ */
public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) { public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) {
try { try {
return new DefaultServiceAuthenticationDetails(serviceProperties.getService(), context, artifactPattern); return new DefaultServiceAuthenticationDetails(this.serviceProperties.getService(), context,
this.artifactPattern);
} }
catch (MalformedURLException e) { catch (MalformedURLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -389,11 +389,11 @@ public class CasAuthenticationProviderTests {
private Map<String, CasAuthenticationToken> cache = new HashMap<>(); private Map<String, CasAuthenticationToken> cache = new HashMap<>();
public CasAuthenticationToken getByTicketId(String serviceTicket) { public CasAuthenticationToken getByTicketId(String serviceTicket) {
return cache.get(serviceTicket); return this.cache.get(serviceTicket);
} }
public void putTicketInCache(CasAuthenticationToken token) { public void putTicketInCache(CasAuthenticationToken token) {
cache.put(token.getCredentials().toString(), token); this.cache.put(token.getCredentials().toString(), token);
} }
public void removeTicketFromCache(CasAuthenticationToken token) { public void removeTicketFromCache(CasAuthenticationToken token) {
@ -415,7 +415,7 @@ public class CasAuthenticationProviderTests {
} }
public Assertion validate(final String ticket, final String service) { public Assertion validate(final String ticket, final String service) {
if (returnTicket) { if (this.returnTicket) {
return new AssertionImpl("rod"); return new AssertionImpl("rod");
} }
throw new BadCredentialsException("As requested from mock"); throw new BadCredentialsException("As requested from mock");

View File

@ -47,42 +47,42 @@ public class CasAuthenticationTokenTests {
} }
private UserDetails makeUserDetails(final String name) { private UserDetails makeUserDetails(final String name) {
return new User(name, "password", true, true, true, true, ROLES); return new User(name, "password", true, true, true, true, this.ROLES);
} }
@Test @Test
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
try { try {
new CasAuthenticationToken(null, makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); new CasAuthenticationToken(null, makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new CasAuthenticationToken("key", null, "Password", ROLES, makeUserDetails(), assertion); new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new CasAuthenticationToken("key", makeUserDetails(), null, ROLES, makeUserDetails(), assertion); new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, makeUserDetails(), null); new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
} }
try { try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, null, assertion); new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion);
fail("Should have thrown IllegalArgumentException"); fail("Should have thrown IllegalArgumentException");
} }
catch (IllegalArgumentException expected) { catch (IllegalArgumentException expected) {
@ -107,10 +107,10 @@ public class CasAuthenticationTokenTests {
public void testEqualsWhenEqual() { public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
assertThat(token2).isEqualTo(token1); assertThat(token2).isEqualTo(token1);
@ -120,7 +120,7 @@ public class CasAuthenticationTokenTests {
public void testGetters() { public void testGetters() {
// Build the proxy list returned in the ticket from CAS // Build the proxy list returned in the ticket from CAS
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
assertThat(token.getKeyHash()).isEqualTo("key".hashCode()); assertThat(token.getKeyHash()).isEqualTo("key".hashCode());
assertThat(token.getPrincipal()).isEqualTo(makeUserDetails()); assertThat(token.getPrincipal()).isEqualTo(makeUserDetails());
@ -146,11 +146,11 @@ public class CasAuthenticationTokenTests {
public void testNotEqualsDueToAbstractParentEqualsCheck() { public void testNotEqualsDueToAbstractParentEqualsCheck() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password", CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password",
ROLES, makeUserDetails(), assertion); this.ROLES, makeUserDetails(), assertion);
assertThat(!token1.equals(token2)).isTrue(); assertThat(!token1.equals(token2)).isTrue();
} }
@ -159,10 +159,11 @@ public class CasAuthenticationTokenTests {
public void testNotEqualsDueToDifferentAuthenticationClass() { public void testNotEqualsDueToDifferentAuthenticationClass() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", ROLES); UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
this.ROLES);
assertThat(!token1.equals(token2)).isTrue(); assertThat(!token1.equals(token2)).isTrue();
} }
@ -170,11 +171,11 @@ public class CasAuthenticationTokenTests {
public void testNotEqualsDueToKey() { public void testNotEqualsDueToKey() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password", CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password",
ROLES, makeUserDetails(), assertion); this.ROLES, makeUserDetails(), assertion);
assertThat(!token1.equals(token2)).isTrue(); assertThat(!token1.equals(token2)).isTrue();
} }
@ -184,10 +185,10 @@ public class CasAuthenticationTokenTests {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test"); final Assertion assertion2 = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion2); makeUserDetails(), assertion2);
assertThat(!token1.equals(token2)).isTrue(); assertThat(!token1.equals(token2)).isTrue();
@ -196,7 +197,7 @@ public class CasAuthenticationTokenTests {
@Test @Test
public void testSetAuthenticated() { public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
assertThat(token.isAuthenticated()).isTrue(); assertThat(token.isAuthenticated()).isTrue();
token.setAuthenticated(false); token.setAuthenticated(false);
@ -206,7 +207,7 @@ public class CasAuthenticationTokenTests {
@Test @Test
public void testToString() { public void testToString() {
final Assertion assertion = new AssertionImpl("test"); final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES,
makeUserDetails(), assertion); makeUserDetails(), assertion);
String result = token.toString(); String result = token.toString();
assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue(); assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue();

View File

@ -31,15 +31,15 @@ public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheT
@Test @Test
public void testGetter() { public void testGetter() {
assertThat(cache.getByTicketId(null)).isNull(); assertThat(this.cache.getByTicketId(null)).isNull();
assertThat(cache.getByTicketId("test")).isNull(); assertThat(this.cache.getByTicketId("test")).isNull();
} }
@Test @Test
public void testInsertAndGet() { public void testInsertAndGet() {
final CasAuthenticationToken token = getToken(); final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token); this.cache.putTicketInCache(token);
assertThat(cache.getByTicketId((String) token.getCredentials())).isNull(); assertThat(this.cache.getByTicketId((String) token.getCredentials())).isNull();
} }
} }

View File

@ -95,15 +95,15 @@ public class CasAuthenticationTokenMixinTests {
@Before @Before
public void setup() { public void setup() {
mapper = new ObjectMapper(); this.mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader(); ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJackson2Modules.getModules(loader)); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
} }
@Test @Test
public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException { public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken(); CasAuthenticationToken token = createCasAuthenticationToken();
String actualJson = mapper.writeValueAsString(token); String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true); JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true);
} }
@ -112,19 +112,19 @@ public class CasAuthenticationTokenMixinTests {
throws JsonProcessingException, JSONException { throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken(); CasAuthenticationToken token = createCasAuthenticationToken();
token.eraseCredentials(); token.eraseCredentials();
String actualJson = mapper.writeValueAsString(token); String actualJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true); JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true);
} }
@Test @Test
public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception { public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception {
CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class); CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class);
assertThat(((UserDetails) token.getPrincipal()).getPassword()).isNull(); assertThat(((UserDetails) token.getPrincipal()).getPassword()).isNull();
} }
@Test @Test
public void deserializeCasAuthenticationTest() throws IOException { public void deserializeCasAuthenticationTest() throws IOException {
CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class); CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin");

View File

@ -237,8 +237,8 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests {
} }
private LdapAuthenticationProvider ldapProvider() { private LdapAuthenticationProvider ldapProvider() {
return ((List<LdapAuthenticationProvider>) ReflectionTestUtils.getField(authenticationManager, "providers")) return ((List<LdapAuthenticationProvider>) ReflectionTestUtils.getField(this.authenticationManager,
.get(0); "providers")).get(0);
} }
private LdapAuthoritiesPopulator getAuthoritiesPopulator(LdapAuthenticationProvider provider) { private LdapAuthoritiesPopulator getAuthoritiesPopulator(LdapAuthenticationProvider provider) {

View File

@ -40,19 +40,19 @@ public class LdapProviderBeanDefinitionParserTests {
@After @After
public void closeAppContext() { public void closeAppContext() {
if (appCtx != null) { if (this.appCtx != null) {
appCtx.close(); this.appCtx.close();
appCtx = null; this.appCtx = null;
} }
} }
@Test @Test
public void simpleProviderAuthenticatesCorrectly() { public void simpleProviderAuthenticatesCorrectly() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"
+ "<authentication-manager>" + " <ldap-authentication-provider group-search-filter='member={0}' />" + "<authentication-manager>" + " <ldap-authentication-provider group-search-filter='member={0}' />"
+ "</authentication-manager>"); + "</authentication-manager>");
AuthenticationManager authenticationManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); .authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
@ -62,12 +62,12 @@ public class LdapProviderBeanDefinitionParserTests {
@Test @Test
public void multipleProvidersAreSupported() { public void multipleProvidersAreSupported() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"
+ "<authentication-manager>" + " <ldap-authentication-provider group-search-filter='member={0}' />" + "<authentication-manager>" + " <ldap-authentication-provider group-search-filter='member={0}' />"
+ " <ldap-authentication-provider group-search-filter='uniqueMember={0}' />" + " <ldap-authentication-provider group-search-filter='uniqueMember={0}' />"
+ "</authentication-manager>"); + "</authentication-manager>");
ProviderManager providerManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class); ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(2); assertThat(providerManager.getProviders()).hasSize(2);
assertThat(providerManager.getProviders()).extracting("authoritiesPopulator.groupSearchFilter") assertThat(providerManager.getProviders()).extracting("authoritiesPopulator.groupSearchFilter")
.containsExactly("member={0}", "uniqueMember={0}"); .containsExactly("member={0}", "uniqueMember={0}");
@ -81,11 +81,11 @@ public class LdapProviderBeanDefinitionParserTests {
@Test @Test
public void supportsPasswordComparisonAuthentication() { public void supportsPasswordComparisonAuthentication() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"
+ "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" + "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>"
+ " <password-compare />" + " </ldap-authentication-provider>" + "</authentication-manager>"); + " <password-compare />" + " </ldap-authentication-provider>" + "</authentication-manager>");
AuthenticationManager authenticationManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword")); .authenticate(new UsernamePasswordAuthenticationToken("ben", "benspassword"));
@ -95,13 +95,13 @@ public class LdapProviderBeanDefinitionParserTests {
@Test @Test
public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() { public void supportsPasswordComparisonAuthenticationWithPasswordEncoder() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"
+ "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" + "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>"
+ " <password-compare password-attribute='uid'>" + " <password-encoder ref='passwordEncoder' />" + " <password-compare password-attribute='uid'>" + " <password-encoder ref='passwordEncoder' />"
+ " </password-compare>" + " </ldap-authentication-provider>" + "</authentication-manager>" + " </password-compare>" + " </ldap-authentication-provider>" + "</authentication-manager>"
+ "<b:bean id='passwordEncoder' class='org.springframework.security.crypto.password.NoOpPasswordEncoder' factory-method='getInstance' />"); + "<b:bean id='passwordEncoder' class='org.springframework.security.crypto.password.NoOpPasswordEncoder' factory-method='getInstance' />");
AuthenticationManager authenticationManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben")); Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("ben", "ben"));
@ -111,13 +111,13 @@ public class LdapProviderBeanDefinitionParserTests {
// SEC-2472 // SEC-2472
@Test @Test
public void supportsCryptoPasswordEncoder() { public void supportsCryptoPasswordEncoder() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"
+ "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>" + "<authentication-manager>" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=people'>"
+ " <password-compare>" + " <password-encoder ref='pe' />" + " </password-compare>" + " <password-compare>" + " <password-encoder ref='pe' />" + " </password-compare>"
+ " </ldap-authentication-provider>" + "</authentication-manager>" + " </ldap-authentication-provider>" + "</authentication-manager>"
+ "<b:bean id='pe' class='org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' />"); + "<b:bean id='pe' class='org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' />");
AuthenticationManager authenticationManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, AuthenticationManager authenticationManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER,
AuthenticationManager.class); AuthenticationManager.class);
Authentication auth = authenticationManager Authentication auth = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("bcrypt", "password")); .authenticate(new UsernamePasswordAuthenticationToken("bcrypt", "password"));
@ -127,13 +127,13 @@ public class LdapProviderBeanDefinitionParserTests {
@Test @Test
public void inetOrgContextMapperIsSupported() { public void inetOrgContextMapperIsSupported() {
appCtx = new InMemoryXmlApplicationContext( this.appCtx = new InMemoryXmlApplicationContext(
"<ldap-server url='ldap://127.0.0.1:343/dc=springframework,dc=org' port='0'/>" "<ldap-server url='ldap://127.0.0.1:343/dc=springframework,dc=org' port='0'/>"
+ "<authentication-manager>" + "<authentication-manager>"
+ " <ldap-authentication-provider user-details-class='inetOrgPerson' />" + " <ldap-authentication-provider user-details-class='inetOrgPerson' />"
+ "</authentication-manager>"); + "</authentication-manager>");
ProviderManager providerManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class); ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(1); assertThat(providerManager.getProviders()).hasSize(1);
assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper") assertThat(providerManager.getProviders()).extracting("userDetailsContextMapper")
.allSatisfy(contextMapper -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class)); .allSatisfy(contextMapper -> assertThat(contextMapper).isInstanceOf(InetOrgPersonContextMapper.class));
@ -143,12 +143,12 @@ public class LdapProviderBeanDefinitionParserTests {
public void ldapAuthenticationProviderWorksWithPlaceholders() { public void ldapAuthenticationProviderWorksWithPlaceholders() {
System.setProperty("udp", "people"); System.setProperty("udp", "people");
System.setProperty("gsf", "member"); System.setProperty("gsf", "member");
appCtx = new InMemoryXmlApplicationContext("<ldap-server />" + "<authentication-manager>" this.appCtx = new InMemoryXmlApplicationContext("<ldap-server />" + "<authentication-manager>"
+ " <ldap-authentication-provider user-dn-pattern='uid={0},ou=${udp}' group-search-filter='${gsf}={0}' />" + " <ldap-authentication-provider user-dn-pattern='uid={0},ou=${udp}' group-search-filter='${gsf}={0}' />"
+ "</authentication-manager>" + "</authentication-manager>"
+ "<b:bean id='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' />"); + "<b:bean id='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' />");
ProviderManager providerManager = appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class); ProviderManager providerManager = this.appCtx.getBean(BeanIds.AUTHENTICATION_MANAGER, ProviderManager.class);
assertThat(providerManager.getProviders()).hasSize(1); assertThat(providerManager.getProviders()).hasSize(1);
AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0); AuthenticationProvider authenticationProvider = providerManager.getProviders().get(0);

View File

@ -40,17 +40,17 @@ public class LdapServerBeanDefinitionParserTests {
@After @After
public void closeAppContext() { public void closeAppContext() {
if (appCtx != null) { if (this.appCtx != null) {
appCtx.close(); this.appCtx.close();
appCtx = null; this.appCtx = null;
} }
} }
@Test @Test
public void embeddedServerCreationContainsExpectedContextSourceAndData() { public void embeddedServerCreationContainsExpectedContextSourceAndData() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>"); this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='0'/>");
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) appCtx DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(BeanIds.CONTEXT_SOURCE); .getBean(BeanIds.CONTEXT_SOURCE);
// Check data is loaded // Check data is loaded
@ -62,14 +62,15 @@ public class LdapServerBeanDefinitionParserTests {
public void useOfUrlAttributeCreatesCorrectContextSource() throws Exception { public void useOfUrlAttributeCreatesCorrectContextSource() throws Exception {
int port = getDefaultPort(); int port = getDefaultPort();
// Create second "server" with a url pointing at embedded one // Create second "server" with a url pointing at embedded one
appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='" + port this.appCtx = new InMemoryXmlApplicationContext("<ldap-server ldif='classpath:test-server.ldif' port='" + port
+ "'/>" + "<ldap-server ldif='classpath:test-server.ldif' id='blah' url='ldap://127.0.0.1:" + port + "'/>" + "<ldap-server ldif='classpath:test-server.ldif' id='blah' url='ldap://127.0.0.1:" + port
+ "/dc=springframework,dc=org' />"); + "/dc=springframework,dc=org' />");
// Check the default context source is still there. // Check the default context source is still there.
appCtx.getBean(BeanIds.CONTEXT_SOURCE); this.appCtx.getBean(BeanIds.CONTEXT_SOURCE);
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) appCtx.getBean("blah"); DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean("blah");
// Check data is loaded as before // Check data is loaded as before
LdapTemplate template = new LdapTemplate(contextSource); LdapTemplate template = new LdapTemplate(contextSource);
@ -78,9 +79,9 @@ public class LdapServerBeanDefinitionParserTests {
@Test @Test
public void loadingSpecificLdifFileIsSuccessful() { public void loadingSpecificLdifFileIsSuccessful() {
appCtx = new InMemoryXmlApplicationContext( this.appCtx = new InMemoryXmlApplicationContext(
"<ldap-server ldif='classpath*:test-server2.xldif' root='dc=monkeymachine,dc=co,dc=uk' port='0'/>"); "<ldap-server ldif='classpath*:test-server2.xldif' root='dc=monkeymachine,dc=co,dc=uk' port='0'/>");
DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) appCtx DefaultSpringSecurityContextSource contextSource = (DefaultSpringSecurityContextSource) this.appCtx
.getBean(BeanIds.CONTEXT_SOURCE); .getBean(BeanIds.CONTEXT_SOURCE);
LdapTemplate template = new LdapTemplate(contextSource); LdapTemplate template = new LdapTemplate(contextSource);
@ -89,8 +90,8 @@ public class LdapServerBeanDefinitionParserTests {
@Test @Test
public void defaultLdifFileIsSuccessful() { public void defaultLdifFileIsSuccessful() {
appCtx = new InMemoryXmlApplicationContext("<ldap-server/>"); this.appCtx = new InMemoryXmlApplicationContext("<ldap-server/>");
ApacheDSContainer dsContainer = appCtx.getBean(ApacheDSContainer.class); ApacheDSContainer dsContainer = this.appCtx.getBean(ApacheDSContainer.class);
assertThat(ReflectionTestUtils.getField(dsContainer, "ldifResources")).isEqualTo("classpath*:*.ldif"); assertThat(ReflectionTestUtils.getField(dsContainer, "ldifResources")).isEqualTo("classpath*:*.ldif");
} }

View File

@ -53,9 +53,9 @@ public class LdapUserServiceBeanDefinitionParserTests {
@After @After
public void closeAppContext() { public void closeAppContext() {
if (appCtx != null) { if (this.appCtx != null) {
appCtx.close(); this.appCtx.close();
appCtx = null; this.appCtx = null;
} }
} }
@ -81,7 +81,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
setContext( setContext(
"<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>"); "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
@ -95,7 +95,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
+ " user-search-filter='(cn={0})' " + " user-search-filter='(cn={0})' "
+ " group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>"); + " group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails joe = uds.loadUserByUsername("Joe Smeth"); UserDetails joe = uds.loadUserByUsername("Joe Smeth");
assertThat(joe.getUsername()).isEqualTo("Joe Smeth"); assertThat(joe.getUsername()).isEqualTo("Joe Smeth");
@ -108,11 +108,11 @@ public class LdapUserServiceBeanDefinitionParserTests {
+ "<ldap-user-service id='ldapUDSNoPrefix' " + " user-search-filter='(uid={0})' " + "<ldap-user-service id='ldapUDSNoPrefix' " + " user-search-filter='(uid={0})' "
+ " group-search-filter='member={0}' role-prefix='none'/><ldap-server ldif='classpath:test-server.ldif'/>"); + " group-search-filter='member={0}' role-prefix='none'/><ldap-server ldif='classpath:test-server.ldif'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("PREFIX_DEVELOPERS"); assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("PREFIX_DEVELOPERS");
uds = (UserDetailsService) appCtx.getBean("ldapUDSNoPrefix"); uds = (UserDetailsService) this.appCtx.getBean("ldapUDSNoPrefix");
ben = uds.loadUserByUsername("ben"); ben = uds.loadUserByUsername("ben");
assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("DEVELOPERS"); assertThat(AuthorityUtils.authorityListToSet(ben.getAuthorities())).contains("DEVELOPERS");
} }
@ -122,7 +122,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
setContext( setContext(
"<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-role-attribute='ou' group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>"); "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' group-role-attribute='ou' group-search-filter='member={0}' /><ldap-server ldif='classpath:test-server.ldif'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
@ -144,7 +144,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
public void personContextMapperIsSupported() { public void personContextMapperIsSupported() {
setContext("<ldap-server ldif='classpath:test-server.ldif'/>" setContext("<ldap-server ldif='classpath:test-server.ldif'/>"
+ "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='person'/>"); + "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='person'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
assertThat(ben instanceof Person).isTrue(); assertThat(ben instanceof Person).isTrue();
} }
@ -153,7 +153,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
public void inetOrgContextMapperIsSupported() { public void inetOrgContextMapperIsSupported() {
setContext("<ldap-server id='someServer' ldif='classpath:test-server.ldif'/>" setContext("<ldap-server id='someServer' ldif='classpath:test-server.ldif'/>"
+ "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='inetOrgPerson'/>"); + "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-details-class='inetOrgPerson'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
assertThat(ben instanceof InetOrgPerson).isTrue(); assertThat(ben instanceof InetOrgPerson).isTrue();
} }
@ -164,13 +164,13 @@ public class LdapUserServiceBeanDefinitionParserTests {
+ "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-context-mapper-ref='mapper'/>" + "<ldap-user-service id='ldapUDS' user-search-filter='(uid={0})' user-context-mapper-ref='mapper'/>"
+ "<b:bean id='mapper' class='" + InetOrgPersonContextMapper.class.getName() + "'/>"); + "<b:bean id='mapper' class='" + InetOrgPersonContextMapper.class.getName() + "'/>");
UserDetailsService uds = (UserDetailsService) appCtx.getBean("ldapUDS"); UserDetailsService uds = (UserDetailsService) this.appCtx.getBean("ldapUDS");
UserDetails ben = uds.loadUserByUsername("ben"); UserDetails ben = uds.loadUserByUsername("ben");
assertThat(ben instanceof InetOrgPerson).isTrue(); assertThat(ben instanceof InetOrgPerson).isTrue();
} }
private void setContext(String context) { private void setContext(String context) {
appCtx = new InMemoryXmlApplicationContext(context); this.appCtx = new InMemoryXmlApplicationContext(context);
} }
} }

View File

@ -78,15 +78,16 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
Package pkg = SpringSecurityCoreVersion.class.getPackage(); Package pkg = SpringSecurityCoreVersion.class.getPackage();
if (pkg == null || coreVersion == null) { if (pkg == null || coreVersion == null) {
logger.info("Couldn't determine package version information."); this.logger.info("Couldn't determine package version information.");
return; return;
} }
String version = pkg.getImplementationVersion(); String version = pkg.getImplementationVersion();
logger.info("Spring Security 'config' module version is " + version); this.logger.info("Spring Security 'config' module version is " + version);
if (version.compareTo(coreVersion) != 0) { if (version.compareTo(coreVersion) != 0) {
logger.error("You are running with different versions of the Spring Security 'core' and 'config' modules"); this.logger.error(
"You are running with different versions of the Spring Security 'core' and 'config' modules");
} }
} }
@ -98,7 +99,7 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
element); element);
} }
String name = pc.getDelegate().getLocalName(element); String name = pc.getDelegate().getLocalName(element);
BeanDefinitionParser parser = parsers.get(name); BeanDefinitionParser parser = this.parsers.get(name);
if (parser == null) { if (parser == null) {
// SEC-1455. Load parsers when required, not just on init(). // SEC-1455. Load parsers when required, not just on init().
@ -126,17 +127,17 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
// We only handle elements // We only handle elements
if (node instanceof Element) { if (node instanceof Element) {
if (Elements.INTERCEPT_METHODS.equals(name)) { if (Elements.INTERCEPT_METHODS.equals(name)) {
return interceptMethodsBDD.decorate(node, definition, pc); return this.interceptMethodsBDD.decorate(node, definition, pc);
} }
if (Elements.FILTER_CHAIN_MAP.equals(name)) { if (Elements.FILTER_CHAIN_MAP.equals(name)) {
if (filterChainMapBDD == null) { if (this.filterChainMapBDD == null) {
loadParsers(); loadParsers();
} }
if (filterChainMapBDD == null) { if (this.filterChainMapBDD == null) {
reportMissingWebClasses(name, pc, node); reportMissingWebClasses(name, pc, node);
} }
return filterChainMapBDD.decorate(node, definition, pc); return this.filterChainMapBDD.decorate(node, definition, pc);
} }
} }
@ -170,29 +171,32 @@ public final class SecurityNamespaceHandler implements NamespaceHandler {
private void loadParsers() { private void loadParsers() {
// Parsers // Parsers
parsers.put(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser()); this.parsers.put(Elements.LDAP_PROVIDER, new LdapProviderBeanDefinitionParser());
parsers.put(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser()); this.parsers.put(Elements.LDAP_SERVER, new LdapServerBeanDefinitionParser());
parsers.put(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser()); this.parsers.put(Elements.LDAP_USER_SERVICE, new LdapUserServiceBeanDefinitionParser());
parsers.put(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser()); this.parsers.put(Elements.USER_SERVICE, new UserServiceBeanDefinitionParser());
parsers.put(Elements.JDBC_USER_SERVICE, new JdbcUserServiceBeanDefinitionParser()); this.parsers.put(Elements.JDBC_USER_SERVICE, new JdbcUserServiceBeanDefinitionParser());
parsers.put(Elements.AUTHENTICATION_PROVIDER, new AuthenticationProviderBeanDefinitionParser()); this.parsers.put(Elements.AUTHENTICATION_PROVIDER, new AuthenticationProviderBeanDefinitionParser());
parsers.put(Elements.GLOBAL_METHOD_SECURITY, new GlobalMethodSecurityBeanDefinitionParser()); this.parsers.put(Elements.GLOBAL_METHOD_SECURITY, new GlobalMethodSecurityBeanDefinitionParser());
parsers.put(Elements.AUTHENTICATION_MANAGER, new AuthenticationManagerBeanDefinitionParser()); this.parsers.put(Elements.AUTHENTICATION_MANAGER, new AuthenticationManagerBeanDefinitionParser());
parsers.put(Elements.METHOD_SECURITY_METADATA_SOURCE, new MethodSecurityMetadataSourceBeanDefinitionParser()); this.parsers.put(Elements.METHOD_SECURITY_METADATA_SOURCE,
new MethodSecurityMetadataSourceBeanDefinitionParser());
// Only load the web-namespace parsers if the web classes are available // Only load the web-namespace parsers if the web classes are available
if (ClassUtils.isPresent(FILTER_CHAIN_PROXY_CLASSNAME, getClass().getClassLoader())) { if (ClassUtils.isPresent(FILTER_CHAIN_PROXY_CLASSNAME, getClass().getClassLoader())) {
parsers.put(Elements.DEBUG, new DebugBeanDefinitionParser()); this.parsers.put(Elements.DEBUG, new DebugBeanDefinitionParser());
parsers.put(Elements.HTTP, new HttpSecurityBeanDefinitionParser()); this.parsers.put(Elements.HTTP, new HttpSecurityBeanDefinitionParser());
parsers.put(Elements.HTTP_FIREWALL, new HttpFirewallBeanDefinitionParser()); this.parsers.put(Elements.HTTP_FIREWALL, new HttpFirewallBeanDefinitionParser());
parsers.put(Elements.FILTER_SECURITY_METADATA_SOURCE, new FilterInvocationSecurityMetadataSourceParser()); this.parsers.put(Elements.FILTER_SECURITY_METADATA_SOURCE,
parsers.put(Elements.FILTER_CHAIN, new FilterChainBeanDefinitionParser()); new FilterInvocationSecurityMetadataSourceParser());
filterChainMapBDD = new FilterChainMapBeanDefinitionDecorator(); this.parsers.put(Elements.FILTER_CHAIN, new FilterChainBeanDefinitionParser());
parsers.put(Elements.CLIENT_REGISTRATIONS, new ClientRegistrationsBeanDefinitionParser()); this.filterChainMapBDD = new FilterChainMapBeanDefinitionDecorator();
this.parsers.put(Elements.CLIENT_REGISTRATIONS, new ClientRegistrationsBeanDefinitionParser());
} }
if (ClassUtils.isPresent(MESSAGE_CLASSNAME, getClass().getClassLoader())) { if (ClassUtils.isPresent(MESSAGE_CLASSNAME, getClass().getClassLoader())) {
parsers.put(Elements.WEBSOCKET_MESSAGE_BROKER, new WebSocketMessageBrokerSecurityBeanDefinitionParser()); this.parsers.put(Elements.WEBSOCKET_MESSAGE_BROKER,
new WebSocketMessageBrokerSecurityBeanDefinitionParser());
} }
} }

View File

@ -103,7 +103,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
return build(); return build();
} }
catch (Exception e) { catch (Exception e) {
logger.debug("Failed to perform build. Returning null", e); this.logger.debug("Failed to perform build. Returning null", e);
return null; return null;
} }
} }
@ -121,7 +121,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <C extends SecurityConfigurerAdapter<O, B>> C apply(C configurer) throws Exception { public <C extends SecurityConfigurerAdapter<O, B>> C apply(C configurer) throws Exception {
configurer.addObjectPostProcessor(objectPostProcessor); configurer.addObjectPostProcessor(this.objectPostProcessor);
configurer.setBuilder((B) this); configurer.setBuilder((B) this);
add(configurer); add(configurer);
return configurer; return configurer;
@ -179,17 +179,18 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer
.getClass(); .getClass();
synchronized (configurers) { synchronized (this.configurers) {
if (buildState.isConfigured()) { if (this.buildState.isConfigured()) {
throw new IllegalStateException("Cannot apply " + configurer + " to already built object"); throw new IllegalStateException("Cannot apply " + configurer + " to already built object");
} }
List<SecurityConfigurer<O, B>> configs = allowConfigurersOfSameType ? this.configurers.get(clazz) : null; List<SecurityConfigurer<O, B>> configs = this.allowConfigurersOfSameType ? this.configurers.get(clazz)
: null;
if (configs == null) { if (configs == null) {
configs = new ArrayList<>(1); configs = new ArrayList<>(1);
} }
configs.add(configurer); configs.add(configurer);
this.configurers.put(clazz, configs); this.configurers.put(clazz, configs);
if (buildState.isInitializing()) { if (this.buildState.isInitializing()) {
this.configurersAddedInInitializing.add(configurer); this.configurersAddedInInitializing.add(configurer);
} }
} }
@ -297,22 +298,22 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
*/ */
@Override @Override
protected final O doBuild() throws Exception { protected final O doBuild() throws Exception {
synchronized (configurers) { synchronized (this.configurers) {
buildState = BuildState.INITIALIZING; this.buildState = BuildState.INITIALIZING;
beforeInit(); beforeInit();
init(); init();
buildState = BuildState.CONFIGURING; this.buildState = BuildState.CONFIGURING;
beforeConfigure(); beforeConfigure();
configure(); configure();
buildState = BuildState.BUILDING; this.buildState = BuildState.BUILDING;
O result = performBuild(); O result = performBuild();
buildState = BuildState.BUILT; this.buildState = BuildState.BUILT;
return result; return result;
} }
@ -349,7 +350,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
configurer.init((B) this); configurer.init((B) this);
} }
for (SecurityConfigurer<O, B> configurer : configurersAddedInInitializing) { for (SecurityConfigurer<O, B> configurer : this.configurersAddedInInitializing) {
configurer.init((B) this); configurer.init((B) this);
} }
} }
@ -376,8 +377,8 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* @return true, if unbuilt else false * @return true, if unbuilt else false
*/ */
private boolean isUnbuilt() { private boolean isUnbuilt() {
synchronized (configurers) { synchronized (this.configurers) {
return buildState == BuildState.UNBUILT; return this.buildState == BuildState.UNBUILT;
} }
} }
@ -427,7 +428,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
} }
public boolean isInitializing() { public boolean isInitializing() {
return INITIALIZING.order == order; return INITIALIZING.order == this.order;
} }
/** /**
@ -435,7 +436,7 @@ public abstract class AbstractConfiguredSecurityBuilder<O, B extends SecurityBui
* @return * @return
*/ */
public boolean isConfigured() { public boolean isConfigured() {
return order >= CONFIGURING.order; return this.order >= CONFIGURING.order;
} }
} }

View File

@ -60,10 +60,10 @@ public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
* @throws IllegalStateException if {@link SecurityBuilder} is null * @throws IllegalStateException if {@link SecurityBuilder} is null
*/ */
protected final B getBuilder() { protected final B getBuilder() {
if (securityBuilder == null) { if (this.securityBuilder == null) {
throw new IllegalStateException("securityBuilder cannot be null"); throw new IllegalStateException("securityBuilder cannot be null");
} }
return securityBuilder; return this.securityBuilder;
} }
/** /**
@ -108,7 +108,7 @@ public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) { public Object postProcess(Object object) {
for (ObjectPostProcessor opp : postProcessors) { for (ObjectPostProcessor opp : this.postProcessors) {
Class<?> oppClass = opp.getClass(); Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class); Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) { if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
@ -125,7 +125,7 @@ public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
*/ */
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor); boolean result = this.postProcessors.add(objectPostProcessor);
postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE); this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result; return result;
} }

View File

@ -220,15 +220,16 @@ public class AuthenticationManagerBuilder
@Override @Override
protected ProviderManager performBuild() throws Exception { protected ProviderManager performBuild() throws Exception {
if (!isConfigured()) { if (!isConfigured()) {
logger.debug("No authenticationProviders and no parentAuthenticationManager defined. Returning null."); this.logger.debug("No authenticationProviders and no parentAuthenticationManager defined. Returning null.");
return null; return null;
} }
ProviderManager providerManager = new ProviderManager(authenticationProviders, parentAuthenticationManager); ProviderManager providerManager = new ProviderManager(this.authenticationProviders,
if (eraseCredentials != null) { this.parentAuthenticationManager);
providerManager.setEraseCredentialsAfterAuthentication(eraseCredentials); if (this.eraseCredentials != null) {
providerManager.setEraseCredentialsAfterAuthentication(this.eraseCredentials);
} }
if (eventPublisher != null) { if (this.eventPublisher != null) {
providerManager.setAuthenticationEventPublisher(eventPublisher); providerManager.setAuthenticationEventPublisher(this.eventPublisher);
} }
providerManager = postProcess(providerManager); providerManager = postProcess(providerManager);
return providerManager; return providerManager;
@ -250,7 +251,7 @@ public class AuthenticationManagerBuilder
* false * false
*/ */
public boolean isConfigured() { public boolean isConfigured() {
return !authenticationProviders.isEmpty() || parentAuthenticationManager != null; return !this.authenticationProviders.isEmpty() || this.parentAuthenticationManager != null;
} }
/** /**

View File

@ -115,18 +115,18 @@ public class AuthenticationConfiguration {
return new AuthenticationManagerDelegator(authBuilder); return new AuthenticationManagerDelegator(authBuilder);
} }
for (GlobalAuthenticationConfigurerAdapter config : globalAuthConfigurers) { for (GlobalAuthenticationConfigurerAdapter config : this.globalAuthConfigurers) {
authBuilder.apply(config); authBuilder.apply(config);
} }
authenticationManager = authBuilder.build(); this.authenticationManager = authBuilder.build();
if (authenticationManager == null) { if (this.authenticationManager == null) {
authenticationManager = getAuthenticationManagerBean(); this.authenticationManager = getAuthenticationManagerBean();
} }
this.authenticationManagerInitialized = true; this.authenticationManagerInitialized = true;
return authenticationManager; return this.authenticationManager;
} }
@Autowired(required = false) @Autowired(required = false)
@ -148,7 +148,7 @@ public class AuthenticationConfiguration {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private <T> T lazyBean(Class<T> interfaceName) { private <T> T lazyBean(Class<T> interfaceName) {
LazyInitTargetSource lazyTargetSource = new LazyInitTargetSource(); LazyInitTargetSource lazyTargetSource = new LazyInitTargetSource();
String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.applicationContext,
interfaceName); interfaceName);
if (beanNamesForType.length == 0) { if (beanNamesForType.length == 0) {
return null; return null;
@ -168,20 +168,20 @@ public class AuthenticationConfiguration {
} }
lazyTargetSource.setTargetBeanName(beanName); lazyTargetSource.setTargetBeanName(beanName);
lazyTargetSource.setBeanFactory(applicationContext); lazyTargetSource.setBeanFactory(this.applicationContext);
ProxyFactoryBean proxyFactory = new ProxyFactoryBean(); ProxyFactoryBean proxyFactory = new ProxyFactoryBean();
proxyFactory = objectPostProcessor.postProcess(proxyFactory); proxyFactory = this.objectPostProcessor.postProcess(proxyFactory);
proxyFactory.setTargetSource(lazyTargetSource); proxyFactory.setTargetSource(lazyTargetSource);
return (T) proxyFactory.getObject(); return (T) proxyFactory.getObject();
} }
private List<String> getPrimaryBeanNames(String[] beanNamesForType) { private List<String> getPrimaryBeanNames(String[] beanNamesForType) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
if (!(applicationContext instanceof ConfigurableApplicationContext)) { if (!(this.applicationContext instanceof ConfigurableApplicationContext)) {
return Collections.emptyList(); return Collections.emptyList();
} }
for (String beanName : beanNamesForType) { for (String beanName : beanNamesForType) {
if (((ConfigurableApplicationContext) applicationContext).getBeanFactory().getBeanDefinition(beanName) if (((ConfigurableApplicationContext) this.applicationContext).getBeanFactory().getBeanDefinition(beanName)
.isPrimary()) { .isPrimary()) {
list.add(beanName); list.add(beanName);
} }
@ -214,7 +214,8 @@ public class AuthenticationConfiguration {
@Override @Override
public void init(AuthenticationManagerBuilder auth) { public void init(AuthenticationManagerBuilder auth) {
Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(EnableGlobalAuthentication.class); Map<String, Object> beansWithAnnotation = this.context
.getBeansWithAnnotation(EnableGlobalAuthentication.class);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Eagerly initializing " + beansWithAnnotation); logger.debug("Eagerly initializing " + beansWithAnnotation);
} }

View File

@ -98,8 +98,8 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator, LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator,
authoritiesPopulator); authoritiesPopulator);
ldapAuthenticationProvider.setAuthoritiesMapper(getAuthoritiesMapper()); ldapAuthenticationProvider.setAuthoritiesMapper(getAuthoritiesMapper());
if (userDetailsContextMapper != null) { if (this.userDetailsContextMapper != null) {
ldapAuthenticationProvider.setUserDetailsContextMapper(userDetailsContextMapper); ldapAuthenticationProvider.setUserDetailsContextMapper(this.userDetailsContextMapper);
} }
return ldapAuthenticationProvider; return ldapAuthenticationProvider;
} }
@ -132,15 +132,15 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
* @return the {@link LdapAuthoritiesPopulator} * @return the {@link LdapAuthoritiesPopulator}
*/ */
private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator() { private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator() {
if (ldapAuthoritiesPopulator != null) { if (this.ldapAuthoritiesPopulator != null) {
return ldapAuthoritiesPopulator; return this.ldapAuthoritiesPopulator;
} }
DefaultLdapAuthoritiesPopulator defaultAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(contextSource, DefaultLdapAuthoritiesPopulator defaultAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(
groupSearchBase); this.contextSource, this.groupSearchBase);
defaultAuthoritiesPopulator.setGroupRoleAttribute(groupRoleAttribute); defaultAuthoritiesPopulator.setGroupRoleAttribute(this.groupRoleAttribute);
defaultAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter); defaultAuthoritiesPopulator.setGroupSearchFilter(this.groupSearchFilter);
defaultAuthoritiesPopulator.setSearchSubtree(groupSearchSubtree); defaultAuthoritiesPopulator.setSearchSubtree(this.groupSearchSubtree);
defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix); defaultAuthoritiesPopulator.setRolePrefix(this.rolePrefix);
this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator; this.ldapAuthoritiesPopulator = defaultAuthoritiesPopulator;
@ -169,8 +169,8 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
* @throws Exception if errors in {@link SimpleAuthorityMapper#afterPropertiesSet()} * @throws Exception if errors in {@link SimpleAuthorityMapper#afterPropertiesSet()}
*/ */
protected GrantedAuthoritiesMapper getAuthoritiesMapper() throws Exception { protected GrantedAuthoritiesMapper getAuthoritiesMapper() throws Exception {
if (authoritiesMapper != null) { if (this.authoritiesMapper != null) {
return authoritiesMapper; return this.authoritiesMapper;
} }
SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper(); SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
@ -186,14 +186,14 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
* @return the {@link LdapAuthenticator} to use * @return the {@link LdapAuthenticator} to use
*/ */
private LdapAuthenticator createLdapAuthenticator(BaseLdapPathContextSource contextSource) { private LdapAuthenticator createLdapAuthenticator(BaseLdapPathContextSource contextSource) {
AbstractLdapAuthenticator ldapAuthenticator = passwordEncoder == null ? createBindAuthenticator(contextSource) AbstractLdapAuthenticator ldapAuthenticator = this.passwordEncoder == null
: createPasswordCompareAuthenticator(contextSource); ? createBindAuthenticator(contextSource) : createPasswordCompareAuthenticator(contextSource);
LdapUserSearch userSearch = createUserSearch(); LdapUserSearch userSearch = createUserSearch();
if (userSearch != null) { if (userSearch != null) {
ldapAuthenticator.setUserSearch(userSearch); ldapAuthenticator.setUserSearch(userSearch);
} }
if (userDnPatterns != null && userDnPatterns.length > 0) { if (this.userDnPatterns != null && this.userDnPatterns.length > 0) {
ldapAuthenticator.setUserDnPatterns(userDnPatterns); ldapAuthenticator.setUserDnPatterns(this.userDnPatterns);
} }
return postProcess(ldapAuthenticator); return postProcess(ldapAuthenticator);
} }
@ -206,10 +206,10 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
private PasswordComparisonAuthenticator createPasswordCompareAuthenticator( private PasswordComparisonAuthenticator createPasswordCompareAuthenticator(
BaseLdapPathContextSource contextSource) { BaseLdapPathContextSource contextSource) {
PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator(contextSource); PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator(contextSource);
if (passwordAttribute != null) { if (this.passwordAttribute != null) {
ldapAuthenticator.setPasswordAttributeName(passwordAttribute); ldapAuthenticator.setPasswordAttributeName(this.passwordAttribute);
} }
ldapAuthenticator.setPasswordEncoder(passwordEncoder); ldapAuthenticator.setPasswordEncoder(this.passwordEncoder);
return ldapAuthenticator; return ldapAuthenticator;
} }
@ -223,10 +223,10 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
} }
private LdapUserSearch createUserSearch() { private LdapUserSearch createUserSearch() {
if (userSearchFilter == null) { if (this.userSearchFilter == null) {
return null; return null;
} }
return new FilterBasedLdapUserSearch(userSearchBase, userSearchFilter, contextSource); return new FilterBasedLdapUserSearch(this.userSearchBase, this.userSearchFilter, this.contextSource);
} }
/** /**
@ -247,7 +247,7 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
* @return the {@link ContextSourceBuilder} for further customizations * @return the {@link ContextSourceBuilder} for further customizations
*/ */
public ContextSourceBuilder contextSource() { public ContextSourceBuilder contextSource() {
return contextSourceBuilder; return this.contextSourceBuilder;
} }
/** /**
@ -540,12 +540,12 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
} }
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(getProviderUrl()); DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(getProviderUrl());
if (managerDn != null) { if (this.managerDn != null) {
contextSource.setUserDn(managerDn); contextSource.setUserDn(this.managerDn);
if (managerPassword == null) { if (this.managerPassword == null) {
throw new IllegalStateException("managerPassword is required if managerDn is supplied"); throw new IllegalStateException("managerPassword is required if managerDn is supplied");
} }
contextSource.setPassword(managerPassword); contextSource.setPassword(this.managerPassword);
} }
contextSource = postProcess(contextSource); contextSource = postProcess(contextSource);
return contextSource; return contextSource;
@ -570,10 +570,10 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
} }
private int getPort() { private int getPort() {
if (port == null) { if (this.port == null) {
port = getDefaultPort(); this.port = getDefaultPort();
} }
return port; return this.port;
} }
private int getDefaultPort() { private int getDefaultPort() {
@ -586,10 +586,10 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
} }
private String getProviderUrl() { private String getProviderUrl() {
if (url == null) { if (this.url == null) {
return "ldap://127.0.0.1:" + getPort() + "/" + root; return "ldap://127.0.0.1:" + getPort() + "/" + this.root;
} }
return url; return this.url;
} }
private ContextSourceBuilder() { private ContextSourceBuilder() {
@ -598,10 +598,10 @@ public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuild
} }
private BaseLdapPathContextSource getContextSource() throws Exception { private BaseLdapPathContextSource getContextSource() throws Exception {
if (contextSource == null) { if (this.contextSource == null) {
contextSource = contextSourceBuilder.build(); this.contextSource = this.contextSourceBuilder.build();
} }
return contextSource; return this.contextSource;
} }
/** /**

View File

@ -150,7 +150,7 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
@Override @Override
protected void initUserDetailsService() throws Exception { protected void initUserDetailsService() throws Exception {
if (!initScripts.isEmpty()) { if (!this.initScripts.isEmpty()) {
getDataSourceInit().afterPropertiesSet(); getDataSourceInit().afterPropertiesSet();
} }
super.initUserDetailsService(); super.initUserDetailsService();
@ -173,14 +173,14 @@ public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B
protected DatabasePopulator getDatabasePopulator() { protected DatabasePopulator getDatabasePopulator() {
ResourceDatabasePopulator dbp = new ResourceDatabasePopulator(); ResourceDatabasePopulator dbp = new ResourceDatabasePopulator();
dbp.setScripts(initScripts.toArray(new Resource[0])); dbp.setScripts(this.initScripts.toArray(new Resource[0]));
return dbp; return dbp;
} }
private DataSourceInitializer getDataSourceInit() { private DataSourceInitializer getDataSourceInit() {
DataSourceInitializer dsi = new DataSourceInitializer(); DataSourceInitializer dsi = new DataSourceInitializer();
dsi.setDatabasePopulator(getDatabasePopulator()); dsi.setDatabasePopulator(getDatabasePopulator());
dsi.setDataSource(dataSource); dsi.setDataSource(this.dataSource);
return dsi; return dsi;
} }

View File

@ -54,7 +54,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
*/ */
@Override @Override
protected void initUserDetailsService() throws Exception { protected void initUserDetailsService() throws Exception {
for (UserDetailsBuilder userBuilder : userBuilders) { for (UserDetailsBuilder userBuilder : this.userBuilders) {
getUserDetailsService().createUser(userBuilder.build()); getUserDetailsService().createUser(userBuilder.build());
} }
for (UserDetails userDetails : this.users) { for (UserDetails userDetails : this.users) {
@ -124,7 +124,7 @@ public class UserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>, C
* @return the {@link UserDetailsManagerConfigurer} for method chaining * @return the {@link UserDetailsManagerConfigurer} for method chaining
*/ */
public C and() { public C and() {
return builder; return this.builder;
} }
/** /**

View File

@ -45,7 +45,7 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
*/ */
protected AbstractDaoAuthenticationConfigurer(U userDetailsService) { protected AbstractDaoAuthenticationConfigurer(U userDetailsService) {
this.userDetailsService = userDetailsService; this.userDetailsService = userDetailsService;
provider.setUserDetailsService(userDetailsService); this.provider.setUserDetailsService(userDetailsService);
if (userDetailsService instanceof UserDetailsPasswordService) { if (userDetailsService instanceof UserDetailsPasswordService) {
this.provider.setUserDetailsPasswordService((UserDetailsPasswordService) userDetailsService); this.provider.setUserDetailsPasswordService((UserDetailsPasswordService) userDetailsService);
} }
@ -70,19 +70,19 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public C passwordEncoder(PasswordEncoder passwordEncoder) { public C passwordEncoder(PasswordEncoder passwordEncoder) {
provider.setPasswordEncoder(passwordEncoder); this.provider.setPasswordEncoder(passwordEncoder);
return (C) this; return (C) this;
} }
public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) { public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) {
provider.setUserDetailsPasswordService(passwordManager); this.provider.setUserDetailsPasswordService(passwordManager);
return (C) this; return (C) this;
} }
@Override @Override
public void configure(B builder) throws Exception { public void configure(B builder) throws Exception {
provider = postProcess(provider); this.provider = postProcess(this.provider);
builder.authenticationProvider(provider); builder.authenticationProvider(this.provider);
} }
/** /**
@ -92,7 +92,7 @@ abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuil
* {@link DaoAuthenticationProvider} * {@link DaoAuthenticationProvider}
*/ */
public U getUserDetailsService() { public U getUserDetailsService() {
return userDetailsService; return this.userDetailsService;
} }
} }

View File

@ -91,7 +91,7 @@ final class AutowireBeanFactoryObjectPostProcessor
*/ */
@Override @Override
public void afterSingletonsInstantiated() { public void afterSingletonsInstantiated() {
for (SmartInitializingSingleton singleton : smartSingletons) { for (SmartInitializingSingleton singleton : this.smartSingletons) {
singleton.afterSingletonsInstantiated(); singleton.afterSingletonsInstantiated();
} }
} }

View File

@ -136,12 +136,12 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
public MethodInterceptor methodSecurityInterceptor(MethodSecurityMetadataSource methodSecurityMetadataSource) { public MethodInterceptor methodSecurityInterceptor(MethodSecurityMetadataSource methodSecurityMetadataSource) {
this.methodSecurityInterceptor = isAspectJ() ? new AspectJMethodSecurityInterceptor() this.methodSecurityInterceptor = isAspectJ() ? new AspectJMethodSecurityInterceptor()
: new MethodSecurityInterceptor(); : new MethodSecurityInterceptor();
methodSecurityInterceptor.setAccessDecisionManager(accessDecisionManager()); this.methodSecurityInterceptor.setAccessDecisionManager(accessDecisionManager());
methodSecurityInterceptor.setAfterInvocationManager(afterInvocationManager()); this.methodSecurityInterceptor.setAfterInvocationManager(afterInvocationManager());
methodSecurityInterceptor.setSecurityMetadataSource(methodSecurityMetadataSource); this.methodSecurityInterceptor.setSecurityMetadataSource(methodSecurityMetadataSource);
RunAsManager runAsManager = runAsManager(); RunAsManager runAsManager = runAsManager();
if (runAsManager != null) { if (runAsManager != null) {
methodSecurityInterceptor.setRunAsManager(runAsManager); this.methodSecurityInterceptor.setRunAsManager(runAsManager);
} }
return this.methodSecurityInterceptor; return this.methodSecurityInterceptor;
@ -185,7 +185,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
private <T> T getSingleBeanOrNull(Class<T> type) { private <T> T getSingleBeanOrNull(Class<T> type) {
try { try {
return context.getBean(type); return this.context.getBean(type);
} }
catch (NoSuchBeanDefinitionException e) { catch (NoSuchBeanDefinitionException e) {
} }
@ -279,7 +279,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
* @return the {@link MethodSecurityExpressionHandler} to use * @return the {@link MethodSecurityExpressionHandler} to use
*/ */
protected MethodSecurityExpressionHandler createExpressionHandler() { protected MethodSecurityExpressionHandler createExpressionHandler() {
return defaultMethodExpressionHandler; return this.defaultMethodExpressionHandler;
} }
/** /**
@ -288,10 +288,10 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
* @return a non {@code null} {@link MethodSecurityExpressionHandler} * @return a non {@code null} {@link MethodSecurityExpressionHandler}
*/ */
protected final MethodSecurityExpressionHandler getExpressionHandler() { protected final MethodSecurityExpressionHandler getExpressionHandler() {
if (expressionHandler == null) { if (this.expressionHandler == null) {
expressionHandler = createExpressionHandler(); this.expressionHandler = createExpressionHandler();
} }
return expressionHandler; return this.expressionHandler;
} }
/** /**
@ -313,20 +313,20 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
* @return the {@link AuthenticationManager} to use * @return the {@link AuthenticationManager} to use
*/ */
protected AuthenticationManager authenticationManager() throws Exception { protected AuthenticationManager authenticationManager() throws Exception {
if (authenticationManager == null) { if (this.authenticationManager == null) {
DefaultAuthenticationEventPublisher eventPublisher = objectPostProcessor DefaultAuthenticationEventPublisher eventPublisher = this.objectPostProcessor
.postProcess(new DefaultAuthenticationEventPublisher()); .postProcess(new DefaultAuthenticationEventPublisher());
auth = new AuthenticationManagerBuilder(objectPostProcessor); this.auth = new AuthenticationManagerBuilder(this.objectPostProcessor);
auth.authenticationEventPublisher(eventPublisher); this.auth.authenticationEventPublisher(eventPublisher);
configure(auth); configure(this.auth);
if (disableAuthenticationRegistry) { if (this.disableAuthenticationRegistry) {
authenticationManager = getAuthenticationConfiguration().getAuthenticationManager(); this.authenticationManager = getAuthenticationConfiguration().getAuthenticationManager();
} }
else { else {
authenticationManager = auth.build(); this.authenticationManager = this.auth.build();
} }
} }
return authenticationManager; return this.authenticationManager;
} }
/** /**
@ -405,13 +405,13 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
public final void setImportMetadata(AnnotationMetadata importMetadata) { public final void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> annotationAttributes = importMetadata Map<String, Object> annotationAttributes = importMetadata
.getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName()); .getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName());
enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes); this.enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes);
} }
@Autowired(required = false) @Autowired(required = false)
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) { public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
this.objectPostProcessor = objectPostProcessor; this.objectPostProcessor = objectPostProcessor;
this.defaultMethodExpressionHandler = objectPostProcessor.postProcess(defaultMethodExpressionHandler); this.defaultMethodExpressionHandler = objectPostProcessor.postProcess(this.defaultMethodExpressionHandler);
} }
@Autowired(required = false) @Autowired(required = false)
@ -429,7 +429,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
} }
private AuthenticationConfiguration getAuthenticationConfiguration() { private AuthenticationConfiguration getAuthenticationConfiguration() {
return context.getBean(AuthenticationConfiguration.class); return this.context.getBean(AuthenticationConfiguration.class);
} }
private boolean prePostEnabled() { private boolean prePostEnabled() {
@ -453,7 +453,7 @@ public class GlobalMethodSecurityConfiguration implements ImportAware, SmartInit
} }
private AnnotationAttributes enableMethodSecurity() { private AnnotationAttributes enableMethodSecurity() {
if (enableMethodSecurity == null) { if (this.enableMethodSecurity == null) {
// if it is null look at this instance (i.e. a subclass was used) // if it is null look at this instance (i.e. a subclass was used)
EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(),
EnableGlobalMethodSecurity.class); EnableGlobalMethodSecurity.class);

View File

@ -54,7 +54,7 @@ class ReactiveMethodSecurityConfiguration implements ImportAware {
public MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source) { public MethodSecurityMetadataSourceAdvisor methodSecurityInterceptor(AbstractMethodSecurityMetadataSource source) {
MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor( MethodSecurityMetadataSourceAdvisor advisor = new MethodSecurityMetadataSourceAdvisor(
"securityMethodInterceptor", source, "methodMetadataSource"); "securityMethodInterceptor", source, "methodMetadataSource");
advisor.setOrder(advisorOrder); advisor.setOrder(this.advisorOrder);
return advisor; return advisor;
} }

View File

@ -74,27 +74,29 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
put(CorsFilter.class, order.next()); put(CorsFilter.class, order.next());
put(CsrfFilter.class, order.next()); put(CsrfFilter.class, order.next());
put(LogoutFilter.class, order.next()); put(LogoutFilter.class, order.next());
filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter", this.filterToOrder.put(
"org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter",
order.next()); order.next());
filterToOrder.put( this.filterToOrder.put(
"org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationRequestFilter", "org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationRequestFilter",
order.next()); order.next());
put(X509AuthenticationFilter.class, order.next()); put(X509AuthenticationFilter.class, order.next());
put(AbstractPreAuthenticatedProcessingFilter.class, order.next()); put(AbstractPreAuthenticatedProcessingFilter.class, order.next());
filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter", order.next()); this.filterToOrder.put("org.springframework.security.cas.web.CasAuthenticationFilter", order.next());
filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter", this.filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter",
order.next()); order.next());
filterToOrder.put( this.filterToOrder.put(
"org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter", "org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter",
order.next()); order.next());
put(UsernamePasswordAuthenticationFilter.class, order.next()); put(UsernamePasswordAuthenticationFilter.class, order.next());
order.next(); // gh-8105 order.next(); // gh-8105
filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order.next()); this.filterToOrder.put("org.springframework.security.openid.OpenIDAuthenticationFilter", order.next());
put(DefaultLoginPageGeneratingFilter.class, order.next()); put(DefaultLoginPageGeneratingFilter.class, order.next());
put(DefaultLogoutPageGeneratingFilter.class, order.next()); put(DefaultLogoutPageGeneratingFilter.class, order.next());
put(ConcurrentSessionFilter.class, order.next()); put(ConcurrentSessionFilter.class, order.next());
put(DigestAuthenticationFilter.class, order.next()); put(DigestAuthenticationFilter.class, order.next());
filterToOrder.put("org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter", this.filterToOrder.put(
"org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter",
order.next()); order.next());
put(BasicAuthenticationFilter.class, order.next()); put(BasicAuthenticationFilter.class, order.next());
put(RequestCacheAwareFilter.class, order.next()); put(RequestCacheAwareFilter.class, order.next());
@ -102,7 +104,7 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
put(JaasApiIntegrationFilter.class, order.next()); put(JaasApiIntegrationFilter.class, order.next());
put(RememberMeAuthenticationFilter.class, order.next()); put(RememberMeAuthenticationFilter.class, order.next());
put(AnonymousAuthenticationFilter.class, order.next()); put(AnonymousAuthenticationFilter.class, order.next());
filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter", this.filterToOrder.put("org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter",
order.next()); order.next());
put(SessionManagementFilter.class, order.next()); put(SessionManagementFilter.class, order.next());
put(ExceptionTranslationFilter.class, order.next()); put(ExceptionTranslationFilter.class, order.next());
@ -174,7 +176,7 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
private void put(Class<? extends Filter> filter, int position) { private void put(Class<? extends Filter> filter, int position) {
String className = filter.getName(); String className = filter.getName();
filterToOrder.put(className, position); this.filterToOrder.put(className, position);
} }
/** /**
@ -185,7 +187,7 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
*/ */
private Integer getOrder(Class<?> clazz) { private Integer getOrder(Class<?> clazz) {
while (clazz != null) { while (clazz != null) {
Integer result = filterToOrder.get(clazz.getName()); Integer result = this.filterToOrder.get(clazz.getName());
if (result != null) { if (result != null) {
return result; return result;
} }

View File

@ -2518,8 +2518,8 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
@Override @Override
protected DefaultSecurityFilterChain performBuild() { protected DefaultSecurityFilterChain performBuild() {
filters.sort(comparator); this.filters.sort(this.comparator);
return new DefaultSecurityFilterChain(requestMatcher, filters); return new DefaultSecurityFilterChain(this.requestMatcher, this.filters);
} }
/* /*
@ -2557,7 +2557,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
* addFilterAfter(javax .servlet.Filter, java.lang.Class) * addFilterAfter(javax .servlet.Filter, java.lang.Class)
*/ */
public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) { public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {
comparator.registerAfter(filter.getClass(), afterFilter); this.comparator.registerAfter(filter.getClass(), afterFilter);
return addFilter(filter); return addFilter(filter);
} }
@ -2568,7 +2568,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
* addFilterBefore( javax.servlet.Filter, java.lang.Class) * addFilterBefore( javax.servlet.Filter, java.lang.Class)
*/ */
public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) { public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) {
comparator.registerBefore(filter.getClass(), beforeFilter); this.comparator.registerBefore(filter.getClass(), beforeFilter);
return addFilter(filter); return addFilter(filter);
} }
@ -2581,7 +2581,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
*/ */
public HttpSecurity addFilter(Filter filter) { public HttpSecurity addFilter(Filter filter) {
Class<? extends Filter> filterClass = filter.getClass(); Class<? extends Filter> filterClass = filter.getClass();
if (!comparator.isRegistered(filterClass)) { if (!this.comparator.isRegistered(filterClass)) {
throw new IllegalArgumentException("The Filter class " + filterClass.getName() throw new IllegalArgumentException("The Filter class " + filterClass.getName()
+ " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead."); + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
} }
@ -2720,7 +2720,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
* @return the {@link RequestMatcherConfigurer} for further customizations * @return the {@link RequestMatcherConfigurer} for further customizations
*/ */
public RequestMatcherConfigurer requestMatchers() { public RequestMatcherConfigurer requestMatchers() {
return requestMatcherConfigurer; return this.requestMatcherConfigurer;
} }
/** /**
@ -2819,7 +2819,7 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
* @return the {@link HttpSecurity} for further customizations * @return the {@link HttpSecurity} for further customizations
*/ */
public HttpSecurity requestMatchers(Customizer<RequestMatcherConfigurer> requestMatcherCustomizer) { public HttpSecurity requestMatchers(Customizer<RequestMatcherConfigurer> requestMatcherCustomizer) {
requestMatcherCustomizer.customize(requestMatcherConfigurer); requestMatcherCustomizer.customize(this.requestMatcherConfigurer);
return HttpSecurity.this; return HttpSecurity.this;
} }

View File

@ -101,7 +101,7 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
private DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); private DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
private SecurityExpressionHandler<FilterInvocation> expressionHandler = defaultWebSecurityExpressionHandler; private SecurityExpressionHandler<FilterInvocation> expressionHandler = this.defaultWebSecurityExpressionHandler;
private Runnable postBuildAction = () -> { private Runnable postBuildAction = () -> {
}; };
@ -156,7 +156,7 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
* should be ignored * should be ignored
*/ */
public IgnoredRequestConfigurer ignoring() { public IgnoredRequestConfigurer ignoring() {
return ignoredRequestRegistry; return this.ignoredRequestRegistry;
} }
/** /**
@ -230,7 +230,7 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
* @return the {@link SecurityExpressionHandler} for further customizations * @return the {@link SecurityExpressionHandler} for further customizations
*/ */
public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() { public SecurityExpressionHandler<FilterInvocation> getExpressionHandler() {
return expressionHandler; return this.expressionHandler;
} }
/** /**
@ -238,11 +238,11 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
* @return the {@link WebInvocationPrivilegeEvaluator} for further customizations * @return the {@link WebInvocationPrivilegeEvaluator} for further customizations
*/ */
public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() { public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() {
if (privilegeEvaluator != null) { if (this.privilegeEvaluator != null) {
return privilegeEvaluator; return this.privilegeEvaluator;
} }
return filterSecurityInterceptor == null ? null return this.filterSecurityInterceptor == null ? null
: new DefaultWebInvocationPrivilegeEvaluator(filterSecurityInterceptor); : new DefaultWebInvocationPrivilegeEvaluator(this.filterSecurityInterceptor);
} }
/** /**
@ -268,39 +268,39 @@ public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter,
@Override @Override
protected Filter performBuild() throws Exception { protected Filter performBuild() throws Exception {
Assert.state(!securityFilterChainBuilders.isEmpty(), Assert.state(!this.securityFilterChainBuilders.isEmpty(),
() -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. " () -> "At least one SecurityBuilder<? extends SecurityFilterChain> needs to be specified. "
+ "Typically this is done by exposing a SecurityFilterChain bean " + "Typically this is done by exposing a SecurityFilterChain bean "
+ "or by adding a @Configuration that extends WebSecurityConfigurerAdapter. " + "or by adding a @Configuration that extends WebSecurityConfigurerAdapter. "
+ "More advanced users can invoke " + WebSecurity.class.getSimpleName() + "More advanced users can invoke " + WebSecurity.class.getSimpleName()
+ ".addSecurityFilterChainBuilder directly"); + ".addSecurityFilterChainBuilder directly");
int chainSize = ignoredRequests.size() + securityFilterChainBuilders.size(); int chainSize = this.ignoredRequests.size() + this.securityFilterChainBuilders.size();
List<SecurityFilterChain> securityFilterChains = new ArrayList<>(chainSize); List<SecurityFilterChain> securityFilterChains = new ArrayList<>(chainSize);
for (RequestMatcher ignoredRequest : ignoredRequests) { for (RequestMatcher ignoredRequest : this.ignoredRequests) {
securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest)); securityFilterChains.add(new DefaultSecurityFilterChain(ignoredRequest));
} }
for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : securityFilterChainBuilders) { for (SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder : this.securityFilterChainBuilders) {
securityFilterChains.add(securityFilterChainBuilder.build()); securityFilterChains.add(securityFilterChainBuilder.build());
} }
FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains); FilterChainProxy filterChainProxy = new FilterChainProxy(securityFilterChains);
if (httpFirewall != null) { if (this.httpFirewall != null) {
filterChainProxy.setFirewall(httpFirewall); filterChainProxy.setFirewall(this.httpFirewall);
} }
if (requestRejectedHandler != null) { if (this.requestRejectedHandler != null) {
filterChainProxy.setRequestRejectedHandler(requestRejectedHandler); filterChainProxy.setRequestRejectedHandler(this.requestRejectedHandler);
} }
filterChainProxy.afterPropertiesSet(); filterChainProxy.afterPropertiesSet();
Filter result = filterChainProxy; Filter result = filterChainProxy;
if (debugEnabled) { if (this.debugEnabled) {
logger.warn("\n\n" + "********************************************************************\n" this.logger.warn("\n\n" + "********************************************************************\n"
+ "********** Security debugging is enabled. *************\n" + "********** Security debugging is enabled. *************\n"
+ "********** This may include sensitive information. *************\n" + "********** This may include sensitive information. *************\n"
+ "********** Do not use in a production system! *************\n" + "********** Do not use in a production system! *************\n"
+ "********************************************************************\n\n"); + "********************************************************************\n\n");
result = new DebugFilter(filterChainProxy); result = new DebugFilter(filterChainProxy);
} }
postBuildAction.run(); this.postBuildAction.run();
return result; return result;
} }

View File

@ -48,7 +48,7 @@ final class AutowiredWebSecurityConfigurersIgnoreParents {
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public List<SecurityConfigurer<Filter, WebSecurity>> getWebSecurityConfigurers() { public List<SecurityConfigurer<Filter, WebSecurity>> getWebSecurityConfigurers() {
List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers = new ArrayList<>(); List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers = new ArrayList<>();
Map<String, WebSecurityConfigurer> beansOfType = beanFactory.getBeansOfType(WebSecurityConfigurer.class); Map<String, WebSecurityConfigurer> beansOfType = this.beanFactory.getBeansOfType(WebSecurityConfigurer.class);
for (Entry<String, WebSecurityConfigurer> entry : beansOfType.entrySet()) { for (Entry<String, WebSecurityConfigurer> entry : beansOfType.entrySet()) {
webSecurityConfigurers.add(entry.getValue()); webSecurityConfigurers.add(entry.getValue());
} }

View File

@ -85,7 +85,7 @@ class HttpSecurityConfiguration {
this.objectPostProcessor, passwordEncoder); this.objectPostProcessor, passwordEncoder);
authenticationBuilder.parentAuthenticationManager(authenticationManager()); authenticationBuilder.parentAuthenticationManager(authenticationManager());
HttpSecurity http = new HttpSecurity(objectPostProcessor, authenticationBuilder, createSharedObjects()); HttpSecurity http = new HttpSecurity(this.objectPostProcessor, authenticationBuilder, createSharedObjects());
http.csrf(withDefaults()).addFilter(new WebAsyncManagerIntegrationFilter()).exceptionHandling(withDefaults()) http.csrf(withDefaults()).addFilter(new WebAsyncManagerIntegrationFilter()).exceptionHandling(withDefaults())
.headers(withDefaults()).sessionManagement(withDefaults()).securityContext(withDefaults()) .headers(withDefaults()).sessionManagement(withDefaults()).securityContext(withDefaults())
.requestCache(withDefaults()).anonymous(withDefaults()).servletApi(withDefaults()) .requestCache(withDefaults()).anonymous(withDefaults()).servletApi(withDefaults())
@ -105,7 +105,7 @@ class HttpSecurityConfiguration {
private Map<Class<?>, Object> createSharedObjects() { private Map<Class<?>, Object> createSharedObjects() {
Map<Class<?>, Object> sharedObjects = new HashMap<>(); Map<Class<?>, Object> sharedObjects = new HashMap<>();
sharedObjects.put(ApplicationContext.class, context); sharedObjects.put(ApplicationContext.class, this.context);
return sharedObjects; return sharedObjects;
} }

View File

@ -53,13 +53,13 @@ class WebMvcSecurityConfiguration implements WebMvcConfigurer, ApplicationContex
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
AuthenticationPrincipalArgumentResolver authenticationPrincipalResolver = new AuthenticationPrincipalArgumentResolver(); AuthenticationPrincipalArgumentResolver authenticationPrincipalResolver = new AuthenticationPrincipalArgumentResolver();
authenticationPrincipalResolver.setBeanResolver(beanResolver); authenticationPrincipalResolver.setBeanResolver(this.beanResolver);
argumentResolvers.add(authenticationPrincipalResolver); argumentResolvers.add(authenticationPrincipalResolver);
argumentResolvers argumentResolvers
.add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver()); .add(new org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver());
CurrentSecurityContextArgumentResolver currentSecurityContextArgumentResolver = new CurrentSecurityContextArgumentResolver(); CurrentSecurityContextArgumentResolver currentSecurityContextArgumentResolver = new CurrentSecurityContextArgumentResolver();
currentSecurityContextArgumentResolver.setBeanResolver(beanResolver); currentSecurityContextArgumentResolver.setBeanResolver(this.beanResolver);
argumentResolvers.add(currentSecurityContextArgumentResolver); argumentResolvers.add(currentSecurityContextArgumentResolver);
argumentResolvers.add(new CsrfTokenArgumentResolver()); argumentResolvers.add(new CsrfTokenArgumentResolver());
} }

View File

@ -88,7 +88,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
@Bean @Bean
@DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) @DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public SecurityExpressionHandler<FilterInvocation> webSecurityExpressionHandler() { public SecurityExpressionHandler<FilterInvocation> webSecurityExpressionHandler() {
return webSecurity.getExpressionHandler(); return this.webSecurity.getExpressionHandler();
} }
/** /**
@ -98,28 +98,28 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
*/ */
@Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) @Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public Filter springSecurityFilterChain() throws Exception { public Filter springSecurityFilterChain() throws Exception {
boolean hasConfigurers = webSecurityConfigurers != null && !webSecurityConfigurers.isEmpty(); boolean hasConfigurers = this.webSecurityConfigurers != null && !this.webSecurityConfigurers.isEmpty();
boolean hasFilterChain = !securityFilterChains.isEmpty(); boolean hasFilterChain = !this.securityFilterChains.isEmpty();
if (hasConfigurers && hasFilterChain) { if (hasConfigurers && hasFilterChain) {
throw new IllegalStateException( throw new IllegalStateException(
"Found WebSecurityConfigurerAdapter as well as SecurityFilterChain." + "Please select just one."); "Found WebSecurityConfigurerAdapter as well as SecurityFilterChain." + "Please select just one.");
} }
if (!hasConfigurers && !hasFilterChain) { if (!hasConfigurers && !hasFilterChain) {
WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor WebSecurityConfigurerAdapter adapter = this.objectObjectPostProcessor
.postProcess(new WebSecurityConfigurerAdapter() { .postProcess(new WebSecurityConfigurerAdapter() {
}); });
webSecurity.apply(adapter); this.webSecurity.apply(adapter);
} }
for (SecurityFilterChain securityFilterChain : securityFilterChains) { for (SecurityFilterChain securityFilterChain : this.securityFilterChains) {
webSecurity.addSecurityFilterChainBuilder(() -> securityFilterChain); this.webSecurity.addSecurityFilterChainBuilder(() -> securityFilterChain);
for (Filter filter : securityFilterChain.getFilters()) { for (Filter filter : securityFilterChain.getFilters()) {
if (filter instanceof FilterSecurityInterceptor) { if (filter instanceof FilterSecurityInterceptor) {
webSecurity.securityInterceptor((FilterSecurityInterceptor) filter); this.webSecurity.securityInterceptor((FilterSecurityInterceptor) filter);
break; break;
} }
} }
} }
return webSecurity.build(); return this.webSecurity.build();
} }
/** /**
@ -130,7 +130,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
@Bean @Bean
@DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) @DependsOn(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
public WebInvocationPrivilegeEvaluator privilegeEvaluator() { public WebInvocationPrivilegeEvaluator privilegeEvaluator() {
return webSecurity.getPrivilegeEvaluator(); return this.webSecurity.getPrivilegeEvaluator();
} }
/** /**
@ -147,9 +147,9 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor, public void setFilterChainProxySecurityConfigurer(ObjectPostProcessor<Object> objectPostProcessor,
@Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers) @Value("#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}") List<SecurityConfigurer<Filter, WebSecurity>> webSecurityConfigurers)
throws Exception { throws Exception {
webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor)); this.webSecurity = objectPostProcessor.postProcess(new WebSecurity(objectPostProcessor));
if (debugEnabled != null) { if (this.debugEnabled != null) {
webSecurity.debug(debugEnabled); this.webSecurity.debug(this.debugEnabled);
} }
webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE); webSecurityConfigurers.sort(AnnotationAwareOrderComparator.INSTANCE);
@ -166,7 +166,7 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
previousConfig = config; previousConfig = config;
} }
for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) { for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) {
webSecurity.apply(webSecurityConfigurer); this.webSecurity.apply(webSecurityConfigurer);
} }
this.webSecurityConfigurers = webSecurityConfigurers; this.webSecurityConfigurers = webSecurityConfigurers;
} }
@ -231,9 +231,9 @@ public class WebSecurityConfiguration implements ImportAware, BeanClassLoaderAwa
Map<String, Object> enableWebSecurityAttrMap = importMetadata Map<String, Object> enableWebSecurityAttrMap = importMetadata
.getAnnotationAttributes(EnableWebSecurity.class.getName()); .getAnnotationAttributes(EnableWebSecurity.class.getName());
AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes.fromMap(enableWebSecurityAttrMap); AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes.fromMap(enableWebSecurityAttrMap);
debugEnabled = enableWebSecurityAttrs.getBoolean("debug"); this.debugEnabled = enableWebSecurityAttrs.getBoolean("debug");
if (webSecurity != null) { if (this.webSecurity != null) {
webSecurity.debug(debugEnabled); this.webSecurity.debug(this.debugEnabled);
} }
} }

View File

@ -195,21 +195,21 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
protected final HttpSecurity getHttp() throws Exception { protected final HttpSecurity getHttp() throws Exception {
if (http != null) { if (this.http != null) {
return http; return this.http;
} }
AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher(); AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher();
localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher); this.localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher);
AuthenticationManager authenticationManager = authenticationManager(); AuthenticationManager authenticationManager = authenticationManager();
authenticationBuilder.parentAuthenticationManager(authenticationManager); this.authenticationBuilder.parentAuthenticationManager(authenticationManager);
Map<Class<?>, Object> sharedObjects = createSharedObjects(); Map<Class<?>, Object> sharedObjects = createSharedObjects();
http = new HttpSecurity(objectPostProcessor, authenticationBuilder, sharedObjects); this.http = new HttpSecurity(this.objectPostProcessor, this.authenticationBuilder, sharedObjects);
if (!disableDefaults) { if (!this.disableDefaults) {
// @formatter:off // @formatter:off
http this.http
.csrf().and() .csrf().and()
.addFilter(new WebAsyncManagerIntegrationFilter()) .addFilter(new WebAsyncManagerIntegrationFilter())
.exceptionHandling().and() .exceptionHandling().and()
@ -227,11 +227,11 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
.loadFactories(AbstractHttpConfigurer.class, classLoader); .loadFactories(AbstractHttpConfigurer.class, classLoader);
for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) { for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) {
http.apply(configurer); this.http.apply(configurer);
} }
} }
configure(http); configure(this.http);
return http; return this.http;
} }
/** /**
@ -250,7 +250,7 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
* @throws Exception * @throws Exception
*/ */
public AuthenticationManager authenticationManagerBean() throws Exception { public AuthenticationManager authenticationManagerBean() throws Exception {
return new AuthenticationManagerDelegator(authenticationBuilder, context); return new AuthenticationManagerDelegator(this.authenticationBuilder, this.context);
} }
/** /**
@ -262,17 +262,17 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
* @throws Exception * @throws Exception
*/ */
protected AuthenticationManager authenticationManager() throws Exception { protected AuthenticationManager authenticationManager() throws Exception {
if (!authenticationManagerInitialized) { if (!this.authenticationManagerInitialized) {
configure(localConfigureAuthenticationBldr); configure(this.localConfigureAuthenticationBldr);
if (disableLocalConfigureAuthenticationBldr) { if (this.disableLocalConfigureAuthenticationBldr) {
authenticationManager = authenticationConfiguration.getAuthenticationManager(); this.authenticationManager = this.authenticationConfiguration.getAuthenticationManager();
} }
else { else {
authenticationManager = localConfigureAuthenticationBldr.build(); this.authenticationManager = this.localConfigureAuthenticationBldr.build();
} }
authenticationManagerInitialized = true; this.authenticationManagerInitialized = true;
} }
return authenticationManager; return this.authenticationManager;
} }
/** /**
@ -296,8 +296,8 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
* @see #userDetailsService() * @see #userDetailsService()
*/ */
public UserDetailsService userDetailsServiceBean() throws Exception { public UserDetailsService userDetailsServiceBean() throws Exception {
AuthenticationManagerBuilder globalAuthBuilder = context.getBean(AuthenticationManagerBuilder.class); AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class);
return new UserDetailsServiceDelegator(Arrays.asList(localConfigureAuthenticationBldr, globalAuthBuilder)); return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder));
} }
/** /**
@ -308,8 +308,8 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
* @return the {@link UserDetailsService} to use * @return the {@link UserDetailsService} to use
*/ */
protected UserDetailsService userDetailsService() { protected UserDetailsService userDetailsService() {
AuthenticationManagerBuilder globalAuthBuilder = context.getBean(AuthenticationManagerBuilder.class); AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class);
return new UserDetailsServiceDelegator(Arrays.asList(localConfigureAuthenticationBldr, globalAuthBuilder)); return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder));
} }
public void init(final WebSecurity web) throws Exception { public void init(final WebSecurity web) throws Exception {
@ -350,7 +350,7 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
* @throws Exception if an error occurs * @throws Exception if an error occurs
*/ */
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
logger.debug( this.logger.debug(
"Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); "Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
// @formatter:off // @formatter:off
@ -378,20 +378,20 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
ObjectPostProcessor<Object> objectPostProcessor = context.getBean(ObjectPostProcessor.class); ObjectPostProcessor<Object> objectPostProcessor = context.getBean(ObjectPostProcessor.class);
LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(context); LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(context);
authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, this.authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor,
passwordEncoder); passwordEncoder);
localConfigureAuthenticationBldr = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, this.localConfigureAuthenticationBldr = new DefaultPasswordEncoderAuthenticationManagerBuilder(
passwordEncoder) { objectPostProcessor, passwordEncoder) {
@Override @Override
public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) { public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) {
authenticationBuilder.eraseCredentials(eraseCredentials); WebSecurityConfigurerAdapter.this.authenticationBuilder.eraseCredentials(eraseCredentials);
return super.eraseCredentials(eraseCredentials); return super.eraseCredentials(eraseCredentials);
} }
@Override @Override
public AuthenticationManagerBuilder authenticationEventPublisher( public AuthenticationManagerBuilder authenticationEventPublisher(
AuthenticationEventPublisher eventPublisher) { AuthenticationEventPublisher eventPublisher) {
authenticationBuilder.authenticationEventPublisher(eventPublisher); WebSecurityConfigurerAdapter.this.authenticationBuilder.authenticationEventPublisher(eventPublisher);
return super.authenticationEventPublisher(eventPublisher); return super.authenticationEventPublisher(eventPublisher);
} }
}; };
@ -430,11 +430,11 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
*/ */
private Map<Class<?>, Object> createSharedObjects() { private Map<Class<?>, Object> createSharedObjects() {
Map<Class<?>, Object> sharedObjects = new HashMap<>(); Map<Class<?>, Object> sharedObjects = new HashMap<>();
sharedObjects.putAll(localConfigureAuthenticationBldr.getSharedObjects()); sharedObjects.putAll(this.localConfigureAuthenticationBldr.getSharedObjects());
sharedObjects.put(UserDetailsService.class, userDetailsService()); sharedObjects.put(UserDetailsService.class, userDetailsService());
sharedObjects.put(ApplicationContext.class, context); sharedObjects.put(ApplicationContext.class, this.context);
sharedObjects.put(ContentNegotiationStrategy.class, contentNegotiationStrategy); sharedObjects.put(ContentNegotiationStrategy.class, this.contentNegotiationStrategy);
sharedObjects.put(AuthenticationTrustResolver.class, trustResolver); sharedObjects.put(AuthenticationTrustResolver.class, this.trustResolver);
return sharedObjects; return sharedObjects;
} }
@ -462,27 +462,27 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
} }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (delegate != null) { if (this.delegate != null) {
return delegate.loadUserByUsername(username); return this.delegate.loadUserByUsername(username);
} }
synchronized (delegateMonitor) { synchronized (this.delegateMonitor) {
if (delegate == null) { if (this.delegate == null) {
for (AuthenticationManagerBuilder delegateBuilder : delegateBuilders) { for (AuthenticationManagerBuilder delegateBuilder : this.delegateBuilders) {
delegate = delegateBuilder.getDefaultUserDetailsService(); this.delegate = delegateBuilder.getDefaultUserDetailsService();
if (delegate != null) { if (this.delegate != null) {
break; break;
} }
} }
if (delegate == null) { if (this.delegate == null) {
throw new IllegalStateException("UserDetailsService is required."); throw new IllegalStateException("UserDetailsService is required.");
} }
this.delegateBuilders = null; this.delegateBuilders = null;
} }
} }
return delegate.loadUserByUsername(username); return this.delegate.loadUserByUsername(username);
} }
} }
@ -509,24 +509,24 @@ public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigu
Field parentAuthMgrField = ReflectionUtils.findField(AuthenticationManagerBuilder.class, Field parentAuthMgrField = ReflectionUtils.findField(AuthenticationManagerBuilder.class,
"parentAuthenticationManager"); "parentAuthenticationManager");
ReflectionUtils.makeAccessible(parentAuthMgrField); ReflectionUtils.makeAccessible(parentAuthMgrField);
beanNames = getAuthenticationManagerBeanNames(context); this.beanNames = getAuthenticationManagerBeanNames(context);
validateBeanCycle(ReflectionUtils.getField(parentAuthMgrField, delegateBuilder), beanNames); validateBeanCycle(ReflectionUtils.getField(parentAuthMgrField, delegateBuilder), this.beanNames);
this.delegateBuilder = delegateBuilder; this.delegateBuilder = delegateBuilder;
} }
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (delegate != null) { if (this.delegate != null) {
return delegate.authenticate(authentication); return this.delegate.authenticate(authentication);
} }
synchronized (delegateMonitor) { synchronized (this.delegateMonitor) {
if (delegate == null) { if (this.delegate == null) {
delegate = this.delegateBuilder.getObject(); this.delegate = this.delegateBuilder.getObject();
this.delegateBuilder = null; this.delegateBuilder = null;
} }
} }
return delegate.authenticate(authentication); return this.delegate.authenticate(authentication);
} }
private static Set<String> getAuthenticationManagerBeanNames(ApplicationContext applicationContext) { private static Set<String> getAuthenticationManagerBeanNames(ApplicationContext applicationContext) {

View File

@ -141,7 +141,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
*/ */
public T loginProcessingUrl(String loginProcessingUrl) { public T loginProcessingUrl(String loginProcessingUrl) {
this.loginProcessingUrl = loginProcessingUrl; this.loginProcessingUrl = loginProcessingUrl;
authFilter.setRequiresAuthenticationRequestMatcher(createLoginProcessingUrlMatcher(loginProcessingUrl)); this.authFilter.setRequiresAuthenticationRequestMatcher(createLoginProcessingUrlMatcher(loginProcessingUrl));
return getSelf(); return getSelf();
} }
@ -268,7 +268,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
public void configure(B http) throws Exception { public void configure(B http) throws Exception {
PortMapper portMapper = http.getSharedObject(PortMapper.class); PortMapper portMapper = http.getSharedObject(PortMapper.class);
if (portMapper != null) { if (portMapper != null) {
authenticationEntryPoint.setPortMapper(portMapper); this.authenticationEntryPoint.setPortMapper(portMapper);
} }
RequestCache requestCache = http.getSharedObject(RequestCache.class); RequestCache requestCache = http.getSharedObject(RequestCache.class);
@ -276,22 +276,22 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
this.defaultSuccessHandler.setRequestCache(requestCache); this.defaultSuccessHandler.setRequestCache(requestCache);
} }
authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); this.authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
authFilter.setAuthenticationSuccessHandler(successHandler); this.authFilter.setAuthenticationSuccessHandler(this.successHandler);
authFilter.setAuthenticationFailureHandler(failureHandler); this.authFilter.setAuthenticationFailureHandler(this.failureHandler);
if (authenticationDetailsSource != null) { if (this.authenticationDetailsSource != null) {
authFilter.setAuthenticationDetailsSource(authenticationDetailsSource); this.authFilter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
} }
SessionAuthenticationStrategy sessionAuthenticationStrategy = http SessionAuthenticationStrategy sessionAuthenticationStrategy = http
.getSharedObject(SessionAuthenticationStrategy.class); .getSharedObject(SessionAuthenticationStrategy.class);
if (sessionAuthenticationStrategy != null) { if (sessionAuthenticationStrategy != null) {
authFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); this.authFilter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
} }
RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class); RememberMeServices rememberMeServices = http.getSharedObject(RememberMeServices.class);
if (rememberMeServices != null) { if (rememberMeServices != null) {
authFilter.setRememberMeServices(rememberMeServices); this.authFilter.setRememberMeServices(rememberMeServices);
} }
F filter = postProcess(authFilter); F filter = postProcess(this.authFilter);
http.addFilter(filter); http.addFilter(filter);
} }
@ -319,7 +319,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return true if a custom login page has been specified, else false * @return true if a custom login page has been specified, else false
*/ */
public final boolean isCustomLoginPage() { public final boolean isCustomLoginPage() {
return customLoginPage; return this.customLoginPage;
} }
/** /**
@ -327,7 +327,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return the Authentication Filter * @return the Authentication Filter
*/ */
protected final F getAuthenticationFilter() { protected final F getAuthenticationFilter() {
return authFilter; return this.authFilter;
} }
/** /**
@ -343,7 +343,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return the login page * @return the login page
*/ */
protected final String getLoginPage() { protected final String getLoginPage() {
return loginPage; return this.loginPage;
} }
/** /**
@ -351,7 +351,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return the Authentication Entry Point * @return the Authentication Entry Point
*/ */
protected final AuthenticationEntryPoint getAuthenticationEntryPoint() { protected final AuthenticationEntryPoint getAuthenticationEntryPoint() {
return authenticationEntryPoint; return this.authenticationEntryPoint;
} }
/** /**
@ -360,7 +360,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return the URL to submit an authentication request to * @return the URL to submit an authentication request to
*/ */
protected final String getLoginProcessingUrl() { protected final String getLoginProcessingUrl() {
return loginProcessingUrl; return this.loginProcessingUrl;
} }
/** /**
@ -368,7 +368,7 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @return the URL to send users if authentication fails (e.g. "/login?error"). * @return the URL to send users if authentication fails (e.g. "/login?error").
*/ */
protected final String getFailureUrl() { protected final String getFailureUrl() {
return failureUrl; return this.failureUrl;
} }
/** /**
@ -376,16 +376,16 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* @throws Exception * @throws Exception
*/ */
protected final void updateAuthenticationDefaults() { protected final void updateAuthenticationDefaults() {
if (loginProcessingUrl == null) { if (this.loginProcessingUrl == null) {
loginProcessingUrl(loginPage); loginProcessingUrl(this.loginPage);
} }
if (failureHandler == null) { if (this.failureHandler == null) {
failureUrl(loginPage + "?error"); failureUrl(this.loginPage + "?error");
} }
final LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class); final LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) { if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) {
logoutConfigurer.logoutSuccessUrl(loginPage + "?logout"); logoutConfigurer.logoutSuccessUrl(this.loginPage + "?logout");
} }
} }
@ -393,8 +393,8 @@ public abstract class AbstractAuthenticationFilterConfigurer<B extends HttpSecur
* Updates the default values for access. * Updates the default values for access.
*/ */
protected final void updateAccessDefaults(B http) { protected final void updateAccessDefaults(B http) {
if (permitAll) { if (this.permitAll) {
PermitAllSupport.permitAll(http, loginPage, loginProcessingUrl, failureUrl); PermitAllSupport.permitAll(http, this.loginPage, this.loginProcessingUrl, this.failureUrl);
} }
} }

View File

@ -48,7 +48,7 @@ public abstract class AbstractConfigAttributeRequestMatcherRegistry<C> extends A
* {@link #chainRequestMatchers(java.util.List)} * {@link #chainRequestMatchers(java.util.List)}
*/ */
final List<UrlMapping> getUrlMappings() { final List<UrlMapping> getUrlMappings() {
return urlMappings; return this.urlMappings;
} }
/** /**
@ -100,8 +100,8 @@ public abstract class AbstractConfigAttributeRequestMatcherRegistry<C> extends A
* {@link ConfigAttribute} instances. Cannot be null. * {@link ConfigAttribute} instances. Cannot be null.
*/ */
final LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> createRequestMap() { final LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> createRequestMap() {
if (unmappedMatchers != null) { if (this.unmappedMatchers != null) {
throw new IllegalStateException("An incomplete mapping was found for " + unmappedMatchers throw new IllegalStateException("An incomplete mapping was found for " + this.unmappedMatchers
+ ". Try completing it with something like requestUrls().<something>.hasRole('USER')"); + ". Try completing it with something like requestUrls().<something>.hasRole('USER')");
} }
@ -130,11 +130,11 @@ public abstract class AbstractConfigAttributeRequestMatcherRegistry<C> extends A
} }
public RequestMatcher getRequestMatcher() { public RequestMatcher getRequestMatcher() {
return requestMatcher; return this.requestMatcher;
} }
public Collection<ConfigAttribute> getConfigAttrs() { public Collection<ConfigAttribute> getConfigAttrs() {
return configAttrs; return this.configAttrs;
} }
} }

View File

@ -75,8 +75,8 @@ abstract class AbstractInterceptUrlConfigurer<C extends AbstractInterceptUrlConf
} }
FilterSecurityInterceptor securityInterceptor = createFilterSecurityInterceptor(http, metadataSource, FilterSecurityInterceptor securityInterceptor = createFilterSecurityInterceptor(http, metadataSource,
http.getSharedObject(AuthenticationManager.class)); http.getSharedObject(AuthenticationManager.class));
if (filterSecurityInterceptorOncePerRequest != null) { if (this.filterSecurityInterceptorOncePerRequest != null) {
securityInterceptor.setObserveOncePerRequest(filterSecurityInterceptorOncePerRequest); securityInterceptor.setObserveOncePerRequest(this.filterSecurityInterceptorOncePerRequest);
} }
securityInterceptor = postProcess(securityInterceptor); securityInterceptor = postProcess(securityInterceptor);
http.addFilter(securityInterceptor); http.addFilter(securityInterceptor);
@ -157,10 +157,10 @@ abstract class AbstractInterceptUrlConfigurer<C extends AbstractInterceptUrlConf
* @return the {@link AccessDecisionManager} to use * @return the {@link AccessDecisionManager} to use
*/ */
private AccessDecisionManager getAccessDecisionManager(H http) { private AccessDecisionManager getAccessDecisionManager(H http) {
if (accessDecisionManager == null) { if (this.accessDecisionManager == null) {
accessDecisionManager = createDefaultAccessDecisionManager(http); this.accessDecisionManager = createDefaultAccessDecisionManager(http);
} }
return accessDecisionManager; return this.accessDecisionManager;
} }
/** /**

View File

@ -140,27 +140,27 @@ public final class AnonymousConfigurer<H extends HttpSecurityBuilder<H>>
@Override @Override
public void init(H http) { public void init(H http) {
if (authenticationProvider == null) { if (this.authenticationProvider == null) {
authenticationProvider = new AnonymousAuthenticationProvider(getKey()); this.authenticationProvider = new AnonymousAuthenticationProvider(getKey());
} }
if (authenticationFilter == null) { if (this.authenticationFilter == null) {
authenticationFilter = new AnonymousAuthenticationFilter(getKey(), principal, authorities); this.authenticationFilter = new AnonymousAuthenticationFilter(getKey(), this.principal, this.authorities);
} }
authenticationProvider = postProcess(authenticationProvider); this.authenticationProvider = postProcess(this.authenticationProvider);
http.authenticationProvider(authenticationProvider); http.authenticationProvider(this.authenticationProvider);
} }
@Override @Override
public void configure(H http) { public void configure(H http) {
authenticationFilter.afterPropertiesSet(); this.authenticationFilter.afterPropertiesSet();
http.addFilter(authenticationFilter); http.addFilter(this.authenticationFilter);
} }
private String getKey() { private String getKey() {
if (key == null) { if (this.key == null) {
key = UUID.randomUUID().toString(); this.key = UUID.randomUUID().toString();
} }
return key; return this.key;
} }
} }

View File

@ -96,7 +96,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>>
} }
public ChannelRequestMatcherRegistry getRegistry() { public ChannelRequestMatcherRegistry getRegistry() {
return REGISTRY; return this.REGISTRY;
} }
@Override @Override
@ -105,19 +105,19 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>>
channelDecisionManager.setChannelProcessors(getChannelProcessors(http)); channelDecisionManager.setChannelProcessors(getChannelProcessors(http));
channelDecisionManager = postProcess(channelDecisionManager); channelDecisionManager = postProcess(channelDecisionManager);
channelFilter.setChannelDecisionManager(channelDecisionManager); this.channelFilter.setChannelDecisionManager(channelDecisionManager);
DefaultFilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new DefaultFilterInvocationSecurityMetadataSource( DefaultFilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new DefaultFilterInvocationSecurityMetadataSource(
requestMap); this.requestMap);
channelFilter.setSecurityMetadataSource(filterInvocationSecurityMetadataSource); this.channelFilter.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
channelFilter = postProcess(channelFilter); this.channelFilter = postProcess(this.channelFilter);
http.addFilter(channelFilter); http.addFilter(this.channelFilter);
} }
private List<ChannelProcessor> getChannelProcessors(H http) { private List<ChannelProcessor> getChannelProcessors(H http) {
if (channelProcessors != null) { if (this.channelProcessors != null) {
return channelProcessors; return this.channelProcessors;
} }
InsecureChannelProcessor insecureChannelProcessor = new InsecureChannelProcessor(); InsecureChannelProcessor insecureChannelProcessor = new InsecureChannelProcessor();
@ -141,9 +141,9 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>>
private ChannelRequestMatcherRegistry addAttribute(String attribute, List<? extends RequestMatcher> matchers) { private ChannelRequestMatcherRegistry addAttribute(String attribute, List<? extends RequestMatcher> matchers) {
for (RequestMatcher matcher : matchers) { for (RequestMatcher matcher : matchers) {
Collection<ConfigAttribute> attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig(attribute)); Collection<ConfigAttribute> attrs = Arrays.<ConfigAttribute>asList(new SecurityConfig(attribute));
requestMap.put(matcher, attrs); this.requestMap.put(matcher, attrs);
} }
return REGISTRY; return this.REGISTRY;
} }
public final class ChannelRequestMatcherRegistry public final class ChannelRequestMatcherRegistry
@ -233,7 +233,7 @@ public final class ChannelSecurityConfigurer<H extends HttpSecurityBuilder<H>>
} }
public ChannelRequestMatcherRegistry requires(String attribute) { public ChannelRequestMatcherRegistry requires(String attribute) {
return addAttribute(attribute, requestMatchers); return addAttribute(attribute, this.requestMatchers);
} }
} }

View File

@ -84,7 +84,7 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
}; };
this.loginPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs); this.loginPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
this.logoutPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs); this.logoutPageGeneratingFilter.setResolveHiddenInputs(hiddenInputs);
http.setSharedObject(DefaultLoginPageGeneratingFilter.class, loginPageGeneratingFilter); http.setSharedObject(DefaultLoginPageGeneratingFilter.class, this.loginPageGeneratingFilter);
} }
@Override @Override
@ -96,9 +96,9 @@ public final class DefaultLoginPageConfigurer<H extends HttpSecurityBuilder<H>>
authenticationEntryPoint = exceptionConf.getAuthenticationEntryPoint(); authenticationEntryPoint = exceptionConf.getAuthenticationEntryPoint();
} }
if (loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) { if (this.loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
loginPageGeneratingFilter = postProcess(loginPageGeneratingFilter); this.loginPageGeneratingFilter = postProcess(this.loginPageGeneratingFilter);
http.addFilter(loginPageGeneratingFilter); http.addFilter(this.loginPageGeneratingFilter);
http.addFilter(this.logoutPageGeneratingFilter); http.addFilter(this.logoutPageGeneratingFilter);
} }
} }

View File

@ -106,7 +106,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
} }
public ExpressionInterceptUrlRegistry getRegistry() { public ExpressionInterceptUrlRegistry getRegistry() {
return REGISTRY; return this.REGISTRY;
} }
public final class ExpressionInterceptUrlRegistry extends public final class ExpressionInterceptUrlRegistry extends
@ -175,7 +175,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
private void interceptUrl(Iterable<? extends RequestMatcher> requestMatchers, private void interceptUrl(Iterable<? extends RequestMatcher> requestMatchers,
Collection<ConfigAttribute> configAttributes) { Collection<ConfigAttribute> configAttributes) {
for (RequestMatcher requestMatcher : requestMatchers) { for (RequestMatcher requestMatcher : requestMatchers) {
REGISTRY.addMapping( this.REGISTRY.addMapping(
new AbstractConfigAttributeRequestMatcherRegistry.UrlMapping(requestMatcher, configAttributes)); new AbstractConfigAttributeRequestMatcherRegistry.UrlMapping(requestMatcher, configAttributes));
} }
} }
@ -192,7 +192,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
@Override @Override
ExpressionBasedFilterInvocationSecurityMetadataSource createMetadataSource(H http) { ExpressionBasedFilterInvocationSecurityMetadataSource createMetadataSource(H http) {
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = REGISTRY.createRequestMap(); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = this.REGISTRY.createRequestMap();
if (requestMap.isEmpty()) { if (requestMap.isEmpty()) {
throw new IllegalStateException( throw new IllegalStateException(
"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())"); "At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
@ -201,7 +201,7 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
} }
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler(H http) { private SecurityExpressionHandler<FilterInvocation> getExpressionHandler(H http) {
if (expressionHandler == null) { if (this.expressionHandler == null) {
DefaultWebSecurityExpressionHandler defaultHandler = new DefaultWebSecurityExpressionHandler(); DefaultWebSecurityExpressionHandler defaultHandler = new DefaultWebSecurityExpressionHandler();
AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class); AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class);
if (trustResolver != null) { if (trustResolver != null) {
@ -228,10 +228,10 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
} }
} }
expressionHandler = postProcess(defaultHandler); this.expressionHandler = postProcess(defaultHandler);
} }
return expressionHandler; return this.expressionHandler;
} }
private static String hasAnyRole(String... authorities) { private static String hasAnyRole(String... authorities) {
@ -439,10 +439,10 @@ public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBu
* customization * customization
*/ */
public ExpressionInterceptUrlRegistry access(String attribute) { public ExpressionInterceptUrlRegistry access(String attribute) {
if (not) { if (this.not) {
attribute = "!" + attribute; attribute = "!" + attribute;
} }
interceptUrl(requestMatchers, SecurityConfig.createList(attribute)); interceptUrl(this.requestMatchers, SecurityConfig.createList(attribute));
return ExpressionUrlAuthorizationConfigurer.this.REGISTRY; return ExpressionUrlAuthorizationConfigurer.this.REGISTRY;
} }

View File

@ -125,7 +125,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link ContentTypeOptionsConfig} for additional customizations * @return the {@link ContentTypeOptionsConfig} for additional customizations
*/ */
public ContentTypeOptionsConfig contentTypeOptions() { public ContentTypeOptionsConfig contentTypeOptions() {
return contentTypeOptions.enable(); return this.contentTypeOptions.enable();
} }
/** /**
@ -141,7 +141,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> contentTypeOptions(Customizer<ContentTypeOptionsConfig> contentTypeOptionsCustomizer) { public HeadersConfigurer<H> contentTypeOptions(Customizer<ContentTypeOptionsConfig> contentTypeOptionsCustomizer) {
contentTypeOptionsCustomizer.customize(contentTypeOptions.enable()); contentTypeOptionsCustomizer.customize(this.contentTypeOptions.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -158,7 +158,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return {@link HeadersConfigurer} for additional customization. * @return {@link HeadersConfigurer} for additional customization.
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return and(); return and();
} }
@ -175,8 +175,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link ContentTypeOptionsConfig} for additional customization * @return the {@link ContentTypeOptionsConfig} for additional customization
*/ */
private ContentTypeOptionsConfig enable() { private ContentTypeOptionsConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new XContentTypeOptionsHeaderWriter(); this.writer = new XContentTypeOptionsHeaderWriter();
} }
return this; return this;
} }
@ -194,7 +194,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link XXssConfig} for additional customizations * @return the {@link XXssConfig} for additional customizations
*/ */
public XXssConfig xssProtection() { public XXssConfig xssProtection() {
return xssProtection.enable(); return this.xssProtection.enable();
} }
/** /**
@ -210,7 +210,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> xssProtection(Customizer<XXssConfig> xssCustomizer) { public HeadersConfigurer<H> xssProtection(Customizer<XXssConfig> xssCustomizer) {
xssCustomizer.customize(xssProtection.enable()); xssCustomizer.customize(this.xssProtection.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -228,7 +228,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param enabled the new value * @param enabled the new value
*/ */
public XXssConfig block(boolean enabled) { public XXssConfig block(boolean enabled) {
writer.setBlock(enabled); this.writer.setBlock(enabled);
return this; return this;
} }
@ -256,7 +256,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param enabled the new value * @param enabled the new value
*/ */
public XXssConfig xssProtectionEnabled(boolean enabled) { public XXssConfig xssProtectionEnabled(boolean enabled) {
writer.setEnabled(enabled); this.writer.setEnabled(enabled);
return this; return this;
} }
@ -265,7 +265,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional configuration * @return the {@link HeadersConfigurer} for additional configuration
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return and(); return and();
} }
@ -283,8 +283,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link XXssConfig} for additional customization * @return the {@link XXssConfig} for additional customization
*/ */
private XXssConfig enable() { private XXssConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new XXssProtectionHeaderWriter(); this.writer = new XXssProtectionHeaderWriter();
} }
return this; return this;
} }
@ -302,7 +302,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link CacheControlConfig} for additional customizations * @return the {@link CacheControlConfig} for additional customizations
*/ */
public CacheControlConfig cacheControl() { public CacheControlConfig cacheControl() {
return cacheControl.enable(); return this.cacheControl.enable();
} }
/** /**
@ -318,7 +318,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> cacheControl(Customizer<CacheControlConfig> cacheControlCustomizer) { public HeadersConfigurer<H> cacheControl(Customizer<CacheControlConfig> cacheControlCustomizer) {
cacheControlCustomizer.customize(cacheControl.enable()); cacheControlCustomizer.customize(this.cacheControl.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -335,7 +335,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional configuration * @return the {@link HeadersConfigurer} for additional configuration
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -353,8 +353,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link CacheControlConfig} for additional customization * @return the {@link CacheControlConfig} for additional customization
*/ */
private CacheControlConfig enable() { private CacheControlConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new CacheControlHeadersWriter(); this.writer = new CacheControlHeadersWriter();
} }
return this; return this;
} }
@ -368,7 +368,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HstsConfig} for additional customizations * @return the {@link HstsConfig} for additional customizations
*/ */
public HstsConfig httpStrictTransportSecurity() { public HstsConfig httpStrictTransportSecurity() {
return hsts.enable(); return this.hsts.enable();
} }
/** /**
@ -380,7 +380,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> httpStrictTransportSecurity(Customizer<HstsConfig> hstsCustomizer) { public HeadersConfigurer<H> httpStrictTransportSecurity(Customizer<HstsConfig> hstsCustomizer) {
hstsCustomizer.customize(hsts.enable()); hstsCustomizer.customize(this.hsts.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -409,7 +409,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if maxAgeInSeconds is negative * @throws IllegalArgumentException if maxAgeInSeconds is negative
*/ */
public HstsConfig maxAgeInSeconds(long maxAgeInSeconds) { public HstsConfig maxAgeInSeconds(long maxAgeInSeconds) {
writer.setMaxAgeInSeconds(maxAgeInSeconds); this.writer.setMaxAgeInSeconds(maxAgeInSeconds);
return this; return this;
} }
@ -422,7 +422,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if {@link RequestMatcher} is null * @throws IllegalArgumentException if {@link RequestMatcher} is null
*/ */
public HstsConfig requestMatcher(RequestMatcher requestMatcher) { public HstsConfig requestMatcher(RequestMatcher requestMatcher) {
writer.setRequestMatcher(requestMatcher); this.writer.setRequestMatcher(requestMatcher);
return this; return this;
} }
@ -438,7 +438,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param includeSubDomains true to include subdomains, else false * @param includeSubDomains true to include subdomains, else false
*/ */
public HstsConfig includeSubDomains(boolean includeSubDomains) { public HstsConfig includeSubDomains(boolean includeSubDomains) {
writer.setIncludeSubDomains(includeSubDomains); this.writer.setIncludeSubDomains(includeSubDomains);
return this; return this;
} }
@ -456,7 +456,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @author Ankur Pathak * @author Ankur Pathak
*/ */
public HstsConfig preload(boolean preload) { public HstsConfig preload(boolean preload) {
writer.setPreload(preload); this.writer.setPreload(preload);
return this; return this;
} }
@ -465,7 +465,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional configuration * @return the {@link HeadersConfigurer} for additional configuration
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -483,8 +483,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HstsConfig} for additional customization * @return the {@link HstsConfig} for additional customization
*/ */
private HstsConfig enable() { private HstsConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new HstsHeaderWriter(); this.writer = new HstsHeaderWriter();
} }
return this; return this;
} }
@ -496,7 +496,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link FrameOptionsConfig} for additional customizations * @return the {@link FrameOptionsConfig} for additional customizations
*/ */
public FrameOptionsConfig frameOptions() { public FrameOptionsConfig frameOptions() {
return frameOptions.enable(); return this.frameOptions.enable();
} }
/** /**
@ -506,7 +506,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> frameOptions(Customizer<FrameOptionsConfig> frameOptionsCustomizer) { public HeadersConfigurer<H> frameOptions(Customizer<FrameOptionsConfig> frameOptionsCustomizer) {
frameOptionsCustomizer.customize(frameOptions.enable()); frameOptionsCustomizer.customize(this.frameOptions.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -523,7 +523,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customization. * @return the {@link HeadersConfigurer} for additional customization.
*/ */
public HeadersConfigurer<H> deny() { public HeadersConfigurer<H> deny() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY); this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
return and(); return and();
} }
@ -537,7 +537,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customization. * @return the {@link HeadersConfigurer} for additional customization.
*/ */
public HeadersConfigurer<H> sameOrigin() { public HeadersConfigurer<H> sameOrigin() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN); this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
return and(); return and();
} }
@ -546,7 +546,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional configuration. * @return the {@link HeadersConfigurer} for additional configuration.
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return and(); return and();
} }
@ -563,8 +563,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the FrameOptionsConfig for additional customization. * @return the FrameOptionsConfig for additional customization.
*/ */
private FrameOptionsConfig enable() { private FrameOptionsConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY); this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
} }
return this; return this;
} }
@ -579,7 +579,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @since 4.1 * @since 4.1
*/ */
public HpkpConfig httpPublicKeyPinning() { public HpkpConfig httpPublicKeyPinning() {
return hpkp.enable(); return this.hpkp.enable();
} }
/** /**
@ -590,7 +590,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customizations * @return the {@link HeadersConfigurer} for additional customizations
*/ */
public HeadersConfigurer<H> httpPublicKeyPinning(Customizer<HpkpConfig> hpkpCustomizer) { public HeadersConfigurer<H> httpPublicKeyPinning(Customizer<HpkpConfig> hpkpCustomizer) {
hpkpCustomizer.customize(hpkp.enable()); hpkpCustomizer.customize(this.hpkp.enable());
return HeadersConfigurer.this; return HeadersConfigurer.this;
} }
@ -617,7 +617,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if pins is null * @throws IllegalArgumentException if pins is null
*/ */
public HpkpConfig withPins(Map<String, String> pins) { public HpkpConfig withPins(Map<String, String> pins) {
writer.setPins(pins); this.writer.setPins(pins);
return this; return this;
} }
@ -637,7 +637,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if a pin is null * @throws IllegalArgumentException if a pin is null
*/ */
public HpkpConfig addSha256Pins(String... pins) { public HpkpConfig addSha256Pins(String... pins) {
writer.addSha256Pins(pins); this.writer.addSha256Pins(pins);
return this; return this;
} }
@ -658,7 +658,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if maxAgeInSeconds is negative * @throws IllegalArgumentException if maxAgeInSeconds is negative
*/ */
public HpkpConfig maxAgeInSeconds(long maxAgeInSeconds) { public HpkpConfig maxAgeInSeconds(long maxAgeInSeconds) {
writer.setMaxAgeInSeconds(maxAgeInSeconds); this.writer.setMaxAgeInSeconds(maxAgeInSeconds);
return this; return this;
} }
@ -675,7 +675,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param includeSubDomains true to include subdomains, else false * @param includeSubDomains true to include subdomains, else false
*/ */
public HpkpConfig includeSubDomains(boolean includeSubDomains) { public HpkpConfig includeSubDomains(boolean includeSubDomains) {
writer.setIncludeSubDomains(includeSubDomains); this.writer.setIncludeSubDomains(includeSubDomains);
return this; return this;
} }
@ -692,7 +692,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param reportOnly true to report only, else false * @param reportOnly true to report only, else false
*/ */
public HpkpConfig reportOnly(boolean reportOnly) { public HpkpConfig reportOnly(boolean reportOnly) {
writer.setReportOnly(reportOnly); this.writer.setReportOnly(reportOnly);
return this; return this;
} }
@ -708,7 +708,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @param reportUri the URI where the browser should send the report to. * @param reportUri the URI where the browser should send the report to.
*/ */
public HpkpConfig reportUri(URI reportUri) { public HpkpConfig reportUri(URI reportUri) {
writer.setReportUri(reportUri); this.writer.setReportUri(reportUri);
return this; return this;
} }
@ -725,7 +725,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @throws IllegalArgumentException if the reportUri is not a valid URI * @throws IllegalArgumentException if the reportUri is not a valid URI
*/ */
public HpkpConfig reportUri(String reportUri) { public HpkpConfig reportUri(String reportUri) {
writer.setReportUri(reportUri); this.writer.setReportUri(reportUri);
return this; return this;
} }
@ -734,7 +734,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional configuration. * @return the {@link HeadersConfigurer} for additional configuration.
*/ */
public HeadersConfigurer<H> disable() { public HeadersConfigurer<H> disable() {
writer = null; this.writer = null;
return and(); return and();
} }
@ -753,8 +753,8 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HstsConfig} for additional customization * @return the {@link HstsConfig} for additional customization
*/ */
private HpkpConfig enable() { private HpkpConfig enable() {
if (writer == null) { if (this.writer == null) {
writer = new HpkpHeaderWriter(); this.writer = new HpkpHeaderWriter();
} }
return this; return this;
} }
@ -788,7 +788,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
public ContentSecurityPolicyConfig contentSecurityPolicy(String policyDirectives) { public ContentSecurityPolicyConfig contentSecurityPolicy(String policyDirectives) {
this.contentSecurityPolicy.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives); this.contentSecurityPolicy.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
return contentSecurityPolicy; return this.contentSecurityPolicy;
} }
/** /**
@ -874,11 +874,11 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link HeadersConfigurer} for additional customization * @return the {@link HeadersConfigurer} for additional customization
*/ */
public HeadersConfigurer<H> defaultsDisabled() { public HeadersConfigurer<H> defaultsDisabled() {
contentTypeOptions.disable(); this.contentTypeOptions.disable();
xssProtection.disable(); this.xssProtection.disable();
cacheControl.disable(); this.cacheControl.disable();
hsts.disable(); this.hsts.disable();
frameOptions.disable(); this.frameOptions.disable();
return this; return this;
} }
@ -909,16 +909,16 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
private List<HeaderWriter> getHeaderWriters() { private List<HeaderWriter> getHeaderWriters() {
List<HeaderWriter> writers = new ArrayList<>(); List<HeaderWriter> writers = new ArrayList<>();
addIfNotNull(writers, contentTypeOptions.writer); addIfNotNull(writers, this.contentTypeOptions.writer);
addIfNotNull(writers, xssProtection.writer); addIfNotNull(writers, this.xssProtection.writer);
addIfNotNull(writers, cacheControl.writer); addIfNotNull(writers, this.cacheControl.writer);
addIfNotNull(writers, hsts.writer); addIfNotNull(writers, this.hsts.writer);
addIfNotNull(writers, frameOptions.writer); addIfNotNull(writers, this.frameOptions.writer);
addIfNotNull(writers, hpkp.writer); addIfNotNull(writers, this.hpkp.writer);
addIfNotNull(writers, contentSecurityPolicy.writer); addIfNotNull(writers, this.contentSecurityPolicy.writer);
addIfNotNull(writers, referrerPolicy.writer); addIfNotNull(writers, this.referrerPolicy.writer);
addIfNotNull(writers, featurePolicy.writer); addIfNotNull(writers, this.featurePolicy.writer);
writers.addAll(headerWriters); writers.addAll(this.headerWriters);
return writers; return writers;
} }
@ -1045,7 +1045,7 @@ public class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
public FeaturePolicyConfig featurePolicy(String policyDirectives) { public FeaturePolicyConfig featurePolicy(String policyDirectives) {
this.featurePolicy.writer = new FeaturePolicyHeaderWriter(policyDirectives); this.featurePolicy.writer = new FeaturePolicyHeaderWriter(policyDirectives);
return featurePolicy; return this.featurePolicy;
} }
public final class FeaturePolicyConfig { public final class FeaturePolicyConfig {

View File

@ -212,14 +212,15 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
* @return the {@link J2eePreAuthenticatedProcessingFilter} to use. * @return the {@link J2eePreAuthenticatedProcessingFilter} to use.
*/ */
private J2eePreAuthenticatedProcessingFilter getFilter(AuthenticationManager authenticationManager) { private J2eePreAuthenticatedProcessingFilter getFilter(AuthenticationManager authenticationManager) {
if (j2eePreAuthenticatedProcessingFilter == null) { if (this.j2eePreAuthenticatedProcessingFilter == null) {
j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter(); this.j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(authenticationManager); this.j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(authenticationManager);
j2eePreAuthenticatedProcessingFilter.setAuthenticationDetailsSource(createWebAuthenticationDetailsSource()); this.j2eePreAuthenticatedProcessingFilter
j2eePreAuthenticatedProcessingFilter = postProcess(j2eePreAuthenticatedProcessingFilter); .setAuthenticationDetailsSource(createWebAuthenticationDetailsSource());
this.j2eePreAuthenticatedProcessingFilter = postProcess(this.j2eePreAuthenticatedProcessingFilter);
} }
return j2eePreAuthenticatedProcessingFilter; return this.j2eePreAuthenticatedProcessingFilter;
} }
/** /**
@ -228,8 +229,8 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
* @return the {@link AuthenticationUserDetailsService} to use * @return the {@link AuthenticationUserDetailsService} to use
*/ */
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getUserDetailsService() { private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getUserDetailsService() {
return authenticationUserDetailsService == null ? new PreAuthenticatedGrantedAuthoritiesUserDetailsService() return this.authenticationUserDetailsService == null
: authenticationUserDetailsService; ? new PreAuthenticatedGrantedAuthoritiesUserDetailsService() : this.authenticationUserDetailsService;
} }
/** /**
@ -241,7 +242,7 @@ public final class JeeConfigurer<H extends HttpSecurityBuilder<H>> extends Abstr
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource createWebAuthenticationDetailsSource() { private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource createWebAuthenticationDetailsSource() {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource detailsSource = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource detailsSource = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
SimpleMappableAttributesRetriever rolesRetriever = new SimpleMappableAttributesRetriever(); SimpleMappableAttributesRetriever rolesRetriever = new SimpleMappableAttributesRetriever();
rolesRetriever.setMappableAttributes(mappableRoles); rolesRetriever.setMappableAttributes(this.mappableRoles);
detailsSource.setMappableRolesRetriever(rolesRetriever); detailsSource.setMappableRolesRetriever(rolesRetriever);
detailsSource = postProcess(detailsSource); detailsSource = postProcess(detailsSource);

View File

@ -114,7 +114,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link LogoutConfigurer} for further customization * @return the {@link LogoutConfigurer} for further customization
*/ */
public LogoutConfigurer<H> clearAuthentication(boolean clearAuthentication) { public LogoutConfigurer<H> clearAuthentication(boolean clearAuthentication) {
contextLogoutHandler.setClearAuthentication(clearAuthentication); this.contextLogoutHandler.setClearAuthentication(clearAuthentication);
return this; return this;
} }
@ -126,7 +126,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link LogoutConfigurer} for further customization * @return the {@link LogoutConfigurer} for further customization
*/ */
public LogoutConfigurer<H> invalidateHttpSession(boolean invalidateHttpSession) { public LogoutConfigurer<H> invalidateHttpSession(boolean invalidateHttpSession) {
contextLogoutHandler.setInvalidateHttpSession(invalidateHttpSession); this.contextLogoutHandler.setInvalidateHttpSession(invalidateHttpSession);
return this; return this;
} }
@ -259,19 +259,19 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
private LogoutSuccessHandler createDefaultSuccessHandler() { private LogoutSuccessHandler createDefaultSuccessHandler() {
SimpleUrlLogoutSuccessHandler urlLogoutHandler = new SimpleUrlLogoutSuccessHandler(); SimpleUrlLogoutSuccessHandler urlLogoutHandler = new SimpleUrlLogoutSuccessHandler();
urlLogoutHandler.setDefaultTargetUrl(logoutSuccessUrl); urlLogoutHandler.setDefaultTargetUrl(this.logoutSuccessUrl);
if (defaultLogoutSuccessHandlerMappings.isEmpty()) { if (this.defaultLogoutSuccessHandlerMappings.isEmpty()) {
return urlLogoutHandler; return urlLogoutHandler;
} }
DelegatingLogoutSuccessHandler successHandler = new DelegatingLogoutSuccessHandler( DelegatingLogoutSuccessHandler successHandler = new DelegatingLogoutSuccessHandler(
defaultLogoutSuccessHandlerMappings); this.defaultLogoutSuccessHandlerMappings);
successHandler.setDefaultLogoutSuccessHandler(urlLogoutHandler); successHandler.setDefaultLogoutSuccessHandler(urlLogoutHandler);
return successHandler; return successHandler;
} }
@Override @Override
public void init(H http) { public void init(H http) {
if (permitAll) { if (this.permitAll) {
PermitAllSupport.permitAll(http, this.logoutSuccessUrl); PermitAllSupport.permitAll(http, this.logoutSuccessUrl);
PermitAllSupport.permitAll(http, this.getLogoutRequestMatcher(http)); PermitAllSupport.permitAll(http, this.getLogoutRequestMatcher(http));
} }
@ -296,7 +296,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return true if logout success handling has been customized, else false * @return true if logout success handling has been customized, else false
*/ */
boolean isCustomLogoutSuccess() { boolean isCustomLogoutSuccess() {
return customLogoutSuccess; return this.customLogoutSuccess;
} }
/** /**
@ -305,7 +305,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return the logoutSuccessUrl * @return the logoutSuccessUrl
*/ */
private String getLogoutSuccessUrl() { private String getLogoutSuccessUrl() {
return logoutSuccessUrl; return this.logoutSuccessUrl;
} }
/** /**
@ -313,7 +313,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link LogoutHandler} instances. Cannot be null. * @return the {@link LogoutHandler} instances. Cannot be null.
*/ */
List<LogoutHandler> getLogoutHandlers() { List<LogoutHandler> getLogoutHandlers() {
return logoutHandlers; return this.logoutHandlers;
} }
/** /**
@ -324,9 +324,9 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link LogoutFilter} to use. * @return the {@link LogoutFilter} to use.
*/ */
private LogoutFilter createLogoutFilter(H http) { private LogoutFilter createLogoutFilter(H http) {
logoutHandlers.add(contextLogoutHandler); this.logoutHandlers.add(this.contextLogoutHandler);
logoutHandlers.add(postProcess(new LogoutSuccessEventPublishingLogoutHandler())); this.logoutHandlers.add(postProcess(new LogoutSuccessEventPublishingLogoutHandler()));
LogoutHandler[] handlers = logoutHandlers.toArray(new LogoutHandler[0]); LogoutHandler[] handlers = this.logoutHandlers.toArray(new LogoutHandler[0]);
LogoutFilter result = new LogoutFilter(getLogoutSuccessHandler(), handlers); LogoutFilter result = new LogoutFilter(getLogoutSuccessHandler(), handlers);
result.setLogoutRequestMatcher(getLogoutRequestMatcher(http)); result.setLogoutRequestMatcher(getLogoutRequestMatcher(http));
result = postProcess(result); result = postProcess(result);
@ -335,8 +335,8 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private RequestMatcher getLogoutRequestMatcher(H http) { private RequestMatcher getLogoutRequestMatcher(H http) {
if (logoutRequestMatcher != null) { if (this.logoutRequestMatcher != null) {
return logoutRequestMatcher; return this.logoutRequestMatcher;
} }
if (http.getConfigurer(CsrfConfigurer.class) != null) { if (http.getConfigurer(CsrfConfigurer.class) != null) {
this.logoutRequestMatcher = new AntPathRequestMatcher(this.logoutUrl, "POST"); this.logoutRequestMatcher = new AntPathRequestMatcher(this.logoutUrl, "POST");

View File

@ -73,16 +73,16 @@ final class PermitAllSupport {
} }
if ("".equals(request.getContextPath())) { if ("".equals(request.getContextPath())) {
return uri.equals(processUrl); return uri.equals(this.processUrl);
} }
return uri.equals(request.getContextPath() + processUrl); return uri.equals(request.getContextPath() + this.processUrl);
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("ExactUrl [processUrl='").append(processUrl).append("']"); sb.append("ExactUrl [processUrl='").append(this.processUrl).append("']");
return sb.toString(); return sb.toString();
} }

View File

@ -75,12 +75,12 @@ public final class PortMapperConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link PortMapper} to use * @return the {@link PortMapper} to use
*/ */
private PortMapper getPortMapper() { private PortMapper getPortMapper() {
if (portMapper == null) { if (this.portMapper == null) {
PortMapperImpl portMapper = new PortMapperImpl(); PortMapperImpl portMapper = new PortMapperImpl();
portMapper.setPortMappings(httpsPortMappings); portMapper.setPortMappings(this.httpsPortMappings);
this.portMapper = portMapper; this.portMapper = portMapper;
} }
return portMapper; return this.portMapper;
} }
/** /**
@ -109,7 +109,7 @@ public final class PortMapperConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link PortMapperConfigurer} for further customization * @return the {@link PortMapperConfigurer} for further customization
*/ */
public PortMapperConfigurer<H> mapsTo(int httpsPort) { public PortMapperConfigurer<H> mapsTo(int httpsPort) {
httpsPortMappings.put(String.valueOf(httpPort), String.valueOf(httpsPort)); PortMapperConfigurer.this.httpsPortMappings.put(String.valueOf(this.httpPort), String.valueOf(httpsPort));
return PortMapperConfigurer.this; return PortMapperConfigurer.this;
} }

View File

@ -424,7 +424,7 @@ public final class RememberMeConfigurer<H extends HttpSecurityBuilder<H>>
private String getKey() { private String getKey() {
if (this.key == null) { if (this.key == null) {
if (this.rememberMeServices instanceof AbstractRememberMeServices) { if (this.rememberMeServices instanceof AbstractRememberMeServices) {
this.key = ((AbstractRememberMeServices) rememberMeServices).getKey(); this.key = ((AbstractRememberMeServices) this.rememberMeServices).getKey();
} }
else { else {
this.key = UUID.randomUUID().toString(); this.key = UUID.randomUUID().toString();

View File

@ -70,24 +70,24 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>>
} }
public ServletApiConfigurer<H> rolePrefix(String rolePrefix) { public ServletApiConfigurer<H> rolePrefix(String rolePrefix) {
securityContextRequestFilter.setRolePrefix(rolePrefix); this.securityContextRequestFilter.setRolePrefix(rolePrefix);
return this; return this;
} }
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void configure(H http) { public void configure(H http) {
securityContextRequestFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); this.securityContextRequestFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
ExceptionHandlingConfigurer<H> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class); ExceptionHandlingConfigurer<H> exceptionConf = http.getConfigurer(ExceptionHandlingConfigurer.class);
AuthenticationEntryPoint authenticationEntryPoint = exceptionConf == null ? null AuthenticationEntryPoint authenticationEntryPoint = exceptionConf == null ? null
: exceptionConf.getAuthenticationEntryPoint(http); : exceptionConf.getAuthenticationEntryPoint(http);
securityContextRequestFilter.setAuthenticationEntryPoint(authenticationEntryPoint); this.securityContextRequestFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
LogoutConfigurer<H> logoutConf = http.getConfigurer(LogoutConfigurer.class); LogoutConfigurer<H> logoutConf = http.getConfigurer(LogoutConfigurer.class);
List<LogoutHandler> logoutHandlers = logoutConf == null ? null : logoutConf.getLogoutHandlers(); List<LogoutHandler> logoutHandlers = logoutConf == null ? null : logoutConf.getLogoutHandlers();
securityContextRequestFilter.setLogoutHandlers(logoutHandlers); this.securityContextRequestFilter.setLogoutHandlers(logoutHandlers);
AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class); AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class);
if (trustResolver != null) { if (trustResolver != null) {
securityContextRequestFilter.setTrustResolver(trustResolver); this.securityContextRequestFilter.setTrustResolver(trustResolver);
} }
ApplicationContext context = http.getSharedObject(ApplicationContext.class); ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if (context != null) { if (context != null) {
@ -95,11 +95,11 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>>
if (grantedAuthorityDefaultsBeanNames.length == 1) { if (grantedAuthorityDefaultsBeanNames.length == 1) {
GrantedAuthorityDefaults grantedAuthorityDefaults = context GrantedAuthorityDefaults grantedAuthorityDefaults = context
.getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class); .getBean(grantedAuthorityDefaultsBeanNames[0], GrantedAuthorityDefaults.class);
securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix()); this.securityContextRequestFilter.setRolePrefix(grantedAuthorityDefaults.getRolePrefix());
} }
} }
securityContextRequestFilter = postProcess(securityContextRequestFilter); this.securityContextRequestFilter = postProcess(this.securityContextRequestFilter);
http.addFilter(securityContextRequestFilter); http.addFilter(this.securityContextRequestFilter);
} }
} }

View File

@ -100,7 +100,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations * @return the {@link ExpressionUrlAuthorizationConfigurer} for further customizations
*/ */
public StandardInterceptUrlRegistry getRegistry() { public StandardInterceptUrlRegistry getRegistry() {
return REGISTRY; return this.REGISTRY;
} }
/** /**
@ -176,7 +176,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
*/ */
@Override @Override
FilterInvocationSecurityMetadataSource createMetadataSource(H http) { FilterInvocationSecurityMetadataSource createMetadataSource(H http) {
return new DefaultFilterInvocationSecurityMetadataSource(REGISTRY.createRequestMap()); return new DefaultFilterInvocationSecurityMetadataSource(this.REGISTRY.createRequestMap());
} }
/** /**
@ -191,10 +191,10 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
private StandardInterceptUrlRegistry addMapping(Iterable<? extends RequestMatcher> requestMatchers, private StandardInterceptUrlRegistry addMapping(Iterable<? extends RequestMatcher> requestMatchers,
Collection<ConfigAttribute> configAttributes) { Collection<ConfigAttribute> configAttributes) {
for (RequestMatcher requestMatcher : requestMatchers) { for (RequestMatcher requestMatcher : requestMatchers) {
REGISTRY.addMapping( this.REGISTRY.addMapping(
new AbstractConfigAttributeRequestMatcherRegistry.UrlMapping(requestMatcher, configAttributes)); new AbstractConfigAttributeRequestMatcherRegistry.UrlMapping(requestMatcher, configAttributes));
} }
return REGISTRY; return this.REGISTRY;
} }
/** /**
@ -334,7 +334,7 @@ public final class UrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
* @return the {@link UrlAuthorizationConfigurer} for further customization * @return the {@link UrlAuthorizationConfigurer} for further customization
*/ */
public StandardInterceptUrlRegistry access(String... attributes) { public StandardInterceptUrlRegistry access(String... attributes) {
addMapping(requestMatchers, SecurityConfig.createList(attributes)); addMapping(this.requestMatchers, SecurityConfig.createList(attributes));
return UrlAuthorizationConfigurer.this.REGISTRY; return UrlAuthorizationConfigurer.this.REGISTRY;
} }

View File

@ -185,27 +185,27 @@ public final class X509Configurer<H extends HttpSecurityBuilder<H>>
} }
private X509AuthenticationFilter getFilter(AuthenticationManager authenticationManager) { private X509AuthenticationFilter getFilter(AuthenticationManager authenticationManager) {
if (x509AuthenticationFilter == null) { if (this.x509AuthenticationFilter == null) {
x509AuthenticationFilter = new X509AuthenticationFilter(); this.x509AuthenticationFilter = new X509AuthenticationFilter();
x509AuthenticationFilter.setAuthenticationManager(authenticationManager); this.x509AuthenticationFilter.setAuthenticationManager(authenticationManager);
if (x509PrincipalExtractor != null) { if (this.x509PrincipalExtractor != null) {
x509AuthenticationFilter.setPrincipalExtractor(x509PrincipalExtractor); this.x509AuthenticationFilter.setPrincipalExtractor(this.x509PrincipalExtractor);
} }
if (authenticationDetailsSource != null) { if (this.authenticationDetailsSource != null) {
x509AuthenticationFilter.setAuthenticationDetailsSource(authenticationDetailsSource); this.x509AuthenticationFilter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
} }
x509AuthenticationFilter = postProcess(x509AuthenticationFilter); this.x509AuthenticationFilter = postProcess(this.x509AuthenticationFilter);
} }
return x509AuthenticationFilter; return this.x509AuthenticationFilter;
} }
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getAuthenticationUserDetailsService( private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getAuthenticationUserDetailsService(
H http) { H http) {
if (authenticationUserDetailsService == null) { if (this.authenticationUserDetailsService == null) {
userDetailsService(http.getSharedObject(UserDetailsService.class)); userDetailsService(http.getSharedObject(UserDetailsService.class));
} }
return authenticationUserDetailsService; return this.authenticationUserDetailsService;
} }
} }

View File

@ -210,9 +210,9 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
this.relyingPartyRegistrationRepository = getSharedOrBean(http, RelyingPartyRegistrationRepository.class); this.relyingPartyRegistrationRepository = getSharedOrBean(http, RelyingPartyRegistrationRepository.class);
} }
saml2WebSsoAuthenticationFilter = new Saml2WebSsoAuthenticationFilter(getAuthenticationConverter(http), this.saml2WebSsoAuthenticationFilter = new Saml2WebSsoAuthenticationFilter(getAuthenticationConverter(http),
this.loginProcessingUrl); this.loginProcessingUrl);
setAuthenticationFilter(saml2WebSsoAuthenticationFilter); setAuthenticationFilter(this.saml2WebSsoAuthenticationFilter);
super.loginProcessingUrl(this.loginProcessingUrl); super.loginProcessingUrl(this.loginProcessingUrl);
if (hasText(this.loginPage)) { if (hasText(this.loginPage)) {
@ -258,7 +258,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
registerDefaultAuthenticationProvider(http); registerDefaultAuthenticationProvider(http);
} }
else { else {
saml2WebSsoAuthenticationFilter.setAuthenticationManager(this.authenticationManager); this.saml2WebSsoAuthenticationFilter.setAuthenticationManager(this.authenticationManager);
} }
} }
@ -281,7 +281,7 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
return; return;
} }
csrf.ignoringRequestMatchers(new AntPathRequestMatcher(loginProcessingUrl)); csrf.ignoringRequestMatchers(new AntPathRequestMatcher(this.loginProcessingUrl));
} }
private void initDefaultLoginFilter(B http) { private void initDefaultLoginFilter(B http) {

View File

@ -231,7 +231,7 @@ public class MessageSecurityMetadataSourceRegistry {
matcherToExpression.put(entry.getKey().build(), entry.getValue()); matcherToExpression.put(entry.getKey().build(), entry.getValue());
} }
return ExpressionBasedMessageSecurityMetadataSourceFactory return ExpressionBasedMessageSecurityMetadataSourceFactory
.createExpressionMessageMetadataSource(matcherToExpression, expressionHandler); .createExpressionMessageMetadataSource(matcherToExpression, this.expressionHandler);
} }
/** /**
@ -378,8 +378,8 @@ public class MessageSecurityMetadataSourceRegistry {
* customization * customization
*/ */
public MessageSecurityMetadataSourceRegistry access(String attribute) { public MessageSecurityMetadataSourceRegistry access(String attribute) {
for (MatcherBuilder messageMatcher : messageMatchers) { for (MatcherBuilder messageMatcher : this.messageMatchers) {
matcherToExpression.put(messageMatcher, attribute); MessageSecurityMetadataSourceRegistry.this.matcherToExpression.put(messageMatcher, attribute);
} }
return MessageSecurityMetadataSourceRegistry.this; return MessageSecurityMetadataSourceRegistry.this;
} }
@ -418,7 +418,7 @@ public class MessageSecurityMetadataSourceRegistry {
} }
public MessageMatcher<?> build() { public MessageMatcher<?> build() {
return matcher; return this.matcher;
} }
} }
@ -435,16 +435,19 @@ public class MessageSecurityMetadataSourceRegistry {
} }
public MessageMatcher<?> build() { public MessageMatcher<?> build() {
if (type == null) { if (this.type == null) {
return new SimpDestinationMessageMatcher(pattern, pathMatcher); return new SimpDestinationMessageMatcher(this.pattern,
MessageSecurityMetadataSourceRegistry.this.pathMatcher);
} }
else if (SimpMessageType.MESSAGE == type) { else if (SimpMessageType.MESSAGE == this.type) {
return SimpDestinationMessageMatcher.createMessageMatcher(pattern, pathMatcher); return SimpDestinationMessageMatcher.createMessageMatcher(this.pattern,
MessageSecurityMetadataSourceRegistry.this.pathMatcher);
} }
else if (SimpMessageType.SUBSCRIBE == type) { else if (SimpMessageType.SUBSCRIBE == this.type) {
return SimpDestinationMessageMatcher.createSubscribeMatcher(pattern, pathMatcher); return SimpDestinationMessageMatcher.createSubscribeMatcher(this.pattern,
MessageSecurityMetadataSourceRegistry.this.pathMatcher);
} }
throw new IllegalStateException(type + " is not supported since it does not have a destination"); throw new IllegalStateException(this.type + " is not supported since it does not have a destination");
} }
} }
@ -460,31 +463,31 @@ public class MessageSecurityMetadataSourceRegistry {
private PathMatcher delegate = new AntPathMatcher(); private PathMatcher delegate = new AntPathMatcher();
public boolean isPattern(String path) { public boolean isPattern(String path) {
return delegate.isPattern(path); return this.delegate.isPattern(path);
} }
public boolean match(String pattern, String path) { public boolean match(String pattern, String path) {
return delegate.match(pattern, path); return this.delegate.match(pattern, path);
} }
public boolean matchStart(String pattern, String path) { public boolean matchStart(String pattern, String path) {
return delegate.matchStart(pattern, path); return this.delegate.matchStart(pattern, path);
} }
public String extractPathWithinPattern(String pattern, String path) { public String extractPathWithinPattern(String pattern, String path) {
return delegate.extractPathWithinPattern(pattern, path); return this.delegate.extractPathWithinPattern(pattern, path);
} }
public Map<String, String> extractUriTemplateVariables(String pattern, String path) { public Map<String, String> extractUriTemplateVariables(String pattern, String path) {
return delegate.extractUriTemplateVariables(pattern, path); return this.delegate.extractUriTemplateVariables(pattern, path);
} }
public Comparator<String> getPatternComparator(String path) { public Comparator<String> getPatternComparator(String path) {
return delegate.getPatternComparator(path); return this.delegate.getPatternComparator(path);
} }
public String combine(String pattern1, String pattern2) { public String combine(String pattern1, String pattern2) {
return delegate.combine(pattern1, pattern2); return this.delegate.combine(pattern1, pattern2);
} }
void setPathMatcher(PathMatcher pathMatcher) { void setPathMatcher(PathMatcher pathMatcher) {

View File

@ -103,12 +103,12 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
@Override @Override
public final void configureClientInboundChannel(ChannelRegistration registration) { public final void configureClientInboundChannel(ChannelRegistration registration) {
ChannelSecurityInterceptor inboundChannelSecurity = context.getBean(ChannelSecurityInterceptor.class); ChannelSecurityInterceptor inboundChannelSecurity = this.context.getBean(ChannelSecurityInterceptor.class);
registration.setInterceptors(context.getBean(SecurityContextChannelInterceptor.class)); registration.setInterceptors(this.context.getBean(SecurityContextChannelInterceptor.class));
if (!sameOriginDisabled()) { if (!sameOriginDisabled()) {
registration.setInterceptors(context.getBean(CsrfChannelInterceptor.class)); registration.setInterceptors(this.context.getBean(CsrfChannelInterceptor.class));
} }
if (inboundRegistry.containsMapping()) { if (this.inboundRegistry.containsMapping()) {
registration.setInterceptors(inboundChannelSecurity); registration.setInterceptors(inboundChannelSecurity);
} }
customizeClientInboundChannel(registration); customizeClientInboundChannel(registration);
@ -116,7 +116,7 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
private PathMatcher getDefaultPathMatcher() { private PathMatcher getDefaultPathMatcher() {
try { try {
return context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher(); return this.context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher();
} }
catch (NoSuchBeanDefinitionException e) { catch (NoSuchBeanDefinitionException e) {
return new AntPathMatcher(); return new AntPathMatcher();
@ -174,9 +174,9 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
@Bean @Bean
public MessageSecurityMetadataSource inboundMessageSecurityMetadataSource() { public MessageSecurityMetadataSource inboundMessageSecurityMetadataSource() {
inboundRegistry.expressionHandler(getMessageExpressionHandler()); this.inboundRegistry.expressionHandler(getMessageExpressionHandler());
configureInbound(inboundRegistry); configureInbound(this.inboundRegistry);
return inboundRegistry.createMetadataSource(); return this.inboundRegistry.createMetadataSource();
} }
/** /**
@ -223,14 +223,14 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
@Autowired(required = false) @Autowired(required = false)
public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) { public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) {
defaultExpressionHandler = objectPostProcessor.postProcess(defaultExpressionHandler); this.defaultExpressionHandler = objectPostProcessor.postProcess(this.defaultExpressionHandler);
} }
private SecurityExpressionHandler<Message<Object>> getMessageExpressionHandler() { private SecurityExpressionHandler<Message<Object>> getMessageExpressionHandler() {
if (expressionHandler == null) { if (this.expressionHandler == null) {
return defaultExpressionHandler; return this.defaultExpressionHandler;
} }
return expressionHandler; return this.expressionHandler;
} }
public void afterSingletonsInstantiated() { public void afterSingletonsInstantiated() {
@ -239,7 +239,7 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
} }
String beanName = "stompWebSocketHandlerMapping"; String beanName = "stompWebSocketHandlerMapping";
SimpleUrlHandlerMapping mapping = context.getBean(beanName, SimpleUrlHandlerMapping.class); SimpleUrlHandlerMapping mapping = this.context.getBean(beanName, SimpleUrlHandlerMapping.class);
Map<String, Object> mappings = mapping.getHandlerMap(); Map<String, Object> mappings = mapping.getHandlerMap();
for (Object object : mappings.values()) { for (Object object : mappings.values()) {
if (object instanceof SockJsHttpRequestHandler) { if (object instanceof SockJsHttpRequestHandler) {
@ -275,9 +275,9 @@ public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends A
} }
} }
if (inboundRegistry.containsMapping() && !inboundRegistry.isSimpDestPathMatcherConfigured()) { if (this.inboundRegistry.containsMapping() && !this.inboundRegistry.isSimpDestPathMatcherConfigured()) {
PathMatcher pathMatcher = getDefaultPathMatcher(); PathMatcher pathMatcher = getDefaultPathMatcher();
inboundRegistry.simpDestPathMatcher(pathMatcher); this.inboundRegistry.simpDestPathMatcher(pathMatcher);
} }
} }

View File

@ -48,7 +48,7 @@ public class AuthenticationManagerFactoryBean implements FactoryBean<Authenticat
public AuthenticationManager getObject() throws Exception { public AuthenticationManager getObject() throws Exception {
try { try {
return (AuthenticationManager) bf.getBean(BeanIds.AUTHENTICATION_MANAGER); return (AuthenticationManager) this.bf.getBean(BeanIds.AUTHENTICATION_MANAGER);
} }
catch (NoSuchBeanDefinitionException e) { catch (NoSuchBeanDefinitionException e) {
if (!BeanIds.AUTHENTICATION_MANAGER.equals(e.getBeanName())) { if (!BeanIds.AUTHENTICATION_MANAGER.equals(e.getBeanName())) {
@ -80,7 +80,7 @@ public class AuthenticationManagerFactoryBean implements FactoryBean<Authenticat
} }
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
bf = beanFactory; this.bf = beanFactory;
} }
private <T> T getBeanOrNull(Class<T> type) { private <T> T getBeanOrNull(Class<T> type) {

View File

@ -76,11 +76,11 @@ public class PasswordEncoderParser {
String ref = element.getAttribute(ATT_REF); String ref = element.getAttribute(ATT_REF);
if (StringUtils.hasText(ref)) { if (StringUtils.hasText(ref)) {
passwordEncoder = new RuntimeBeanReference(ref); this.passwordEncoder = new RuntimeBeanReference(ref);
} }
else { else {
passwordEncoder = createPasswordEncoderBeanDefinition(hash, useBase64); this.passwordEncoder = createPasswordEncoderBeanDefinition(hash, useBase64);
((RootBeanDefinition) passwordEncoder).setSource(parserContext.extractSource(element)); ((RootBeanDefinition) this.passwordEncoder).setSource(parserContext.extractSource(element));
} }
} }
@ -91,7 +91,7 @@ public class PasswordEncoderParser {
} }
public BeanMetadataElement getPasswordEncoder() { public BeanMetadataElement getPasswordEncoder() {
return passwordEncoder; return this.passwordEncoder;
} }
} }

View File

@ -112,16 +112,16 @@ public class UserServiceBeanDefinitionParser extends AbstractUserDetailsServiceB
} }
private String generateRandomPassword() { private String generateRandomPassword() {
if (random == null) { if (this.random == null) {
try { try {
random = SecureRandom.getInstance("SHA1PRNG"); this.random = SecureRandom.getInstance("SHA1PRNG");
} }
catch (NoSuchAlgorithmException e) { catch (NoSuchAlgorithmException e) {
// Shouldn't happen... // Shouldn't happen...
throw new RuntimeException("Failed find SHA1PRNG algorithm!"); throw new RuntimeException("Failed find SHA1PRNG algorithm!");
} }
} }
return Long.toString(random.nextLong()); return Long.toString(this.random.nextLong());
} }
} }

View File

@ -41,7 +41,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBean
@Override @Override
public MapReactiveUserDetailsService getObject() throws Exception { public MapReactiveUserDetailsService getObject() throws Exception {
Collection<UserDetails> users = userDetails.getObject(); Collection<UserDetails> users = this.userDetails.getObject();
return new MapReactiveUserDetailsService(users); return new MapReactiveUserDetailsService(users);
} }
@ -52,7 +52,7 @@ public class ReactiveUserDetailsServiceResourceFactoryBean
@Override @Override
public void setResourceLoader(ResourceLoader resourceLoader) { public void setResourceLoader(ResourceLoader resourceLoader) {
userDetails.setResourceLoader(resourceLoader); this.userDetails.setResourceLoader(resourceLoader);
} }
/** /**

View File

@ -98,9 +98,9 @@ public class UserDetailsResourceFactoryBean implements ResourceLoaderAware, Fact
} }
private Resource getPropertiesResource() { private Resource getPropertiesResource() {
Resource result = resource; Resource result = this.resource;
if (result == null && resourceLocation != null) { if (result == null && this.resourceLocation != null) {
result = resourceLoader.getResource(resourceLocation); result = this.resourceLoader.getResource(this.resourceLocation);
} }
Assert.notNull(result, "resource cannot be null if resourceLocation is null"); Assert.notNull(result, "resource cannot be null if resourceLocation is null");
return result; return result;

Some files were not shown because too many files have changed in this diff Show More