如何在Spring中获取Session Object?

eoigrqb6  于 2024-01-05  发布在  Spring
关注(0)|答案(9)|浏览(172)

我对Spring和Spring安全性比较陌生。
我试图编写一个程序,我需要在服务器端使用Spring安全性对用户进行身份验证,
我得出了以下结论:

  1. public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
  2. @Override
  3. protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
  4. throws AuthenticationException
  5. {
  6. System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
  7. }
  8. @Override
  9. protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
  10. {
  11. System.out.println("Method invoked : retrieveUser");
  12. //so far so good, i can authenticate user here, and throw exception if not authenticated!!
  13. //THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
  14. }
  15. }

字符串
我的用例是,当一个用户被认证时,我需要放置一个属性,如:

  1. session.setAttribute("userObject", myUserObject);


myUserObject是某个类的对象,我可以通过多个用户请求在整个服务器代码中访问它。

zf9nrax1

zf9nrax11#

你的朋友是org.springframework.web.context.request.RequestContextHolder

  1. // example usage
  2. public static HttpSession session() {
  3. ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
  4. return attr.getRequest().getSession(true); // true == allow create
  5. }

字符串
这将由标准的spring mvc dispatch servlet填充,但是如果你使用不同的web框架,你必须在web.xml中添加org.springframework.web.filter.RequestContextFilter作为过滤器来管理保持器。

编辑:作为一个附带的问题,你实际上想做什么,我不确定你是否需要在UserDetailsServiceretieveUser方法中访问HttpSession。Spring security将为你在会话中放置UserDetails对象。它可以通过访问SecurityContextHolder来检索:

  1. public static UserDetails currentUserDetails(){
  2. SecurityContext securityContext = SecurityContextHolder.getContext();
  3. Authentication authentication = securityContext.getAuthentication();
  4. if (authentication != null) {
  5. Object principal = authentication.getPrincipal();
  6. return principal instanceof UserDetails ? (UserDetails) principal : null;
  7. }
  8. return null;
  9. }

展开查看全部
nzkunb0c

nzkunb0c2#

既然你使用的是Spring,那就坚持使用Spring,不要像其他帖子所说的那样自己动手。
Spring manual说道:
出于安全考虑,您不应该直接与HttpSession交互。这样做根本没有正当理由-始终使用SecurityContextHolder。
访问会话的建议最佳做法是:

  1. Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  2. if (principal instanceof UserDetails) {
  3. String username = ((UserDetails)principal).getUsername();
  4. } else {
  5. String username = principal.toString();
  6. }

字符串
这里的关键是Spring和Spring Security为您做了各种各样的伟大的事情,比如Session Fixation Prevention。这些事情假设您正在使用Spring框架,因为它被设计用于使用。因此,在您的servlet中,使其具有上下文意识并像上面的示例那样访问会话。
如果你只需要在会话作用域中存储一些数据,试着创建一些会话作用域bean,比如this example,让autowire来发挥它的魔力。

展开查看全部
q8l4jmvw

q8l4jmvw3#

