Search code examples
javaannotationsspring-security

@RolesAllowed doesn't work


I searched for the answer, but didn't find it. If I add <intercept-url pattern="/test*" access="ROLE_USER" /> inside the <form-login> of my spring-security.xml, everything works predictably. But if I want @RolesAllowed("ROLE_ADMIN") to act for the method:

@RolesAllowed("ROLE_ADMIN")
@RequestMapping(value="/test", method = RequestMethod.GET)
public String test() {
    return "test";
}        

And if spring-security.xml looks like this (jsr250-annotations are enabled):

<http auto-config="true">
    <form-login login-page="/login.html" 
                default-target-url="/welcome.html"
                authentication-failure-url="/loginfailed.html" />
    <logout logout-success-url="/logout.html" />
</http>          

<authentication-manager>
  <authentication-provider>
        <user-service>
                <user name="john" password="doe" authorities="ROLE_ADMIN" />
                <user name="jane" password="doe" authorities="ROLE_USER" />
        </user-service>
  </authentication-provider>
</authentication-manager>

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

Well, in this case both John and Jane can access the test page. I think I missed something basic, the help would be appreciated.


Solution

  • If you change @RolesAllowed to @PreAuthorize("hasAuthority('ROLE_ADMIN')") and define global-method-security with pre-post-annotations="enabled" attribute, does it work?

    Also, I suppose that it's not working because you define global-method-security and other configuration in servlet config instead of application context.

    See similar post: https://stackoverflow.com/a/2525048/352708