Howto use acegi-security and the @Secured annotation for method interception

Acegi-security (now spring-security) provides a @Secured (org.acegisecurity.annotation.Secured) annotation.
Classes using this annotation can be processed by a suitable BeanPostProcessor, which will proxy the class so that calls to @Secured methods are intercepted and the required authentication is validated against the acegi security context. Note that the following is a configuration for acegi-security, things might be different with spring-security.

2008-07-12: Comment: It is indeed a lot simpler using spring-security, as Craig Walls demonstrates in this posting in his blog “Spring-Loaded”).

In order to activate the post processing for the @Secured annotations, a spring configuration such as the following is required:

    <!-- Bean post-processor for activating any advisors -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>

    <!-- The advisor that creates secured proxies for beans using security annotations such as @Secured -->
    <bean class="org.acegisecurity.intercept.method.aopalliance.MethodDefinitionSourceAdvisor">
        <constructor-arg>
            <ref bean="myMethodInterceptor"/>
        </constructor-arg>
    </bean>

Where myMethodInterceptor is a MethodSecurityInterceptor, which may be configured like this:

    <bean id="myMethodInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
        <property name="validateConfigAttributes" value="false"/>
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="accessDecisionManager"/>
        <property name="objectDefinitionSource" ref="objectDefinitionSource"/>
    </bean>

With a suitable AuthenticationManager, AccessDescisionManager and and objectDefinitionSource of type MethodDefinitionSource.

Often it is the case that annotated bean classes must be proxied directly, rather than proxying some implemented interface.

If you get an exception such as

Failed to convert property value of type [$Proxy70] to required type ...
no matching editors or conversion strategy found

Your solution might be to force the proxying of the target class itself using:

    <!-- Bean post-processor for auto-activating all advisors -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
        <property name="proxyTargetClass" value="true" />
    </bean>

This entry was posted on Friday, July 4th, 2008 at 11:19. Posted in: J2EE, System architecture, acegi, java, spring. You can follow any responses to this entry through the RSS 2.0feed. You can leave a response, or trackback from your own site.

Leave a Reply