我自己做的utils.它很方便。:)

  1. package samples.utils;
  2. import java.util.Arrays;
  3. import java.util.Collection;
  4. import java.util.Locale;
  5. import javax.servlet.ServletContext;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpSession;
  8. import javax.sql.DataSource;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  12. import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
  13. import org.springframework.context.ApplicationContext;
  14. import org.springframework.context.ApplicationEventPublisher;
  15. import org.springframework.context.MessageSource;
  16. import org.springframework.core.convert.ConversionService;
  17. import org.springframework.core.io.ResourceLoader;
  18. import org.springframework.core.io.support.ResourcePatternResolver;
  19. import org.springframework.ui.context.Theme;
  20. import org.springframework.util.ClassUtils;
  21. import org.springframework.web.context.request.RequestContextHolder;
  22. import org.springframework.web.context.request.ServletRequestAttributes;
  23. import org.springframework.web.context.support.WebApplicationContextUtils;
  24. import org.springframework.web.servlet.LocaleResolver;
  25. import org.springframework.web.servlet.ThemeResolver;
  26. import org.springframework.web.servlet.support.RequestContextUtils;
  27. /**
  28. * SpringMVC通用工具
  29. *
  30. * @author 应卓([email protected])
  31. *
  32. */
  33. public final class WebContextHolder {
  34. private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);
  35. private static WebContextHolder INSTANCE = new WebContextHolder();
  36. public WebContextHolder get() {
  37. return INSTANCE;
  38. }
  39. private WebContextHolder() {
  40. super();
  41. }
  42. // --------------------------------------------------------------------------------------------------------------
  43. public HttpServletRequest getRequest() {
  44. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
  45. return attributes.getRequest();
  46. }
  47. public HttpSession getSession() {
  48. return getSession(true);
  49. }
  50. public HttpSession getSession(boolean create) {
  51. return getRequest().getSession(create);
  52. }
  53. public String getSessionId() {
  54. return getSession().getId();
  55. }
  56. public ServletContext getServletContext() {
  57. return getSession().getServletContext(); // servlet2.3
  58. }
  59. public Locale getLocale() {
  60. return RequestContextUtils.getLocale(getRequest());
  61. }
  62. public Theme getTheme() {
  63. return RequestContextUtils.getTheme(getRequest());
  64. }
  65. public ApplicationContext getApplicationContext() {
  66. return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  67. }
  68. public ApplicationEventPublisher getApplicationEventPublisher() {
  69. return (ApplicationEventPublisher) getApplicationContext();
  70. }
  71. public LocaleResolver getLocaleResolver() {
  72. return RequestContextUtils.getLocaleResolver(getRequest());
  73. }
  74. public ThemeResolver getThemeResolver() {
  75. return RequestContextUtils.getThemeResolver(getRequest());
  76. }
  77. public ResourceLoader getResourceLoader() {
  78. return (ResourceLoader) getApplicationContext();
  79. }
  80. public ResourcePatternResolver getResourcePatternResolver() {
  81. return (ResourcePatternResolver) getApplicationContext();
  82. }
  83. public MessageSource getMessageSource() {
  84. return (MessageSource) getApplicationContext();
  85. }
  86. public ConversionService getConversionService() {
  87. return getBeanFromApplicationContext(ConversionService.class);
  88. }
  89. public DataSource getDataSource() {
  90. return getBeanFromApplicationContext(DataSource.class);
  91. }
  92. public Collection<String> getActiveProfiles() {
  93. return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
  94. }
  95. public ClassLoader getBeanClassLoader() {
  96. return ClassUtils.getDefaultClassLoader();
  97. }
  98. private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
  99. try {
  100. return getApplicationContext().getBean(requiredType);
  101. } catch (NoUniqueBeanDefinitionException e) {
  102. LOGGER.error(e.getMessage(), e);
  103. throw e;
  104. } catch (NoSuchBeanDefinitionException e) {
  105. LOGGER.warn(e.getMessage());
  106. return null;
  107. }
  108. }
  109. }

字符串

展开查看全部
sbtkgmzw

sbtkgmzw4#

实际上,即使会话在HttpSessionLisener上被销毁,您也可以通过执行以下操作从会话中访问信息:

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

字符串
或者你也可以在任何有HttpSession对象的地方访问信息,比如:

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


最后一个假设你有这样的东西:

  1. HttpSession sesssion = ...; // can come from request.getSession(false);

展开查看全部
1u4esq0p

1u4esq0p5#

在我的场景中,我像这样将HttpSession注入到CustomAuthenticationProvider类中

  1. public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
  2. @Autowired
  3. private HttpSession httpSession;
  4. @Override
  5. protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
  6. throws AuthenticationException
  7. {
  8. System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
  9. }
  10. @Override
  11. protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException
  12. {
  13. System.out.println("Method invoked : retrieveUser");
  14. //so far so good, i can authenticate user here, and throw exception
  15. if not authenticated!!
  16. //THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
  17. httpSession.setAttribute("userObject", myUserObject);
  18. }
  19. }

字符串

展开查看全部
91zkwejq

91zkwejq6#

我尝试与下一个代码和工作出色

  1. import org.springframework.security.core.Authentication;
  2. import org.springframework.security.core.context.SecurityContextHolder;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.ModelMap;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. /**
  8. * Created by jaime on 14/01/15.
  9. */
  10. @Controller
  11. public class obteinUserSession {
  12. @RequestMapping(value = "/loginds", method = RequestMethod.GET)
  13. public String UserSession(ModelMap modelMap) {
  14. Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  15. String name = auth.getName();
  16. modelMap.addAttribute("username", name);
  17. return "hellos " + name;
  18. }

字符串

展开查看全部
g9icjywg

g9icjywg7#

如果你需要的只是User的详细信息,对于 Spring Version 4.x,你可以使用Spring提供的@AuthenticationPrincipal@EnableWebSecurity标签,如下所示。
安全配置类:

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  4. ...
  5. }

字符串
控制器方法:

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

展开查看全部
jljoyd4f

jljoyd4f8#

  1. ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
  2. attr.getSessionId();

字符串

vptzau2j

vptzau2j9#

  1. String token = (String) pageContext.findAttribute("TOKEN");
  2. if (token.equals(null)) {
  3. System.out.println("No pasar");
  4. } else {
  5. System.out.println("Excelente llego");
  6. }

字符串

相关问题