如何注入用户名(不是身份验证)?

How to inject the username (not the Authentication)?

在我的 spring 引导应用程序中,在我的其余控制器中,我成功地注入了 Authentication 的实例以获取会话的用户信息。

但是,在所有这些控制器中,我目前调用这样的辅助方法:

@GetMapping
public List<String> getData(Authentication auth) {
    String username = auth.getName().replaceFirst(".*?\\", ""); // to remove windows domain name
    // the rest of these methods only use variable `username`, never `auth`
}

如何减少代码重复?

您可以创建一个实用程序 class 如下所示,然后您可以像这样 UserUtility.getUsername() 在任何需要的地方使用它。

public class UserUtility {

    public static String getUsername(){
        if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
            return SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        }
        return null;
    }
}