我对 Spring 比较陌生和 Spring 安全性。
我正在尝试编写一个程序,我需要使用 Spring 安全性在服务器端对用户进行身份验证,
我想出了以下内容:
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
throws AuthenticationException
{
System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
}
@Override
protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
{
System.out.println("Method invoked : retrieveUser");
//so far so good, i can authenticate user here, and throw exception if not authenticated!!
//THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
}
}
我的用例是,当用户通过身份验证时,我需要放置如下属性:
session.setAttribute("userObject", myUserObject);
myUserObject 是某个类的对象,我可以跨多个用户请求在整个服务器代码中访问它。
最佳答案
你的 friend 是org.springframework.web.context.request.RequestContextHolder
// example usage
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
这将由标准 spring mvc 调度 servlet 填充,但如果您使用不同的 Web 框架,您可以在 中添加
来管理持有者。org.springframework.web.filter.RequestContextFilter
作为过滤器>web.xml
编辑:作为一个附带问题,您实际上想做什么,我不确定您是否需要访问 retieveUser 中的
方法。 Spring security 会以任何方式将 UserDetails 对象放入 session 中。可以通过访问 HttpSession
UserDetailsService
的 SecurityContextHolder
来检索它:
public static UserDetails currentUserDetails(){
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
return principal instanceof UserDetails ? (UserDetails) principal : null;
}
return null;
}
关于spring - 如何在 Spring 中获取 Session 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1629211/