How to add AccessDescisionVoters to AccessDescisionManager in Spring Security

Here’s a pretty neat approach to add AccessDescisionVoters to the default AccessDescisionManager in Spring Security:

/**
 * This BeanPostProcessor adds all {@link AccessDecisionVoter}s that are set with
 * {@link #setAdditionalAccessDecisionVoters(List)} to beans that are instances of {@link AffirmativeBased}. This is the
 * default {@link AccessDecisionManager} implementation that the spring security namespace handler creates.
 * <p>
 *
 * The configuration could look like:
 *
 * <pre>
 * {@code
 * <bean id="voterAdder">
 *   <property name="additionalAccessDecisionVoters">
 *     <list>
 *       <bean />
 *     </list>
 *   </property>
 * </bean>
 * }
 * </pre>
 */
@Component
public class VoterAdder implements BeanPostProcessor {
  private List<AccessDecisionVoter> additionalAccessDecisionVoters;

  public void setAdditionalAccessDecisionVoters(List<AccessDecisionVoter> additionalAccessDecisionVoters) {
    this.additionalAccessDecisionVoters = additionalAccessDecisionVoters;
  }

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof AffirmativeBased) {
      AffirmativeBased dm = (AffirmativeBased) bean;
      additionalAccessDecisionVoters.addAll(dm.getDecisionVoters());
      dm.setDecisionVoters(additionalAccessDecisionVoters);
    }
    return bean;
  }
}

Source: http://forum.springsource.org/showthread.php?116830-How-to-add-voters-to-the-default-accessDecisionManager&s=1a6d05dedb0342570b900141a6d53d2e&p=386079#post386079

Leave a Reply