简体   繁体   中英

How can I access data of a logged in user in Java spring?

So I have Users and Some data of those users. I want that logged in user can access only to his data. So If two users are logged in they access only to their data.

Is that feasibile with SessionRegistry? but how should be the API calls?

When user logs in I put this in the controller:

    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                                                                    user.getMail(), 
                                                                    user.getPassword(), 
                                                                    userDetails.getAuthorities()));

Spring manages user information in SecurityContextHolder. So, you can access user information anytime from the securityContextHolder. This is how it is done:

Users user = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

user will contain necessary information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM