0

I can't really understand the concept of this. Take a look what I have:

@PostMapping("/login")
public ModelAndView login( @ModelAttribute UserLoginDTO userDto, HttpSession session) {
    if (authenticateService.loginCheck(userDto.getUsername(), userDto.getPassword())) {
        session.setAttribute("sessionid",123);
        return new ModelAndView("redirect:/profile");
    } else {
        return new ModelAndView("signin","error","Invalid username or password combination, or the user does not exist.");
    }
}

I have set a sessionID to the session. When the user navigates around the website, how do I know that it is the same user?

Do I have to store the sessionID on server side in a ConcurrentHashMap? And when there is a page switch I should do this?

if (conHashMap[...] == session.getId()) {...}
else //redirect to login page 

Also on logout, do I just remove the element from the hashmap and call for session.invalidate()?

Or is there a way of doing this without using hashmaps at all?

Andrew
  • 95
  • 2
  • 12
  • You get those garantuees by how a session works. This has nothing to do with Spring but how the `HttpSession` is defined in the Servlet Specification and handled by the Servlet Container. – M. Deinum Aug 17 '18 at 09:51
  • Thanks, I edited the tags. What I want tho, is an example how to do what I am describing above. – Andrew Aug 17 '18 at 09:56
  • No. You don't manage the session the container does. On logout you only need to invalidate the session. You are overthinking and overcomplicating things. – M. Deinum Aug 17 '18 at 09:57
  • I'm trying really hard to understand, so please bear with me. – Andrew Aug 17 '18 at 10:01
  • If the session is managed by the container, where do I tell the container, that if the session is invalid, then redirect the user to the login page? – Andrew Aug 17 '18 at 10:02
  • Check in a servlet filter if there is a session and if that session contains the variable you use to store the user. Or even better use Spring Security to do all this for you. – M. Deinum Aug 17 '18 at 10:03

2 Answers2

0

You know the session is from the same user if the id is the same, yes. You can eventually store informations on the session. Alternativelly, you can create session scoped beans :

@Component
@Scope(value="session")
public class MyComponent {
    // ...
}

All you will store in this kind of objects are only accessible by one user.

Oreste Viron
  • 3,592
  • 3
  • 22
  • 34
0

Figured it out.

After invalidating, the browser will visit the site with a new session. The new session won't have the "sessionid" attribute bound to it. This way, I could determine which session is a valid one, without using hashmaps.

if (session.getAttribute("sessionid")==null){
        return new ModelAndView("signin","error","Session expired, please log in again.");
Andrew
  • 95
  • 2
  • 12