'How to log-out Spring Security in Vaadin?

Is there a practical working example of how to programmatically log out from Spring Security? I tried many ways, and no one works; the session ID stays valid in the browser.

Here is the code I am using:

activeUserMenu.addItem("Log out", e -> {
        UI.getCurrent().getPage().setLocation("/");
        SecurityContextHolder.clearContext();
        SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
        logoutHandler.logout(
            VaadinServletRequest.getCurrent().getHttpServletRequest(), null,
            null);
        for(Cookie cookie : VaadinServletRequest.getCurrent().getCookies()) {
          cookie.setMaxAge(0);
        }
      });

Notice: I log in through a custom Thymeleaf form. In theory, all I have to do is redirect the browser to "/logout" default Spring URL. But Vaadin tells me that the router does not recognize that URL. I made several other attempts, including using Javascript and handling a get to "/logout". None worked.



Solution 1:[1]

I think clearing cookies should work. I use the following to remove a cookie by name in a Vaadin 14 app:

private void removeCookie(String cookieName) {
    Cookie cookie = new Cookie(cookieName, "");
    cookie.setMaxAge(0);
    VaadinResponse.getCurrent().addCookie(cookie);
}

Alternatively you should be able to logout just by invalidating the whole HTTP session: VaadinServletRequest.getCurrent().getHttpServletRequest().getSession().invalidate()

Solution 2:[2]

Configure:

http.
...
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")

then

logoutButton.addClickListener(clickEvent -> {
            UI.getCurrent().getPage().setLocation("/logout");
        });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Viorel Stolea