Search code examples
javaspringsessionhttpsession

Spring : How to get the username on logout call


I have the following controller for logout I want to get the name of the logout user how can I acheive this ?

String userName=(String)session.getAttribute("name"); this line not working

Logout Controller

@RequestMapping(value = "/session", method = RequestMethod.DELETE)
    public @ResponseBody ResponseEntity<?> logout(HttpSession session){

        String userName=(String)session.getAttribute("name");
        System.out.println("name: " + userName);
        session.invalidate();
        return ResponseEntity.ok("user logged out");

    } 

Solution

  • I do not have currently any Spring projects near me, but as I remember, it could be possible to do it like this:

    SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    

    As I said, I'm not sure if it's working. It's been a while since I last used Spring, but let me know if it is.