1

I am using Spring security + JPA + custom UserDetailsService. It seems like I can only store

String username, String password, boolean enabled, boolean accountNonExpired,
            boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities

In the User object. What should I do if I need to sore my custom User object in session after login. I want to save FIRST, LAST, Company and... Thanks!

topcan5
  • 1,511
  • 8
  • 30
  • 54

2 Answers2

3

You could define your own user model, and add all your preferred attributes to it.then Wrap it in your UserDetails Implementation, for example

public class UserModel {
   private username;
   private password;
   private firstname;
   private lastname;
   .
   .
   .
   etc
}

public class MyUserDetails implements UserDetails {

  private UserModel user;

  public UserModel getUser(){
    return user;
  }

  @Override
  public String getUsername(){
    return user.getUsername();
  }

  @Override
  public String getPassword(){
    return user.getPassword();
  }

}

And whenever you need to access your UserModel specific attributes, use the getUser() method and access your specific fields directly

MyUserDetails myUserDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

UserModel user = myUserDetails.getUser();

String firstname = user.getFirstname();

The good point of such an implementation is that you separate the security UserDetails implementation from your own User implementation which could be for example a managed entity by any ORM framework like Hibernate

fujy
  • 5,168
  • 5
  • 31
  • 50
  • May I ask what is this userDetails there for ? When would I want to use the userDetailsService and its userDetails ? What use case ? In which scenario ? I have implemented a fully working basic authentication for my REST application and wonder if/how/why I should add the userDetails in the mix. – Stephane Nov 26 '14 at 12:02
  • I think I got an answer to my question. I implemented a custom UserDetailsServiceImpl extending UserDetailsService with a custom UserDetailsWrapper extending UserDetails and using it in the security configuration with a http.userDetailsService(userDetailsService); This allows for my user state to be considered before granting access. For example. if the user lacks a role then he is denied authorization. – Stephane Nov 26 '14 at 16:29
0

There is a few great tutorials out there but if you want short cut with github example check out this question.

Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService

It also has a github rep you can access to get example code, it was done in collaboration with Sprin Sec dev lead.

Community
  • 1
  • 1
Aeseir
  • 7,754
  • 10
  • 58
  • 107