【问题标题】:Spring Security: getting some data from session during logoutSpring Security:在注销期间从会话中获取一些数据
【发布时间】:2017-06-11 14:11:15
【问题描述】:

在我的Spring MVC Web 应用程序中,我使用Spring Security 进行登录和注销。在我的spring-security.xml 我有以下内容:

<form-login login-page="/login" default-target-url="/"
            authentication-failure-url="/login?error" username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/login?logout" />

在登录过程中,我将一个包含用户详细信息的 TO 设置为会话,如下所示:

request.getSession().setAttribute("USERTO", userTO);

其中userTO 是具有UserTO 类型的用户详细信息的对象。而我的注销控制器方法如下:

@RequestMapping(value = "/login", method = RequestMethod.GET)
        public String login(ModelMap model, @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout)
        {
            try
            {
                UserTO user = (UserTO) httpSession.getAttribute("USERTO");
                if (error != null)
                    {
                        //error during login
                    }
                if (logout != null)
                    {
                        //succesful logout
                    }
                model.addAttribute("smartWCMLayoutID", "smartly");
                model.addAttribute("cm", new CommonModel("", "", ""));
                return "smartwcm.login.definition";
            }
            catch(Exception ex)
            {

            }
        }

但在注销期间,我总是将UserTO 设为空。有什么方法可以在注销之前从会话中捕获该值。

【问题讨论】:

    标签: java spring spring-mvc session spring-security


    【解决方案1】:

    我不会直接回答,而是告诉你另一种方法。我总是将以下课程附加到我的 spring-security 项目中:

    public class LoggedUserUtils {
        public static User getLoggedUser() {
            final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            final Object principal = auth.getPrincipal();
    
            if (principal instanceof User) {
                return (User) principal;
            }
            return null;
        }
    }
    

    它使用SecurityContext,您在其中存储了UserDetails。我总是在User 类中实现UserDetails 接口,所以它可以工作。

    您可以在每个控制器、服务或存储库中使用上述静态方法(但我认为只有服务层是合适的,最终也是控制器)。如果通过不安全的端点输入的调用没有经过身份验证,它将返回一个null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-16
      • 2015-06-30
      • 2020-11-16
      • 1970-01-01
      • 2016-11-11
      • 2016-10-02
      • 2013-12-22
      • 1970-01-01
      相关资源
      最近更新 更多