简体   繁体   中英

What is the correct way to get the logged user via spring security (angularjs)

After success login, how I can retrieve the logged users in spring RestController ?

I use the below method/principle to get the logged user, but it retrieves anonymousUser instead of logged user.

Principal principal = SecurityContextHolder.getContext().getAuthentication();

or

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

You may get the logged in user name from Authentication object. To get the user object, you can then use the username retrieved from the authentication object.

Something like this should work:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User user = userService.findByUserName(name);

Or better, you can use Principal in your controller as an argument, and let the Spring pass the correct principal object. If the user not logged in, it would be null.

 public String hello(Principal principal ) {

  String name = principal.getName();
  User user = userService.findByUserName(name);

}

Ps: If you are getting anonymous authentication, then the user is not authenticated. SecurityContext returns anonymous authentication is the user is not logged in. `

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