SEC-271: added Ordered interface to AcessDecisionVoters

This commit is contained in:
Vishal Puri 2007-07-06 13:34:43 +00:00
parent 02cf570be7
commit 0e46e5307c
5 changed files with 775 additions and 570 deletions

View File

@ -39,8 +39,11 @@ import org.acegisecurity.runas.NullRunAsManager;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.ApplicationEventPublisherAware;
@ -52,86 +55,119 @@ import org.springframework.util.Assert;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* Abstract class that implements security interception for secure objects.<p>The * Abstract class that implements security interception for secure objects.
* <code>AbstractSecurityInterceptor</code> will ensure the proper startup configuration of the security interceptor. * <p>
* It will also implement the proper handling of secure object invocations, being: * The <code>AbstractSecurityInterceptor</code> will ensure the proper startup
* configuration of the security interceptor. It will also implement the proper
* handling of secure object invocations, being:
* <ol> * <ol>
* <li>Obtain the {@link Authentication} object from the {@link SecurityContextHolder}.</li> * <li>Obtain the {@link Authentication} object from the
* <li>Determine if the request relates to a secured or public invocation by looking up the secure object * {@link SecurityContextHolder}.</li>
* request against the {@link ObjectDefinitionSource}.</li> * <li>Determine if the request relates to a secured or public invocation by
* <li>For an invocation that is secured (there is a <code>ConfigAttributeDefinition</code> for the secure * looking up the secure object request against the
* object invocation): * {@link ObjectDefinitionSource}.</li>
* <li>For an invocation that is secured (there is a
* <code>ConfigAttributeDefinition</code> for the secure object invocation):
* <ol type="a"> * <ol type="a">
* <li>If either the {@link org.acegisecurity.Authentication#isAuthenticated()} returns * <li>If either the {@link org.acegisecurity.Authentication#isAuthenticated()}
* <code>false</code>, or the {@link #alwaysReauthenticate} is <code>true</code>, authenticate the request * returns <code>false</code>, or the {@link #alwaysReauthenticate} is
* against the configured {@link AuthenticationManager}. When authenticated, replace the * <code>true</code>, authenticate the request against the configured
* <code>Authentication</code> object on the <code>SecurityContextHolder</code> with the returned value.</li> * {@link AuthenticationManager}. When authenticated, replace the
* <li>Authorize the request against the configured {@link AccessDecisionManager}.</li> * <code>Authentication</code> object on the
* <code>SecurityContextHolder</code> with the returned value.</li>
* <li>Authorize the request against the configured
* {@link AccessDecisionManager}.</li>
* <li>Perform any run-as replacement via the configured {@link RunAsManager}.</li> * <li>Perform any run-as replacement via the configured {@link RunAsManager}.</li>
* <li>Pass control back to the concrete subclass, which will actually proceed with executing the * <li>Pass control back to the concrete subclass, which will actually proceed
* object. A {@link InterceptorStatusToken} is returned so that after the subclass has finished proceeding * with executing the object. A {@link InterceptorStatusToken} is returned so
* with execution of the object, its finally clause can ensure the <code>AbstractSecurityInterceptor</code> * that after the subclass has finished proceeding with execution of the object,
* its finally clause can ensure the <code>AbstractSecurityInterceptor</code>
* is re-called and tidies up correctly.</li> * is re-called and tidies up correctly.</li>
* <li>The concrete subclass will re-call the <code>AbstractSecurityInterceptor</code> via the * <li>The concrete subclass will re-call the
* <code>AbstractSecurityInterceptor</code> via the
* {@link #afterInvocation(InterceptorStatusToken, Object)} method.</li> * {@link #afterInvocation(InterceptorStatusToken, Object)} method.</li>
* <li>If the <code>RunAsManager</code> replaced the <code>Authentication</code> object, return * <li>If the <code>RunAsManager</code> replaced the
* the <code>SecurityContextHolder</code> to the object that existed after the call to * <code>Authentication</code> object, return the
* <code>AuthenticationManager</code>.</li> * <code>SecurityContextHolder</code> to the object that existed after the
* <li>If an <code>AfterInvocationManager</code> is defined, invoke the invocation manager and * call to <code>AuthenticationManager</code>.</li>
* allow it to replace the object due to be returned to the caller.</li> * <li>If an <code>AfterInvocationManager</code> is defined, invoke the
* invocation manager and allow it to replace the object due to be returned to
* the caller.</li>
* </ol> * </ol>
* </li> * </li>
* <li>For an invocation that is public (there is no <code>ConfigAttributeDefinition</code> for the secure * <li>For an invocation that is public (there is no
* object invocation): * <code>ConfigAttributeDefinition</code> for the secure object invocation):
* <ol type="a"> * <ol type="a">
* <li>As described above, the concrete subclass will be returned an * <li>As described above, the concrete subclass will be returned an
* <code>InterceptorStatusToken</code> which is subsequently re-presented to the * <code>InterceptorStatusToken</code> which is subsequently re-presented to
* <code>AbstractSecurityInterceptor</code> after the secure object has been executed. The * the <code>AbstractSecurityInterceptor</code> after the secure object has
* <code>AbstractSecurityInterceptor</code> will take no further action when its {@link * been executed. The <code>AbstractSecurityInterceptor</code> will take no
* #afterInvocation(InterceptorStatusToken, Object)} is called.</li> * further action when its {@link #afterInvocation(InterceptorStatusToken,
* Object)} is called.</li>
* </ol> * </ol>
* </li> * </li>
* <li>Control again returns to the concrete subclass, along with the <code>Object</code> that should be * <li>Control again returns to the concrete subclass, along with the
* returned to the caller. The subclass will then return that result or exception to the original caller.</li> * <code>Object</code> that should be returned to the caller. The subclass
* will then return that result or exception to the original caller.</li>
* </ol> * </ol>
* </p> * </p>
* *
* @author Ben Alex * @author Ben Alex
* @version $Id$ * @version $Id: AbstractSecurityInterceptor.java 1790 2007-03-30 18:27:19Z
* luke_t $
*/ */
public abstract class AbstractSecurityInterceptor implements InitializingBean, ApplicationEventPublisherAware, public abstract class AbstractSecurityInterceptor implements InitializingBean, ApplicationEventPublisherAware,
MessageSourceAware { MessageSourceAware, ApplicationContextAware {
//~ Static fields/initializers ===================================================================================== // ~ Static fields/initializers
// =====================================================================================
protected static final Log logger = LogFactory.getLog(AbstractSecurityInterceptor.class); protected static final Log logger = LogFactory.getLog(AbstractSecurityInterceptor.class);
//~ Instance fields ================================================================================================ // ~ Instance fields
// ================================================================================================
private AccessDecisionManager accessDecisionManager; private AccessDecisionManager accessDecisionManager;
private AfterInvocationManager afterInvocationManager; private AfterInvocationManager afterInvocationManager;
private ApplicationEventPublisher eventPublisher; private ApplicationEventPublisher eventPublisher;
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor(); protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor();
private RunAsManager runAsManager = new NullRunAsManager(); private RunAsManager runAsManager = new NullRunAsManager();
private boolean alwaysReauthenticate = false; private boolean alwaysReauthenticate = false;
private boolean rejectPublicInvocations = false; private boolean rejectPublicInvocations = false;
private boolean validateConfigAttributes = true; private boolean validateConfigAttributes = true;
//~ Methods ======================================================================================================== private boolean isSetAuthenticationManagerInvoked = false;
private boolean isSetAccessDecisionManagerInvoked = false;
private ApplicationContext applicationContext;
// ~ Methods
// ========================================================================================================
/** /**
* Completes the work of the <code>AbstractSecurityInterceptor</code> after the secure object invocation * Completes the work of the <code>AbstractSecurityInterceptor</code>
* has been complete * after the secure object invocation has been complete
* *
* @param token as returned by the {@link #beforeInvocation(Object)}} method * @param token as returned by the {@link #beforeInvocation(Object)}}
* @param returnedObject any object returned from the secure object invocation (may be<code>null</code>) * method
* @param returnedObject any object returned from the secure object
* invocation (may be<code>null</code>)
* *
* @return the object the secure object invocation should ultimately return to its caller (may be * @return the object the secure object invocation should ultimately return
* <code>null</code>) * to its caller (may be <code>null</code>)
*/ */
protected Object afterInvocation(InterceptorStatusToken token, Object returnedObject) { protected Object afterInvocation(InterceptorStatusToken token, Object returnedObject) {
if (token == null) { if (token == null) {
@ -152,9 +188,10 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
try { try {
returnedObject = afterInvocationManager.decide(token.getAuthentication(), token.getSecureObject(), returnedObject = afterInvocationManager.decide(token.getAuthentication(), token.getSecureObject(),
token.getAttr(), returnedObject); token.getAttr(), returnedObject);
} catch (AccessDeniedException accessDeniedException) { }
AuthorizationFailureEvent event = new AuthorizationFailureEvent(token.getSecureObject(), catch (AccessDeniedException accessDeniedException) {
token.getAttr(), token.getAuthentication(), accessDeniedException); AuthorizationFailureEvent event = new AuthorizationFailureEvent(token.getSecureObject(), token
.getAttr(), token.getAuthentication(), accessDeniedException);
publishEvent(event); publishEvent(event);
throw accessDeniedException; throw accessDeniedException;
@ -168,8 +205,15 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
Assert.notNull(getSecureObjectClass(), "Subclass must provide a non-null response to getSecureObjectClass()"); Assert.notNull(getSecureObjectClass(), "Subclass must provide a non-null response to getSecureObjectClass()");
Assert.notNull(this.messages, "A message source must be set"); Assert.notNull(this.messages, "A message source must be set");
if (!isSetAuthenticationManagerInvoked) {
autoDetectAuthenticationManager();
}
Assert.notNull(this.authenticationManager, "An AuthenticationManager is required"); Assert.notNull(this.authenticationManager, "An AuthenticationManager is required");
if (!isSetAccessDecisionManagerInvoked) {
autoDetectAccessDecisionManager();
}
Assert.notNull(this.accessDecisionManager, "An AccessDecisionManager is required"); Assert.notNull(this.accessDecisionManager, "An AccessDecisionManager is required");
Assert.notNull(this.runAsManager, "A RunAsManager is required"); Assert.notNull(this.runAsManager, "A RunAsManager is required");
@ -223,6 +267,47 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
} }
/**
* Introspects the <code>Applicationcontext</code> for the single instance
* of <code>AccessDecisionManager</code>. If more than one instance of
* <code>AccessDecisionManager</code> is found, the method uses the first
* one detected.
*
* @param applicationContext to locate the instance
*/
private void autoDetectAccessDecisionManager() {
if (applicationContext != null) {
Map map = applicationContext.getBeansOfType(AccessDecisionManager.class);
if (map.size() > 0)
setAccessDecisionManager((AccessDecisionManager) map.values().iterator().next());
}
}
/**
* Introspects the <code>Applicationcontext</code> for the single instance
* of <code>AuthenticationManager</code>. If found invoke
* setAuthenticationManager method by providing the found instance of
* authenticationManager as a method parameter. If more than one instance of
* <code>AuthenticationManager</code> is found, the method throws
* <code>IllegalStateException</code>.
*
* @param applicationContext to locate the instance
*/
private void autoDetectAuthenticationManager() {
if (applicationContext != null) {
Map map = applicationContext.getBeansOfType(AuthenticationManager.class);
if (map.size() > 1) {
throw new IllegalArgumentException(
"More than one AuthenticationManager beans detected please refer to the one using "
+ " [ authenticationManager ] " + "property");
}
else if (map.size() == 1) {
setAuthenticationManager((AuthenticationManager) map.values().iterator().next());
}
}
}
protected InterceptorStatusToken beforeInvocation(Object object) { protected InterceptorStatusToken beforeInvocation(Object object) {
Assert.notNull(object, "Object was null"); Assert.notNull(object, "Object was null");
@ -236,7 +321,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource().getAttributes(object); ConfigAttributeDefinition attr = this.obtainObjectDefinitionSource().getAttributes(object);
if (attr == null) { if (attr == null) {
if(rejectPublicInvocations) { if (rejectPublicInvocations) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"No public invocations are allowed via this AbstractSecurityInterceptor. " "No public invocations are allowed via this AbstractSecurityInterceptor. "
+ "This indicates a configuration error because the " + "This indicates a configuration error because the "
@ -252,7 +337,6 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
return null; // no further work post-invocation return null; // no further work post-invocation
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Secure object: " + object.toString() + "; ConfigAttributes: " + attr.toString()); logger.debug("Secure object: " + object.toString() + "; ConfigAttributes: " + attr.toString());
} }
@ -262,24 +346,28 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
"An Authentication object was not found in the SecurityContext"), object, attr); "An Authentication object was not found in the SecurityContext"), object, attr);
} }
// Attempt authentication if not already authenticated, or user always wants reauthentication // Attempt authentication if not already authenticated, or user always
// wants reauthentication
Authentication authenticated; Authentication authenticated;
if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated() || alwaysReauthenticate) { if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated() || alwaysReauthenticate) {
try { try {
authenticated = this.authenticationManager.authenticate(SecurityContextHolder.getContext() authenticated = this.authenticationManager.authenticate(SecurityContextHolder.getContext()
.getAuthentication()); .getAuthentication());
} catch (AuthenticationException authenticationException) { }
catch (AuthenticationException authenticationException) {
throw authenticationException; throw authenticationException;
} }
// We don't authenticated.setAuthentication(true), because each provider should do that // We don't authenticated.setAuthentication(true), because each
// provider should do that
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Successfully Authenticated: " + authenticated.toString()); logger.debug("Successfully Authenticated: " + authenticated.toString());
} }
SecurityContextHolder.getContext().setAuthentication(authenticated); SecurityContextHolder.getContext().setAuthentication(authenticated);
} else { }
else {
authenticated = SecurityContextHolder.getContext().getAuthentication(); authenticated = SecurityContextHolder.getContext().getAuthentication();
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
@ -290,7 +378,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
// Attempt authorization // Attempt authorization
try { try {
this.accessDecisionManager.decide(authenticated, object, attr); this.accessDecisionManager.decide(authenticated, object, attr);
} catch (AccessDeniedException accessDeniedException) { }
catch (AccessDeniedException accessDeniedException) {
AuthorizationFailureEvent event = new AuthorizationFailureEvent(object, attr, authenticated, AuthorizationFailureEvent event = new AuthorizationFailureEvent(object, attr, authenticated,
accessDeniedException); accessDeniedException);
publishEvent(event); publishEvent(event);
@ -315,7 +404,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
// no further work post-invocation // no further work post-invocation
return new InterceptorStatusToken(authenticated, false, attr, object); return new InterceptorStatusToken(authenticated, false, attr, object);
} else { }
else {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Switching to RunAs Authentication: " + runAs.toString()); logger.debug("Switching to RunAs Authentication: " + runAs.toString());
} }
@ -328,8 +418,11 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
/** /**
* Helper method which generates an exception containing the passed reason, and publishes an event to the * Helper method which generates an exception containing the passed reason,
* application context.<p>Always throws an exception.</p> * and publishes an event to the application context.
* <p>
* Always throws an exception.
* </p>
* *
* @param reason to be provided in the exception detail * @param reason to be provided in the exception detail
* @param secureObject that was being called * @param secureObject that was being called
@ -362,9 +455,10 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
/** /**
* Indicates the type of secure objects the subclass will be presenting to the abstract parent for * Indicates the type of secure objects the subclass will be presenting to
* processing. This is used to ensure collaborators wired to the <code>AbstractSecurityInterceptor</code> all * the abstract parent for processing. This is used to ensure collaborators
* support the indicated secure object class. * wired to the <code>AbstractSecurityInterceptor</code> all support the
* indicated secure object class.
* *
* @return the type of secure object the subclass provides services for * @return the type of secure object the subclass provides services for
*/ */
@ -385,6 +479,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
public abstract ObjectDefinitionSource obtainObjectDefinitionSource(); public abstract ObjectDefinitionSource obtainObjectDefinitionSource();
public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager) { public void setAccessDecisionManager(AccessDecisionManager accessDecisionManager) {
isSetAccessDecisionManagerInvoked = true;
this.accessDecisionManager = accessDecisionManager; this.accessDecisionManager = accessDecisionManager;
} }
@ -393,14 +488,17 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
/** /**
* Indicates whether the <code>AbstractSecurityInterceptor</code> should ignore the {@link * Indicates whether the <code>AbstractSecurityInterceptor</code> should
* Authentication#isAuthenticated()} property. Defaults to <code>false</code>, meaning by default the * ignore the {@link Authentication#isAuthenticated()} property. Defaults to
* <code>Authentication.isAuthenticated()</code> property is trusted and re-authentication will not occur if the * <code>false</code>, meaning by default the
* principal has already been authenticated. * <code>Authentication.isAuthenticated()</code> property is trusted and
* re-authentication will not occur if the principal has already been
* authenticated.
* *
* @param alwaysReauthenticate <code>true</code> to force <code>AbstractSecurityInterceptor</code> to disregard the * @param alwaysReauthenticate <code>true</code> to force
* value of <code>Authentication.isAuthenticated()</code> and always re-authenticate the request (defaults * <code>AbstractSecurityInterceptor</code> to disregard the value of
* to <code>false</code>). * <code>Authentication.isAuthenticated()</code> and always
* re-authenticate the request (defaults to <code>false</code>).
*/ */
public void setAlwaysReauthenticate(boolean alwaysReauthenticate) { public void setAlwaysReauthenticate(boolean alwaysReauthenticate) {
this.alwaysReauthenticate = alwaysReauthenticate; this.alwaysReauthenticate = alwaysReauthenticate;
@ -411,6 +509,7 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
public void setAuthenticationManager(AuthenticationManager newManager) { public void setAuthenticationManager(AuthenticationManager newManager) {
isSetAuthenticationManagerInvoked = true;
this.authenticationManager = newManager; this.authenticationManager = newManager;
} }
@ -419,16 +518,21 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
} }
/** /**
* By rejecting public invocations (and setting this property to <code>true</code>), essentially you are * By rejecting public invocations (and setting this property to
* ensuring that every secure object invocation advised by <code>AbstractSecurityInterceptor</code> has a * <code>true</code>), essentially you are ensuring that every secure
* configuration attribute defined. This is useful to ensure a "fail safe" mode where undeclared secure objects * object invocation advised by <code>AbstractSecurityInterceptor</code>
* will be rejected and configuration omissions detected early. An <code>IllegalArgumentException</code> will be * has a configuration attribute defined. This is useful to ensure a "fail
* thrown by the <code>AbstractSecurityInterceptor</code> if you set this property to <code>true</code> and an * safe" mode where undeclared secure objects will be rejected and
* attempt is made to invoke a secure object that has no configuration attributes. * configuration omissions detected early. An
* <code>IllegalArgumentException</code> will be thrown by the
* <code>AbstractSecurityInterceptor</code> if you set this property to
* <code>true</code> and an attempt is made to invoke a secure object that
* has no configuration attributes.
* *
* @param rejectPublicInvocations set to <code>true</code> to reject invocations of secure objects that have no * @param rejectPublicInvocations set to <code>true</code> to reject
* configuration attributes (by default it is <code>false</code> which treats undeclared secure objects as * invocations of secure objects that have no configuration attributes (by
* "public" or unauthorized) * default it is <code>false</code> which treats undeclared secure objects
* as "public" or unauthorized)
*/ */
public void setRejectPublicInvocations(boolean rejectPublicInvocations) { public void setRejectPublicInvocations(boolean rejectPublicInvocations) {
this.rejectPublicInvocations = rejectPublicInvocations; this.rejectPublicInvocations = rejectPublicInvocations;
@ -447,4 +551,8 @@ public abstract class AbstractSecurityInterceptor implements InitializingBean, A
this.eventPublisher.publishEvent(event); this.eventPublisher.publishEvent(event);
} }
} }
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
} }

View File

@ -15,43 +15,71 @@
package org.acegisecurity.vote; package org.acegisecurity.vote;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.acegisecurity.AccessDecisionManager; import org.acegisecurity.AccessDecisionManager;
import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AcegiMessageSource; import org.acegisecurity.AcegiMessageSource;
import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttribute;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware; import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor; import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.Iterator;
import java.util.List;
/** /**
* Abstract implementation of {@link AccessDecisionManager}.<p>Handles configuration of a bean context defined list * Abstract implementation of {@link AccessDecisionManager}.
* of {@link AccessDecisionVoter}s and the access control behaviour if all voters abstain from voting (defaults to * <p>
* deny access).</p> * Handles configuration of a bean context defined list of
* {@link AccessDecisionVoter}s and the access control behaviour if all voters
* abstain from voting (defaults to deny access).
* </p>
*/ */
public abstract class AbstractAccessDecisionManager implements AccessDecisionManager, InitializingBean, public abstract class AbstractAccessDecisionManager implements AccessDecisionManager, InitializingBean,
MessageSourceAware { MessageSourceAware, ApplicationContextAware {
//~ Instance fields ================================================================================================ // ~ Instance fields
// ================================================================================================
private List decisionVoters; private List decisionVoters;
protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor(); protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor();
private boolean allowIfAllAbstainDecisions = false; private boolean allowIfAllAbstainDecisions = false;
//~ Methods ======================================================================================================== private boolean isSetDecisionVotersInvoked = false;
private ApplicationContext applicationContext;
// ~ Methods
// ========================================================================================================
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
checkIfValidList(this.decisionVoters); if (!isSetDecisionVotersInvoked) {
autoDetectVoters();
}
Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
Assert.notNull(this.messages, "A message source must be set"); Assert.notNull(this.messages, "A message source must be set");
} }
private void autoDetectVoters() {
Map map = this.applicationContext.getBeansOfType(AccessDecisionVoter.class);
List list = new ArrayList();
for(Iterator it = map.values().iterator(); it.hasNext();) {
list.add((it.next()));
}
Collections.sort(list, new OrderComparator());
setDecisionVoters(list);
}
protected final void checkAllowIfAllAbstainDecisions() { protected final void checkAllowIfAllAbstainDecisions() {
if (!this.isAllowIfAllAbstainDecisions()) { if (!this.isAllowIfAllAbstainDecisions()) {
throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied", throw new AccessDeniedException(messages.getMessage("AbstractAccessDecisionManager.accessDenied",
@ -59,12 +87,6 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
} }
} }
private void checkIfValidList(List listToCheck) {
if ((listToCheck == null) || (listToCheck.size() == 0)) {
throw new IllegalArgumentException("A list of AccessDecisionVoters is required");
}
}
public List getDecisionVoters() { public List getDecisionVoters() {
return this.decisionVoters; return this.decisionVoters;
} }
@ -78,7 +100,8 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
} }
public void setDecisionVoters(List newList) { public void setDecisionVoters(List newList) {
checkIfValidList(newList); isSetDecisionVotersInvoked = true;
Assert.notEmpty(newList);
Iterator iter = newList.iterator(); Iterator iter = newList.iterator();
@ -89,7 +112,8 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
currentObject = iter.next(); currentObject = iter.next();
AccessDecisionVoter attemptToCast = (AccessDecisionVoter) currentObject; AccessDecisionVoter attemptToCast = (AccessDecisionVoter) currentObject;
} catch (ClassCastException cce) { }
catch (ClassCastException cce) {
throw new IllegalArgumentException("AccessDecisionVoter " + currentObject.getClass().getName() throw new IllegalArgumentException("AccessDecisionVoter " + currentObject.getClass().getName()
+ " must implement AccessDecisionVoter"); + " must implement AccessDecisionVoter");
} }
@ -117,8 +141,12 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
} }
/** /**
* Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support the presented class.<p>If * Iterates through all <code>AccessDecisionVoter</code>s and ensures
* one or more voters cannot support the presented class, <code>false</code> is returned.</p> * each can support the presented class.
* <p>
* If one or more voters cannot support the presented class,
* <code>false</code> is returned.
* </p>
* *
* @param clazz DOCUMENT ME! * @param clazz DOCUMENT ME!
* *
@ -137,4 +165,9 @@ public abstract class AbstractAccessDecisionManager implements AccessDecisionMan
return true; return true;
} }
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
} }

View File

@ -21,6 +21,7 @@ import org.acegisecurity.AuthenticationTrustResolverImpl;
import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition; import org.acegisecurity.ConfigAttributeDefinition;
import org.springframework.core.Ordered;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.Iterator; import java.util.Iterator;
@ -41,17 +42,20 @@ import java.util.Iterator;
* @author Ben Alex * @author Ben Alex
* @version $Id$ * @version $Id$
*/ */
public class AuthenticatedVoter implements AccessDecisionVoter { public class AuthenticatedVoter implements AccessDecisionVoter, Ordered {
//~ Static fields/initializers ===================================================================================== //~ Static fields/initializers =====================================================================================
public static final String IS_AUTHENTICATED_FULLY = "IS_AUTHENTICATED_FULLY"; public static final String IS_AUTHENTICATED_FULLY = "IS_AUTHENTICATED_FULLY";
public static final String IS_AUTHENTICATED_REMEMBERED = "IS_AUTHENTICATED_REMEMBERED"; public static final String IS_AUTHENTICATED_REMEMBERED = "IS_AUTHENTICATED_REMEMBERED";
public static final String IS_AUTHENTICATED_ANONYMOUSLY = "IS_AUTHENTICATED_ANONYMOUSLY"; public static final String IS_AUTHENTICATED_ANONYMOUSLY = "IS_AUTHENTICATED_ANONYMOUSLY";
public static int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE;
//~ Instance fields ================================================================================================ //~ Instance fields ================================================================================================
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private int order = DEFAULT_ORDER;
//~ Methods ======================================================================================================== //~ Methods ========================================================================================================
private boolean isFullyAuthenticated(Authentication authentication) { private boolean isFullyAuthenticated(Authentication authentication) {
@ -120,4 +124,13 @@ public class AuthenticatedVoter implements AccessDecisionVoter {
return result; return result;
} }
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
} }

View File

@ -18,44 +18,65 @@ package org.acegisecurity.vote;
import org.acegisecurity.Authentication; import org.acegisecurity.Authentication;
import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition; import org.acegisecurity.ConfigAttributeDefinition;
import org.springframework.core.Ordered;
import java.util.Iterator; import java.util.Iterator;
/** /**
* <p>Votes if any {@link ConfigAttribute#getAttribute()} starts with a prefix indicating that it is a role. The * <p>
* default prefix string is <Code>ROLE_</code>, but this may be overriden to any value. It may also be set to empty, * Votes if any {@link ConfigAttribute#getAttribute()} starts with a prefix
* which means that essentially any attribute will be voted on. As described further below, the effect of an empty * indicating that it is a role. The default prefix string is <Code>ROLE_</code>,
* prefix may not be quite desireable.</p> * but this may be overriden to any value. It may also be set to empty, which
* <p>Abstains from voting if no configuration attribute commences with the role prefix. Votes to grant access if * means that essentially any attribute will be voted on. As described further
* there is an exact matching {@link org.acegisecurity.GrantedAuthority} to a <code>ConfigAttribute</code> starting * below, the effect of an empty prefix may not be quite desireable.
* with the role prefix. Votes to deny access if there is no exact matching <code>GrantedAuthority</code> to a * </p>
* <code>ConfigAttribute</code> starting with the role prefix.</p> * <p>
* <p>An empty role prefix means that the voter will vote for every ConfigAttribute. When there are different * Abstains from voting if no configuration attribute commences with the role
* categories of ConfigAttributes used, this will not be optimal since the voter will be voting for attributes which * prefix. Votes to grant access if there is an exact matching
* do not represent roles. However, this option may be of some use when using preexisting role names without a prefix, * {@link org.acegisecurity.GrantedAuthority} to a <code>ConfigAttribute</code>
* and no ability exists to prefix them with a role prefix on reading them in, such as provided for example in {@link * starting with the role prefix. Votes to deny access if there is no exact
* org.acegisecurity.userdetails.jdbc.JdbcDaoImpl}.</p> * matching <code>GrantedAuthority</code> to a <code>ConfigAttribute</code>
* <p>All comparisons and prefixes are case sensitive.</p> * starting with the role prefix.
* </p>
* <p>
* An empty role prefix means that the voter will vote for every
* ConfigAttribute. When there are different categories of ConfigAttributes
* used, this will not be optimal since the voter will be voting for attributes
* which do not represent roles. However, this option may be of some use when
* using preexisting role names without a prefix, and no ability exists to
* prefix them with a role prefix on reading them in, such as provided for
* example in {@link org.acegisecurity.userdetails.jdbc.JdbcDaoImpl}.
* </p>
* <p>
* All comparisons and prefixes are case sensitive.
* </p>
* *
* @author Ben Alex * @author Ben Alex
* @author colin sampaleanu * @author colin sampaleanu
* @version $Id$ * @version $Id$
*/ */
public class RoleVoter implements AccessDecisionVoter { public class RoleVoter implements AccessDecisionVoter, Ordered {
//~ Instance fields ================================================================================================ // ~ Static fields/initializers
// =====================================================================================
public static int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE;
// ~ Instance fields
// ================================================================================================
private String rolePrefix = "ROLE_"; private String rolePrefix = "ROLE_";
//~ Methods ======================================================================================================== private int order = DEFAULT_ORDER;
// ~ Methods
// ========================================================================================================
public String getRolePrefix() { public String getRolePrefix() {
return rolePrefix; return rolePrefix;
} }
/** /**
* Allows the default role prefix of <code>ROLE_</code> to be overriden. May be set to an empty value, * Allows the default role prefix of <code>ROLE_</code> to be overriden.
* although this is usually not desireable. * May be set to an empty value, although this is usually not desireable.
* *
* @param rolePrefix the new prefix * @param rolePrefix the new prefix
*/ */
@ -66,13 +87,15 @@ public class RoleVoter implements AccessDecisionVoter {
public boolean supports(ConfigAttribute attribute) { public boolean supports(ConfigAttribute attribute) {
if ((attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix())) { if ((attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix())) {
return true; return true;
} else { }
else {
return false; return false;
} }
} }
/** /**
* This implementation supports any type of class, because it does not query the presented secure object. * This implementation supports any type of class, because it does not query
* the presented secure object.
* *
* @param clazz the secure object * @param clazz the secure object
* *
@ -103,4 +126,13 @@ public class RoleVoter implements AccessDecisionVoter {
return result; return result;
} }
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
} }

View File

@ -18,26 +18,36 @@ package org.acegisecurity.vote;
import org.acegisecurity.Authentication; import org.acegisecurity.Authentication;
import org.acegisecurity.ConfigAttribute; import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition; import org.acegisecurity.ConfigAttributeDefinition;
import org.springframework.core.Ordered;
import java.util.Iterator; import java.util.Iterator;
/** /**
* Implementation of an {@link AccessDecisionVoter} for unit testing.<p>If the {@link * Implementation of an {@link AccessDecisionVoter} for unit testing.
* ConfigAttribute#getAttribute()} has a value of <code>DENY_AGAIN_FOR_SURE</code>, the voter will vote to deny * <p>
* access.</p> * If the {@link ConfigAttribute#getAttribute()} has a value of
* <p>All comparisons are case sensitive.</p> * <code>DENY_AGAIN_FOR_SURE</code>, the voter will vote to deny access.
* </p>
* <p>
* All comparisons are case sensitive.
* </p>
* *
* @author Ben Alex * @author Ben Alex
* @version $Id$ * @version $Id$
*/ */
public class DenyAgainVoter implements AccessDecisionVoter { public class DenyAgainVoter implements AccessDecisionVoter, Ordered {
//~ Methods ======================================================================================================== public static int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE;
private int order = DEFAULT_ORDER;
// ~ Methods
// ========================================================================================================
public boolean supports(ConfigAttribute attribute) { public boolean supports(ConfigAttribute attribute) {
if ("DENY_AGAIN_FOR_SURE".equals(attribute.getAttribute())) { if ("DENY_AGAIN_FOR_SURE".equals(attribute.getAttribute())) {
return true; return true;
} else { }
else {
return false; return false;
} }
} }
@ -59,4 +69,13 @@ public class DenyAgainVoter implements AccessDecisionVoter {
return ACCESS_ABSTAIN; return ACCESS_ABSTAIN;
} }
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
} }