[英]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`
}
如何减少此代码重复?
您可以按如下方式创建实用程序类,然后您可以像使用UserUtility.getUsername()
一样使用它。
public class UserUtility {
public static String getUsername(){
if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
return SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.