@AuthenticationPrincipal 注释有什么意义?

2 java spring spring-security

据我了解,此注释用于在控制器中获取经过身份验证的用户。但我可以通过以下代码获得没有它的用​​户:

@GetMapping("/example")
public String currentUserName(Authentication authentication) { 
    return authentication.getName(); 
}
Run Code Online (Sandbox Code Playgroud)

如果您能告诉我它有什么用或分享一些文档,我将不胜感激,因为我找不到。我非常感谢你的帮助!

Mar*_*gio 6

此注释用于将 a 解析Principal为您的方法参数,更具体地说,是 a Authentication#getPrincipal()。例如,如果您有一个自定义UserDetails实现,例如CurrentUser implements UserDetails,由您返回,UserDetailsService您可以将其直接解析到您的方法中:

@GetMapping("/example")
public String currentCustomProperty(@AuthenticationPrincipal CurrentUser currentUser) { 
    return currentUser.getCustomProperty(); 
}
Run Code Online (Sandbox Code Playgroud)

否则,您需要执行以下操作:

@GetMapping("/example")
public String currentCustomProperty(Authentication authentication) {
    CurrentUser currentUser = (CurrentUser) authentication.getPrincipal();
    return currentUser.getCustomProperty(); 
}
Run Code Online (Sandbox Code Playgroud)

此外,它还有助于将 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(); 
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以应用SpEL注释并自定义它将返回的内容。

Spring Security 参考中有更多详细信息。