SpringSecurity6 | 获取登录用户的认证信息
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
在Spring Security 6中,你可以通过SecurityContextHolder
来获取当前登录用户的认证信息。以下是一个简单的例子:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityUtils {
public static Authentication getCurrentAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public static Object getPrincipal() {
Authentication authentication = getCurrentAuthentication();
return authentication == null ? null : authentication.getPrincipal();
}
// 如果Principal是UserDetails类型,可以进一步获取用户的详细信息
public static String getCurrentUsername() {
Object principal = getPrincipal();
return principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : null;
}
}
使用SecurityUtils
类中的方法可以获取当前登录用户的认证信息。例如,获取当前用户名:
String currentUsername = SecurityUtils.getCurrentUsername();
请确保在一个有Spring Security上下文的环境中调用这些方法,通常是在控制器、服务或过滤器中。
评论已关闭