为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

忽然笑 2021-09-03 13:53:33
在我的 spring boot 应用程序中,在我的 rest 控制器中,我成功地注入了一个实例Authentication来获取会话的用户信息。但是,在所有这些控制器中,我目前调用这样的辅助方法:@GetMappingpublic 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`}如何减少此代码重复?
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

您可以按如下方式创建一个实用程序类,然后您可以UserUtility.getUsername()在任何需要的地方使用它。


public class UserUtility {


    public static String getUsername(){

        if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {

            return SecurityContextHolder.getContext().getAuthentication().getPrincipal());

        }

        return null;

    }

}


查看完整回答
反对 回复 2021-09-03
  • 1 回答
  • 0 关注
  • 167 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信