N
N
Nikita Bratsky2022-01-30 23:26:51
Java
Nikita Bratsky, 2022-01-30 23:26:51

How to save sessions between rest requests in spring boot?

Good evening everyone, there was a problem with saving sessions between requests. Conditionally, I have two methods (in different controllers) that process post requests. The first method is login, which saves the user's session, the second method accesses the session, but this is where the problem arose. First of all, it should be noted that the session is being created and this can be seen both by the method request.getSession().getAttribute("name") , written immediately after saving the value to the session, and in Mongo Compass, by the way, the database for storing sessions is selected - Mongo , but when comparing the id of these two sessions, it turns out that these sessions are completely different. I tried all the methods from articles, similar problems on Stack Overflow and so on.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2022-01-31
@NikBr_9

Sessions work like this: when creating a session, the server sends a Set-Cookie header to the browser, in which it stores the value of the session identifier (JSESSIONID). On subsequent requests, the browser sends a "cookie" back to the server, and the latter, having received the identifier, can restore the session from its storage. If the "cookies" are blocked, then it is possible to pass jsessionid as the query param of the request. But this already requires additional gestures on the client side.
Since you're mentioning REST, I'll assume using XmlHttpRequest in a browser (either directly or indirectly through some library) that doesn't send the default Cookie header.
So a solution might be to send the session id explicitly as a query param named jsessionid.
However, using a session in REST requests is generally not a good practice, since REST is supposed to be stateless. And in the case of a session, you have a state on the server side. If the session is only needed to authenticate the client, then look into using tokens such as JWTs to solve this problem without having a session on the server side.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question