You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sec:authentication与sec:authentication property获取用户名的差异及响应时间对比

Differences Between 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 the getName() method on the Authentication object stored in Spring Security's SecurityContextHolder. By default, for both LDAP and database authentication, this name property maps to the user's login identifier—whether that's the username field from your database user table, or the LDAP attribute (like uid or sAMAccountName) used for authentication.

  • sec:authentication property="principal.username"
    Here, we first access the principal attribute of the Authentication object. The principal is typically your custom UserDetails implementation (for database auth) or an LdapUserDetails object (for LDAP auth). The username part then fetches the username property from that principal object.

    In most default setups, the value returned by principal.username is identical to Authentication.getName()—because the UserDetails.getUsername() method usually returns the same login identifier that populates Authentication.name. However, if you've customized your UserDetails (e.g., making getName() 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 UserDetails where principal.username might differ from Authentication.name, choose the one that gives you the value you need.

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:01:25