- 代码案例
@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;
}
}
- 测试结果