Securing controller method with @RolesAllowed and @PreAuthorize

前端 未结 2 1177
感动是毒
感动是毒 2020-12-11 23:38

I\'ve been banging my head over this one for a while now. I\'ve done everything I could in order to find an appropriate solution and followed a lot of Stackoverflow examples

相关标签:
2条回答
  • 2020-12-11 23:48

    Two things I noticed (as mentioned on this thread):

    1. prePostEnabled in the annotation to enable Pre/Post annotations
    2. use of CGLib proxies (Serge mentioned this too)

    Does your @EnableGlobalMethodSecurity have those two attributes?

    @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
    
    0 讨论(0)
  • 2020-12-11 23:59

    The symptoms you describe make me think to a problem of proxying. Annotations works fine on service layer, because services generally implements interfaces, and Spring can easily use a JDK proxy to put the AOP authorizations.

    But controllers generally do not implement interfaces. That's the reason why PreAuthorize annotation are more frequently used in service layer. IMHO, you'd better try to use URL pattern based authorization instead of PreAuthorize annotations on controller. The alternative would be to use target class proxying with CGLIB.

    To use PreAuthorize and JSR-250 annotations, you must

    • annotate you spring security configuration class with :

      @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true)
      
    • if you use anywhere else in your application Spring AOP with JDK proxies, make all controller classes in which you want to use method security implement interfaces declaring all protected methods

    • if you use anywhere else in your application Spring AOP with CGLIB proxies, add proxyTargetClass = true to @EnableGlobalMethodSecurity :

      @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true,
              proxyTargetClass = true)
      
    • if you want to use CGLIB proxies with Spring version under 3.2, add CGLIB library to your classpath (CGLIB classes are included in Spring 3.2+)

    • avoid mixing CGLIB and JDK proxying as it is not recommended by Spring documentation : Multiple sections are collapsed into a single unified auto-proxy creator at runtime, which applies the strongest proxy settings that any of the sections (typically from different XML bean definition files) specified. This also applies to the and elements. To be clear: using 'proxy-target-class="true"' on , or elements will force the use of CGLIB proxies for all three of them.

    But anyway, my advice is to try to move method security to service layer which normally already supports AOP.

    0 讨论(0)
提交回复
热议问题