📜  如何在 Spring Boot 中找到登录用户? - Java (1)

📅  最后修改于: 2023-12-03 14:52:34.568000             🧑  作者: Mango

如何在 Spring Boot 中找到登录用户

在 Spring Boot 中,我们可以使用 Spring Security 来实现用户身份验证和授权管理。一旦我们的用户已登录,我们可能需要在应用程序中访问他们的信息。 下面是一些可能有用的方法来获取当前认证的用户。

1. 使用 SecurityContextHolder

Spring Security 提供了 SecurityContextHolder,它可以在任何地方访问当前用户。我们可以使用以下代码来获取当前认证的用户:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();

这将返回当前已认证的用户的用户名。

2. 使用 @AuthenticationPrincipal 注解

如果您想要直接注入已认证的用户,可以使用 @AuthenticationPrincipal 注解。这将使 Spring 自动将当前已认证的用户注入到您的控制器方法中:

@GetMapping("/hello")
public String hello(@AuthenticationPrincipal Principal user) {
    String username = user.getName();
    return "Hello, " + username;
}

这里的 user 参数将直接注入当前已认证的用户。请注意,此示例中的 Principal 类型将包含更多有关当前用户的信息。

3. 使用 HttpServletRequest

如果您需要在过滤器或 Servlet 中访问当前已认证的用户,则可以使用 HttpServletRequest。可以使用以下代码:

@GetMapping("/hello")
public String hello(HttpServletRequest request) {
    Principal principal = request.getUserPrincipal();
    String username = principal.getName();
    return "Hello, " + username;
}

这里的 request.getUserPrincipal() 将返回当前已认证的用户。请注意,此示例中的 Principal 类型将包含更多有关当前用户的信息。

总之,以上这些方法都可以让我们在 Spring Boot 中访问已认证的用户。可以根据需要选择最适合您应用程序的方法。