Spring Security(Third Edition)
上QQ阅读APP看书,第一时间看更新

Displaying custom user attributes

Now that CalendarUser is populated into Spring Security's authentication, we can update our UI to display the name of the current user rather than the email address. Update the header.html file with the following code:

    //src/main/resources/templates/fragments/header.html

<ul class="nav navbar-nav pull-right"
sec:authorize="isAuthenticated()">
<li id="greeting">
<p class="navbar-text">Welcome <p class="navbar-text"
th:text="${#authentication.getPrincipal().getName()}">
User</p>
</p>
</li>

Internally, the "${#authentication.getPrincipal().getName()}" tag attribute executes the following code. Observe that the highlighted values correlate to the property attribute of the authentication tag we specified in the header.html file:

    SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
CalendarUser user = (CalendarUser) authentication.getPrincipal();
String firstAndLastName = user.getName();

Restart the application, visit http://localhost:8080/, and log in to view the updates. Instead of seeing the current user's email, you should now see their first and last names.

Your code should now look like chapter03.04-calendar.