
[英]What is @AuthenticationPrincipal alternative for micronaut?
[英]What is the point of @AuthenticationPrincipal annotation?
据我了解,此注释用于在 Controller 中获取经过身份验证的用户。 但是我可以通过以下代码获得没有它的用户:
@GetMapping("/example")
public String currentUserName(Authentication authentication) {
return authentication.getName();
}
如果您能告诉我它的用途或分享一些文档,我将不胜感激,因为我找不到。 我非常感谢您的帮助!
此注释用于将Principal
解析为您的方法参数,更具体地说,是Authentication#getPrincipal()
。 例如,如果您有一个自定义UserDetails
实现,如CurrentUser implements UserDetails
,它由您的UserDetailsService
返回,您可以将其直接解析到您的方法中:
@GetMapping("/example")
public String currentCustomProperty(@AuthenticationPrincipal CurrentUser currentUser) {
return currentUser.getCustomProperty();
}
否则,您需要执行以下操作:
@GetMapping("/example")
public String currentCustomProperty(Authentication authentication) {
CurrentUser currentUser = (CurrentUser) authentication.getPrincipal();
return currentUser.getCustomProperty();
}
此外,它有助于将您的 Spring MVC 层与 Spring Security 的实现分离:
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}
@GetMapping("/example")
public String currentCustomProperty(@CurrentUser CurrentUser currentUser) {
return currentUser.getCustomProperty();
}
您甚至可以将SpEL
应用于注释并自定义它将返回的内容。
Spring Security 参考中有更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.