Spring Security:在方法中获取经过身份验证的用户

时间:2020-06-01 20:12:09

标签: java spring spring-security

我正在尝试通过以下方式在服务类中找回当前经过身份验证的用户:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

但是它返回一个String用户名而不是一个用户对象。

我应该怎么做才能拥有用户对象?

1 个答案:

答案 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());
    }
}
相关问题