如何在 Spring 中获取会话对象? [英] How do I get the Session Object in Spring?
问题描述
我对 Spring 和 Spring 安全性比较陌生.
I am relatively new to Spring and Spring security.
我试图编写一个程序,我需要在服务器端使用 Spring 安全性对用户进行身份验证,
I was attempting to write a program where I needed to authenticate a user at the server end using Spring security,
我想出了以下几点:
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
}
}
我的用例是当用户通过身份验证时,我需要放置一个属性,如:
My usecase is that when a user is authenticated, I need to place an attribute like:
session.setAttribute("userObject", myUserObject);
myUserObject 是某个类的对象,我可以跨多个用户请求在整个服务器代码中访问它.
myUserObject is an object of some class that I can access throughout my server code across multiple user requests.
推荐答案
你的朋友是 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
来管理持有者.
This will be populated by the standard spring mvc dispatch servlet, but if you are using a different web framework you have add org.springframework.web.filter.RequestContextFilter
as a filter in your web.xml
to manage the holder.
编辑:作为一个附带问题,您实际上要做什么,我不确定您是否需要访问 retieveUser 中的
方法.Spring security 会以任何方式将 UserDetails 对象放入会话中.可以通过访问 HttpSession
UserDetailsService
的 SecurityContextHolder
来检索它:
EDIT: just as a side issue what are you actually trying to do, I'm not sure you should need access to the HttpSession
in the retieveUser
method of a UserDetailsService
. Spring security will put the UserDetails object in the session for you any how. It can be retrieved by accessing the 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 中获取会话对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!