所以我想弄清楚是否有一种更简单,更直接的方式来获取当前登录用户的CustomUser对象。
我有自定义UserServiceImplementation并使用自定义用户对象。
阅读我注意到@AuthenticationPrincipal的使用,但我似乎无法得到任何有效的例子。此外,它依赖于@EnableWebMVCSecurity,它为我正在使用的当前版本的spring security(4.x.x)折旧。
我是否正在寻找能够实现目标的正确功能,还是应该关注完全不同的事情?
我当前代码的示例,我被迫获取登录用户的当前用户对象,以便能够实现进一步处理。
@RequestMapping(value = "/map", method = method = RequestMethod.POST)
public String processMap(@Valid MapProc mapObject) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = userInterface.findByLogin(((UserDetails) principal).getUsername());
// rest of code
return "map/processed";
}
答案 0 :(得分:0)
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userName= auth.getName();
答案 1 :(得分:0)
在Session中始终是UserDetailsService持久性的UserDetails对象。如果您有自己的实现,则返回您自己的用户对象,您可以通过以下方式获取它:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof User) {
//Your Code here
}