spring security. display user name on every page
I want to store user information after logging in and to display my l开发者_StackOverflow中文版ogin and username on every page (using jsp). How can I get access in my jsp views to the session bean that would store information of the user that is logged in?
use the authentication tag
This tag allows access to the current Authentication object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the principal property of the Authentication is an instance of Spring Security's UserDetails object, then using <sec:authentication property="principal.username" /> will render the name of the current user.
Of course, it isn't necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. You can access the Authentication object in your MVC controller (by calling SecurityContextHolder.getContext().getAuthentication()) and add the data directly to your model for rendering by the view.
I'm assuming you are using spring security. After successful login put the UserDetails object in the session like so (This is usually the controller where you would forward if login was successfull)
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
HttpSession session = request.getSession(true); //create a new session
// put the UserDetails object here.
session.setAttribute("userDetails", principal);
In your JSP you can access the UserDetails object, like so:
<span class="message">Welcome ${userDetails.username}</span>
This is a near duplicate to When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?. The Spring endorsed method is
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
but the linked discussion has alternatives.
精彩评论