Skip to content

How does Spring Security check @PreAuthorize and how does it call hasAuthority() method?

When I use Spring Security I found @PreAuthorize("hasAuthority('authority_name')")

How does Spring Security check @PreAuthorize and how does it call hasAuthority() method?

Answer

Spring Security (@PreAuthorize) use a SPEL (Spring Expression Language) expression that invoke an Object returned from a MethodSecurityExpressionHandler.

The default implementation for MethodSecurityExpressionHandler is DefaultMethodSecurityExpressionHandler. It create an instance of MethodSecurityExpressionRoot and then process the SPEL expression on it.

MethodSecurityExpressionRoot extends SecurityExpressionRoot, and that provides the hasAuthority method, that bekome invoked when you use it in a @PreAuthorize Annotation.