算是很全各种方式啦,就看哪种最适合在项目使用了
第一种方式,从 Authentication 获取
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
String getUserInfo(
Authentication authentication
) {
return authentication.getName();
}
}
设置登录态的时候,填充到 principal 的是 MimeayDetail 类,在使用的时候可以将 authentication.getPrincipal() 转成 MimeayDetail
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
MimeayDetail getUserInfo(
Authentication authentication
) {
MimeayDetail mimeayDetail = (MimeayDetail) authentication.getPrincipal();
return mimeayDetail;
}
}
第二种方式, 从 Principal 获取
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
String getUserInfo(
Principal principal
) {
return principal.getName();
}
}
第三种方式, 从自定义的用户类取
取整个自定义用户实体
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
MimeayDetail getUserInfo(
@AuthenticationPrincipal MimeayDetail mimeayDetail
) {
return mimeayDetail;
}
}
自定义用户类内容
{
"id": 1,
"nickname": "chenxiaochi"
}
取自定义用户实体某个字段
public class IndexController {
@GetMapping("/no-public/user-info")
String getUserInfo(
@AuthenticationPrincipal(expression = "nickname") String nickname
) {
return nickname;
}
}
查阅文档的时候,有一个做法也还不错,不想在程序中使用 AuthenticationPrincipal, 则可以在包装一层
@Target({ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface MimeayUserDetail {
}
使用的时候就变成这样
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
MimeayDetail getUserInfo(
@MimeayUserDetail MimeayDetail mimeayDetail
) {
return mimeayDetail;
}
}
其他方式
从 CurrentSecurityContext 获取
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
String getUserInfo(
@CurrentSecurityContext(expression = "authentication") Authentication authentication
) {
return authentication.getName();
}
}
从 SecurityContextHolder 获取
@RestController
public class IndexController {
@GetMapping("/no-public/user-info")
MimeayDetail getUserInfo(
) {
MimeayDetail mimeayDetail = (MimeayDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return mimeayDetail;
}
}
可运行 demo
https://github.com/imeay/mimeay_security
参考文章
https://www.springcloud.io/post/2022-02/spring-security-get-current-user/#gsc.tab=0
https://www.baeldung.com/get-user-in-spring-security