根据我的理解,有许多不同的方法可以在 Spring Security 中检索经过身份验证的用户名。
我目前通过将 Principal
作为 Controller 方法参数来获取用户名:
@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView displayHomePage(ModelAndView modelAndView, Principal principal) {
modelAndView.addObject("email", principal.getName());
// Render template located at src/main/resources/templates/dashboard.html
modelAndView.setViewName("dashboard");
return modelAndView;
}
Spring Security 是否为我提供了一种将用户对象存储到 session 中以便可以通过任何 Controller 方法轻松检索它的简单方法?
我想避免每次都执行数据库查找:
// Lookup user in database by e-mail
User user = userService.findUserByEmail(principal.getName());
我正在使用 Spring Security 4.2。
最佳答案
Spring Security 为您提供了一个静态方法,可以快速轻松地访问:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
或者
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
也许您想在基本抽象类中执行此操作
public abstract class BaseController {
protected User getCurrentUser() {
return (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
...
public YourController extends BaseController {
...
}
更新
如果您想在 session 中存储当前经过身份验证的用户,那么您只需按照@gkatzioura 的建议第一次存储在一个对象中。
@Component
@Scope("session")
public class MySessionInfo {
private User user;
protected User getCurrentUser() {
if (user == null) {
user = userService.findUserByEmail(SecurityContextHolder.getContext().getAuthentication().getPrincipal().getName());
}
return user;
}
}
你可以像这样在你的 Controller 中注入(inject)这个bean
@Autowired
private MySessionInfo mySessionInfo;
您必须注意用户未登录的情况,但这是另一个问题。
关于java - 将用户对象存储在与 Spring Security 的 session 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42836232/