开发者

Spring Security hasRole('ROLE_ADMIN') in config and @PreAuthorize("permitAll") not working?

I'm trying to lock down my entire app except a particular URL/me开发者_开发技巧thod.

Here's my applicationContext-security.xml:

<global-method-security pre-post-annotations="enabled"/>
<http use-expressions="true">
    <http-basic/>
    <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
    <logout logout-success-url="/products" />
</http>

Here's the class with its annotation:

@RooWebScaffold(path = "products", formBackingObject = Product.class)
@RequestMapping("/products")
@Controller

public class ProductController {

    @RequestMapping(value="/json", headers = "Accept=application/json")
    @ResponseBody
    @PreAuthorize("permitAll")
    public String listJson() {
        return Product.toJsonArray(Product.findAllProducts());
    }

}

However, it's not working as expected.

If I swap the conditions around and have permitAll in the config and the hasRole() in the annotation it works as expected - but I'm trying to achieve the reverse.

Any advice would be greatly appreciated!


If you are using XML Configuration don't forget to add the following attribute:

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

If you are using Java Configuration don't forget to add the following annotation:

       @EnableGlobalMethodSecurity(prePostEnabled = true)


It is almost similar to question spring security 3 - Setting up a customized login, if you restrict all access (pattern /**) to role_admin then how the permitAll on /product would work? Solution would be to provide IS_AUTHENTICATED_ANONYMOUSLY access on /product.


From @PreAuthorize and intercept-url priority :

<intercept-url> ... takes precedence over (@PreAuthorize) annotations. [, since] <intercept-url> works at URL level and annotations at method level.


So the solution to your problem (apart from @PreAuthorize annotations) must be addressed in your security config.

You have to declare /prodcuts/json intercept url with permitAll (or anonymous..) before /** intercept url pattern like:

...
<intercept-url pattern="/products/json" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
...

From https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#nsa-intercept-url:

When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. So the most specific patterns should come first and the most general should come last.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