Use ?. operator in principal id checks for security

162 views Asked by At

I have the below code change.

-    @PreAuthorize("isAuthenticated() and #employee.id == principal.id")
+    @PreAuthorize("#employee.id == principal?.id")

Here the developer makes changes as shown above. Are the two security checks same? So if I make sure that the principal exists and is not null, it is the same as making sure that the user is authenticated and the user is not anonymous?

I found the below from the spring security documentation

Table 15.1. Common built-in expressions

Expression Description

hasRole([role]) Returns true if the current principal has the specified role.
hasAnyRole([role1,role2])   Returns true if the current principal has any of the supplied roles (given as a comma-separated list of strings)
principal   Allows direct access to the principal object representing the current user
authentication  Allows direct access to the current Authentication object obtained from the SecurityContext
permitAll   Always evaluates to true
denyAll Always evaluates to false
isAnonymous()   Returns true if the current principal is an anonymous user
isRememberMe()  Returns true if the current principal is a remember-me user
isAuthenticated()   Returns true if the user is not anonymous
isFullyAuthenticated()  Returns true if the user is not an anonymous or a remember-me user
1

There are 1 answers

1
Paul John On BEST ANSWER

Yes, this would validate that there is a principal object available. As per the documentation - Authentication is a Principal.

    public interface Authentication extends Principal, Serializable {}