How can Spring retrieve information of the currently lo…
In Spring, you can use the Authentication object to obtain information about the current logged-in user. Simply call SecurityContextHolder.getContext().getAuthentication() to retrieve the Authentication object, and then use the getPrincipal() method to access the user’s information.
Here is a sample code:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class UserController {
public User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof User) {
return (User) authentication.getPrincipal();
} else {
// 用户未登录
return null;
}
}
}
In the example above, the getCurrentUser() method returns the object of the user currently logged in, or null if the user is not logged in.
It is important to note that the above code assumes user information is in the Principal object, and adjustments can be made accordingly if user information is stored elsewhere.