John Doe
John Doe

Reputation: 9764

Retrieving unique user data in Spring Security

I have a table of items, user should be able to choose some of them, then these items are put in the other table (in the second table they are associated with the user who chose the items). I could associate items and users with a help of usernames, but I suppose it wouldn't be great. I wonder, what is a good way to do that. I know there is an easy way to retrieve the username (<sec:authentication property="principal.username"/>), but today I learnt there is no such a way for an id. What is a good way to solve this problem? Should I implement UserDetails to have an opportunity to get each id? Is there any good example of this implementation? I use Hibernate to communicate with the database. Is there any other way of the identification (compound key consisted of values that are easy to retrieve or something like that)? Thanks in advance.

Upvotes: 0

Views: 486

Answers (1)

Arnaud Gourlay
Arnaud Gourlay

Reputation: 4666

Yes you have to implement your own UserDetail which will have an id attribute.

You'll then fill in this object during authentication in your implementation of UserDetailService.

For example:

@Service("CustomUserDetailService")
public class CustomUserDetailService implements UserDetailsService{

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException {
        User user = userDao.loadByName(name);
        CustomUserDetail customUserDetail = new CustomUserDetail();
        customUserDetail.setId(user.getId());
        customUserDetail.setPassword(user.getPassword());
        return customUserDetail ;
    }

After that you can retrieve anything from your principal :

<sec:authentication property="principal.id"/>

Upvotes: 2

Related Questions