javaspringspring-securityrolesauthorize

Spring Security: method is not secured with @PreAuthorize annotation


I would like to secure method in my managed session bean for specific role "ROLE_ADMIN"

config(applicationContext-security.xml):

<global-method-security pre-post-annotations="enabled" jsr250-annotations="enabled" secured-annotations="enabled"/>
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/**" access="isAuthenticated()"/>
        <intercept-url pattern="/**" access="permitAll()"/>
        <form-login
         login-processing-url="/j_spring_security_check"
         login-page="/login.jsf"
         default-target-url="/main.jsf"
         authentication-failure-url="/login.jsf" />

    <session-management>
           <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
    </session-management>
    </http>


    <authentication-manager alias="authenticationManager">
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="user1" password="user1" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener"/>

bean's secured method:

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String buy() {
...
    }

When I logged in under user1 or as anonym and click "buy" button on web-page, it still redirected to the next page.

I expect that some access denied exception occurred, and it doesn't.


Solution

  • Remember to enable method level security on your applicationContext-security.xml:

    <sec:global-method-security secured-annotations="enabled" />
    

    If, insted you will use Pre or Post annotations, use:

    <security:global-method-security pre-post-annotations="enabled"/>
    

    For more on this, see:

    http://forum.springsource.org/showthread.php?t=77862

    Note: For annotations from jsr-250:

    <sec:global-method-security jsr250-annotations="enabled" />