[英]Spring security: get Authenticated user in method
I am trying to get back the current authenticated user in a service class with:我正在尝试在服务 class 中取回当前经过身份验证的用户:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
but it returns me a String username instead of a user object.但它返回给我一个字符串用户名而不是用户 object。
What should I do to have the user object?我应该怎么做才能拥有用户 object?
An example of how to get the authenticated user in Controller using @AuthenticationPrincipal
:如何使用@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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.