Maff
Maff

Reputation: 1032

Spring Security User Information

I have a quick question in regards to Spring Security and obtaining further information(Instance variables) for the current logged in User. By default, without the necessity to write your own UserDetailsService Is there a way to obtain any of the other instance variables that are defined within my User bean? As you're probably aware by placing the following code in one of my controllers I have access to the following fields such as: Username, password, enabled, authorities, etc.

UserDetails userDetails = 
               (UserDetails) ((Authentication)principal).getPrincipal();

I would like to obtain other information such as the following instance variables I have defined in my User object (ID, NAME, EMAIL, ETC):

 // Instance Variables
 private int id;
 private String name;
 private String email;
 private String username; // I can already obtain this
 private String password; // I can already obtain this

Could you please provide some further assistance in way which I can get more information?

Upvotes: 0

Views: 138

Answers (2)

Sridhar Chidurala
Sridhar Chidurala

Reputation: 576

Your User Object must implement UserDetails interface. When you get a reference to it cast it correctly so you can access getter methods.

Let's say your user object is like

public class MyUser implements UserDetails{
     private int id;
     private String name;
     private String email;
     private String username;

}

After succesful login you would store an instance of MyUser in as the principal.

Then

     MyUser userDetails = 
           (MyUser) ((Authentication)principal).getPrincipal();
     String name = userDetails.getName();

Upvotes: 1

Jeevan Patil
Jeevan Patil

Reputation: 6089

As you are aware that you can get the UserDetails object using following code.

UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Using UserDetails object, you can get username, password and authorities. Now you want ID and email of that user. In this case, once your user is authenticated, you can have a database query which will return you user object by username.

Upvotes: 1

Related Questions