Why use "#post" instead of "post" in hasPermission check in Spring Security

394 Views Asked by At

I am new to spring security. While analyzing the below code change, I could not comprehend why "#post" is used instead of "post" ? Why is the word "post" prefixed with a "#"? post is an object.

@PreAuthorize("hasPermission(#post, 'MANAGER') or hasRole('ROLE_MODERATOR')")
+   @PreAuthorize("hasPermission(#post, 'write') or hasRole('ROLE_MODERATOR')")
    public void updateFullyPost(Post post) throws AppException;

I referred to spring security documentation and found the below.

hasPermission(Object target, Object permission) Returns true if the user has access to the provided target for the given permission. For example, hasPermission(domainObject, 'read')

The first argument is supposed to be a target object.

Could someone provide some pointers? Appreciate it. Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

In Spring Expression Language (SpEL):

Variables can be referenced in the expression using the syntax #variableName.

When calling method with annotation like @PreAuthorize, the method arguments are passed to SpEL as variables.

If leaving out the #, Spring will look for a property in the root object, in this case a SecurityExpressionRoot. It is where you find the hasPermission method.