我正在尝试通过以下方式在服务类中找回当前经过身份验证的用户:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但是它返回一个String用户名而不是一个用户对象。
我应该怎么做才能拥有用户对象?
答案 0 :(得分:0)
有关如何使用@AuthenticationPrincipal
在Controller中获取经过身份验证的用户的示例:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping
public void getUser(@AuthenticationPrincipal User activeUser) {
System.out.println("user name is "+activeUser.getUsername());
}
}