展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

获取用户信息

  • 代码案例
@RestController
@RequestMapping("/user")
public class WebController {

    @RequestMapping({"/test1"})
    public String index() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = "";
        if(principal != null && principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails)principal;
            username = userDetails.getUsername();
        }
        return username;
    }

    @RequestMapping("/test2")
    @ResponseBody
    public Object userInfo(Authentication authentication) {
        return authentication.getPrincipal();
    }

    @RequestMapping("/test3")
    @ResponseBody
    public Object userInfo2(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

}
  • 测试结果

posted @ 2022-06-24 15:35  DogLeftover  阅读(17)  评论(0编辑  收藏  举报