在Spring中如何获取Session对象?

98

我对 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是某个类的对象,我可以在整个服务器代码中通过多个用户请求进行访问。

8个回答

161

你的朋友在这里使用了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
}

如果您正在使用不同的Web框架,这将由标准Spring MVC分发servlet填充,但是您需要在web.xml中将org.springframework.web.filter.RequestContextFilter作为过滤器添加以管理持有者。

编辑:仅作为一个附带问题,您实际上要做什么?我不确定您是否需要在UserDetailsServiceretrieveUser方法中访问HttpSession。无论如何,Spring安全性将为您将UserDetails对象放入会话中。可以通过访问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;
}

1
@第一点: 我尝试使用RequestContextHolder,但出现了错误: 未找到绑定线程的请求:您是否正在引用...请使用RequestContextListener或RequestContextFilter公开当前请求。 我想我没有尝试过过滤器,我会尝试并告诉你它是否有效。@第二点: 实际上这是一个自定义对象,因此我不喜欢UserDetails如果可能,请查看我在类似主题上的其他问题: http://stackoverflow.com/questions/1629273/is-it-possible-to-send-more-data-in-form-based-authentication-in-spring - Salvin Francis
2
如果您没有使用调度servlet,则需要进行配置:RequestContextFilter。 - Gareth Davis
1
抱歉,我的错误...我从自己的项目中调整了代码,该项目使用getRequest,答案已更新。 - Gareth Davis
1
不,那看起来差不多正确...尝试在调试器中停止您的代码并检查RequestContextFilter是否在调用堆栈中。 - Gareth Davis
1
我发现RequestContextFilter对我没有作用,而RequestContextListener有用…<listener><listener-class>org.springframework.web.context.request.RequestContextListener</listener-class></listener> - Josh
显示剩余7条评论

37

既然你正在使用Spring,就坚持使用Spring,不要像其他帖子所述那样自己动手修改。

Spring手册中说:

为了安全起见,您不应直接与HttpSession交互。没有理由这样做-始终使用SecurityContextHolder。

访问session的建议最佳实践是:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}
关键在于Spring和Spring Security为你做了很多好事,例如防止会话固定攻击。这些功能假设你正在按照设计使用Spring框架。因此,在你的servlet中,使其具有上述示例中的上下文感知能力并访问会话。
如果您只需要将某些数据存储在会话范围内,请尝试创建一些会话范围的bean,如此示例,然后让自动连接完成魔法 :)。

6

我做了自己的工具集,非常方便。 :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC通用工具
 * 
 * @author 应卓(yingzhor@gmail.com)
 *
 */
public final class WebContextHolder {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}

4
在我的场景中,我已将HttpSession注入到CustomAuthenticationProvider类中,方法如下:
public class CustomAuthenticationProvider extends  AbstractUserDetailsAuthenticationProvider{

    @Autowired 
    private HttpSession httpSession;

    @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
        httpSession.setAttribute("userObject", myUserObject);
    }
}

4

当使用 HttpSessionLisener 销毁会话时,您仍然可以通过以下方式访问会话中的信息:

public void sessionDestroyed(HttpSessionEvent hse) {
    SecurityContextImpl sci = (SecurityContextImpl) hse.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    // be sure to check is not null since for users who just get into the home page but never get authenticated it will be
    if (sci != null) {
        UserDetails cud = (UserDetails) sci.getAuthentication().getPrincipal();
        // do whatever you need here with the UserDetails
    }
 }

或者您也可以在任何有HttpSession对象的地方访问信息,例如:

SecurityContextImpl sci = (SecurityContextImpl) session().getAttribute("SPRING_SECURITY_CONTEXT");

假设您有类似以下的东西:
HttpSession sesssion = ...; // can come from request.getSession(false);

3
我尝试了下面的代码,效果非常好。
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    /**
     * Created by jaime on 14/01/15.
     */

    @Controller
    public class obteinUserSession {
        @RequestMapping(value = "/loginds", method = RequestMethod.GET)
        public String UserSession(ModelMap modelMap) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName();
            modelMap.addAttribute("username", name);
            return "hellos " + name;
        }

4
请附上说明与您的代码。在这里仅仅把代码或链接扔给别人并不是一个真正的回答。 - Rémi

2
如果您只需要用户的详细信息,对于Spring版本4.x,您可以使用Spring提供的@AuthenticationPrincipal@EnableWebSecurity标签,如下所示。
安全配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   ...
}

控制器方法:

@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal User user) {
    ...
}

0
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
attr.getSessionId();

5
能否在你的回答中添加一些额外信息,说明这种解决方案与其他现有答案相比如何解决问题? - slfan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接