Spring Security. display username on each page

I want to save user information after logging in and display my login and username on each page (using jsp). How can I access in my jsp views a bean session that will store information about the user who is logged in?

+4
source share
3 answers

use tag

This tag allows you to access the current Authentication Object stored in a security context. It renders the property of the object directly in the JSP. So, for example, if the main authentication property is an instance of Spring Security UserDetails, then using <sec: authentication property = "main.username" /> we will display the name of the current user.

Of course, there is no need to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the presentation. You can access the authentication object in your MVC (by calling SecurityContextHolder.getContext (). GetAuthentication ()) and add the data directly to your model for rendering by type.

+10
source

I assume you are using spring security. After a successful login, put the UserDetails object in the session as follows (usually this is the controller that you would redirect to if the login was successful)

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, for example:

 <span class="message">Welcome ${userDetails.username}</span> 
+3
source

This is almost a duplicate. When using Spring Security, what is the right way to get current user information (e.g. SecurityContext) in a bean? Validated Spring Method

 final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); 

but the related discussion has alternatives.

+1
source

All Articles