如何在Spring中获取会话对象?
我对Spring和security比较陌生 我正试图编写一个程序,需要在服务器端使用Spring security对用户进行身份验证 我得出了以下结论:如何在Spring中获取会话对象?,spring,spring-mvc,spring-security,Spring,Spring Mvc,Spring Security,我对Spring和security比较陌生 我正试图编写一个程序,需要在服务器端使用Spring security对用户进行身份验证 我得出了以下结论: public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{ @Override protected void additionalAuthenticationChecks(UserDetails user
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是某个类的对象,我可以在服务器代码中跨多个用户请求访问它。您的朋友在这里
这将由标准的spring mvc dispatch servlet填充,但如果您使用的是不同的web框架,则需要在web.xml
中添加org.springframework.web.filter.RequestContextFilter
作为过滤器来管理持有者
编辑:作为一个次要问题,您实际上想做什么,我不确定您是否需要访问UserDetailsService
的retieveUser
方法中的HttpSession
。Spring security将以任何方式将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;
}
既然你使用的是Spring,就要坚持使用Spring,不要像其他帖子一样自己动手 报告说: 为了安全起见,您不应该直接与HttpSession交互 目的。根本没有理由这样做-始终使用 而是SecurityContextHolder 访问会议的建议最佳做法是:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
这里的关键是Spring和Spring安全性为您提供了各种各样的功能,比如会话固定预防。这些东西假设您正在使用Spring框架,因为它是为使用而设计的。因此,在servlet中,使其具有上下文意识,并像上面的示例那样访问会话
如果您只需要在会话作用域中隐藏一些数据,请尝试创建一些会话作用域的bean,并让autowire发挥其魔力。:) 实际上,即使会话正在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);
我自己做的。它很方便。:)
package samples.utils;
导入java.util.array;
导入java.util.Collection;
导入java.util.Locale;
导入javax.servlet.ServletContext;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpSession;
导入javax.sql.DataSource;
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
导入org.springframework.beans.factory.NoSuchBeanDefinitionException;
导入org.springframework.beans.factory.nouniquebeandDefinitionException;
导入org.springframework.context.ApplicationContext;
导入org.springframework.context.ApplicationEventPublisher;
导入org.springframework.context.MessageSource;
导入org.springframework.core.convert.ConversionService;
导入org.springframework.core.io.ResourceLoader;
导入org.springframework.core.io.support.ResourcePatternResolver;
导入org.springframework.ui.context.Theme;
导入org.springframework.util.ClassUtils;
导入org.springframework.web.context.request.RequestContextHolder;
导入org.springframework.web.context.request.ServletRequestAttributes;
导入org.springframework.web.context.support.webApplicationContext;
导入org.springframework.web.servlet.LocaleResolver;
导入org.springframework.web.servlet.ThemeResolver;
导入org.springframework.web.servlet.support.RequestContextUtils;
/**
*SpringMVC通用工具
*
*@作者应卓(yingzhor@gmail.com)
*
*/
公开期末课程WebContextHolder{
私有静态最终记录器Logger=LoggerFactory.getLogger(WebContextHolder.class);
私有静态WebContextHolder实例=新WebContextHolder();
公共WebContextHolder get(){
返回实例;
}
私有WebContextHolder(){
超级();
}
// --------------------------------------------------------------------------------------------------------------
公共HttpServletRequest getRequest(){
ServletRequestAttributes=(ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
返回attributes.getRequest();
}
公共HttpSession getSession(){
返回getSession(true);
}
公共HttpSession getSession(布尔创建){
返回getRequest().getSession(创建);
}
公共字符串getSessionId(){
返回getSession().getId();
}
公共ServletContext getServletContext(){
返回getSession().getServletContext();//servlet2.3
}
公共语言环境getLocale(){
返回RequestContextUtils.getLocale(getRequest());
}
公共主题{
返回RequestContextUtils.getTheme(getRequest());
}
公共应用程序上下文getApplicationContext(){
返回WebApplicationContextIls.getWebApplicationContext(getServletContext());
}
公共应用程序EventPublisher getApplicationEventPublisher(){
返回(ApplicationEventPublisher)getApplicationContext();
}
公共LocaleResolver getLocaleResolver(){
返回RequestContextUtils.getLocaleResolver(getRequest());
}
public ThemeResolver getThemeResolver(){
返回RequestContextUtils.getThemeResolver(getRequest());
}
公共资源加载器getResourceLoader(){
return(ResourceLoader)getApplicationContext();
}
公共ResourcePatternResolver getResourcePatternResolver(){
返回(ResourcePatternResolver)getApplicationContext();
}
public MessageSource getMessageSource(){
return(MessageSource)getApplicationContext();
}
公共转换服务getConversionService(){
返回getBeanFromApplicationContext(ConversionService.class);
}
公共数据源getDataSource(){
返回getBeanFromApplicationContex
HttpSession sesssion = ...; // can come from request.getSession(false);
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;
}
}
}
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;
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
@RequestMapping("/messages/inbox")
public ModelAndView findMessagesForUser(@AuthenticationPrincipal User user) {
...
}
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);
}
}
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
attr.getSessionId();