sec:authentication与sec:authentication property获取用户名的差异及响应时间对比
sec:authentication="name" and sec:authentication property="principal.username" Great question! Let's break down how these two Spring Security tag approaches retrieve the username, and their performance characteristics:
1. How They Retrieve the Username
sec:authentication="name"
This directly calls thegetName()method on theAuthenticationobject stored in Spring Security'sSecurityContextHolder. By default, for both LDAP and database authentication, thisnameproperty maps to the user's login identifier—whether that's theusernamefield from your database user table, or the LDAP attribute (likeuidorsAMAccountName) used for authentication.sec:authentication property="principal.username"
Here, we first access theprincipalattribute of theAuthenticationobject. Theprincipalis typically your customUserDetailsimplementation (for database auth) or anLdapUserDetailsobject (for LDAP auth). Theusernamepart then fetches theusernameproperty from that principal object.In most default setups, the value returned by
principal.usernameis identical toAuthentication.getName()—because theUserDetails.getUsername()method usually returns the same login identifier that populatesAuthentication.name. However, if you've customized yourUserDetails(e.g., makinggetName()return a user ID instead of the login name), these two values could differ.
2. Performance & Response Time
The short answer: there's no meaningful performance difference between the two.
Both approaches read data directly from the Authentication object, which is stored in memory (in the user's session) after successful authentication. Neither makes an additional call to your LDAP server or database—so no extra network/disk IO is involved.
If we're splitting hairs, sec:authentication="name" has a tiny theoretical edge: it's a direct method call, whereas the other requires two nested property accesses (get principal, then get username). But this difference is so minuscule that it will never be noticeable in real-world applications.
Final Recommendation
Use whichever approach aligns better with your code's readability and business logic:
- If you just need the login identifier that the user authenticated with, either works.
- If you have a custom
UserDetailswhereprincipal.usernamemight differ fromAuthentication.name, choose the one that gives you the value you need.
内容的提问来源于stack exchange,提问作者Mike

