簡體   English   中英

Spring Security:注銷期間從會話中獲取一些數據

[英]Spring Security: getting some data from session during logout

在我的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為null。 有什么方法可以在注銷之前從會話中捕獲該價值。

我不會直接回答,而是向您展示另一種方法。 我總是在春季安全項目中加入以下課程:

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;
    }
}

它使用其中存儲了UserDetails SecurityContext 我總是在User類中實現UserDetails接口,因此它可以工作。

您可以在每個控制器,服務或存儲庫中使用上述靜態方法(但我認為只有服務層才是合適的,最終還是控制器)。 如果呼叫是通過不安全的端點未經身份驗證進入的,它將返回null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM