Can Spring Security use @PreAuthorize
on Spring controllers methods?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
First you need to add this annotation in your WebSecurityConfig to enable @Pre and @Post annotations.
You can also check roles/authorities as follows
equivalent to
You can also check multiple roles/authorities as follows
There is already a reply regarding how to make it work by changing xml configuration; however, if you are working with code-based configuration, you can achieve the same by placing the following annotation over your
@Configuration
class:Yes, it works fine.
You need
<security:global-method-security pre-post-annotations="enabled" />
in...-servlet.xml
. It also requires CGLIB proxies, so either your controllers shouldn't have interfaces, or you should useproxy-target-class = true
.To Extend the answer provided by Andy, you can use:
to check the specific role.
See Spring Security FAQ (emphasis mine).
If you apply pointcuts to service layer you only need to set
<global-method-security>
in your app's security context.It's over two years since this question was asked but because of problems I had today I'd rather discourage using
@Secured
,@PreAuthorize
, etc. on@Controller
s.What didn't work for me was
@Validated
combined with@Secured
controller:Validator simply does not fire (Spring MVC 4.1.2, Spring Security 3.2.5) and no checks are performed.
Similar problems are caused by CGLIB proxies used by Spring (when there is no interface implemented by a class, Spring creates CGLIB proxy; if the class implements any interface then JDK Proxy is generated - documentation, well explained here and here).
As mentioned in the answers that I linked above, is't better to use Spring Security annotations on service layer that usually implements interfaces (so JDK Proxies are used) as this does not lead to such problems.
If you want to secure web controllers, the better idea is to use
<http>
and<intercept-url />
that are bound to specific urls rather than methods in controllers and work pretty well. In my case: