我有一个 spring-mvc 应用程序,当前有两个 channel - Web 应用程序和 REST 服务。两者都有用户的 http session ,我可以轻松地在我的服务类中获取“当前用户”。
现在我需要开发另一个 REST 服务,其中没有 http session ,并且当前用户依赖于请求参数。因此 Controller 将读取该请求参数并找到当前用户。
现在我需要: 1.修改我的服务层方法以接受当前用户作为参数 或者 2.只需修改从http session 获取当前用户的类即可。
我还需要创建审核日志,我将为此使用 Spring AOP。该方面也需要访问“当前用户”。所以选项#1 可能不适合我,我会选择#2。
对于选项 #2,我将创建一个拦截器,将当前用户放入 ThreadLocal 变量中。新 REST 服务的 Controller 将执行相同的操作,然后在我的服务层和审核日志方面,我可以从那里获取当前用户。
我以前没有做过这样的事情,想知道是否有更好的方法。或者说这种方法会带来什么样的问题。
我将不胜感激任何评论和想法。
盎司
以下是我当前获取当前用户的方式:
@Override
public User getCurrentUser()
{
Authentication currentUser = getAuthentication();
return userService.getByLoginName(currentUser.getName());
}
protected Authentication getAuthentication()
{
return SecurityContextHolder.getContext().getAuthentication();
}
最佳答案
我认为满足您需要的一个简单方法是为新的 REST Web 服务配置 servlet 过滤器,以使用从请求参数构建的 Authentication
对象填充 SecurityContextHolder
.
您可以阅读此内容:http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#d0e2171了解更多详情。
使用此解决方案,您无需修改代码即可检索当前用户。 (请注意,SecurityContextHolder
已经使用 ThreadLocal
来存储 SecurityContext
以及 Authentication
)
关于java - 将 "current user"保留在 threadlocal 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18226009/