Home > Back-end >  Spring Security Expression: "authenticated" vs. "isAuthenticated()"
Spring Security Expression: "authenticated" vs. "isAuthenticated()"

Time:10-11

According to the Spring Security docs, the expression to check whether a user is authenticated is isAuthenticated(). So we would do @PreAuthorize("isAuthenticated()"), for example.

However, according to the official example and confirmed by my own testing, @PreAuthorize("authenticated") also works.

Is it a Spring Security feature or perhaps simply a Java feature (e.g. authenticated is the field that backs the getter isAuthenticated() somewhere) that makes authenticated work as well?

CodePudding user response:

I have checked the source code in org.springframework.security.web.servletapi.Servlet3SecurityContextHolderAwareRequestWrapper:

private boolean isAuthenticated() {
    return getUserPrincipal() != null;
}

then look into getUserPrincipal():

@Override
public Principal getUserPrincipal() {
    Authentication auth = getAuthentication();
    if ((auth == null) || (auth.getPrincipal() == null)) {
        return null;
    }
    return auth;
}

then getAuthentication(). this is key point:

private Authentication getAuthentication() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();//!!!
    return (!this.trustResolver.isAnonymous(auth)) ? auth : null;
}

as it shows, authentication object is managed by SecurityContextHolder.

as for authenticated, I think it might be a singleton Java bean in spring bean container. it has the same value as:

authentication.isAuthenticated();

in org.springframework.security.core.Authentication

CodePudding user response:

The value of the @PreAuthorize is an SpEL , which according from the docs , it will evaluate against the root object SecurityExpressionRoot.

isAuthenticated() is the syntax to invoke isAuthenticated() on the SecurityExpressionRoot instance (see this) .

While authenticated is the syntax to access the properties of the SecurityExpressionRoot instance (see this). It will try to invoke the following public property or methods to evaluate the value :

  • authenticated property
  • getAuthenticated()
  • isAuthenticated() (Only if the evaluated value is boolean)
  • authenticated()

You could find such logic in the codes at here.

  • Related