Keep user logged in using Django and Vue 3
The request.session
object will automatically generate a cookie with the default name sessionid
, which stores the session's session key value. When the session expires, the cookie will automatically removed. Only when the cookie is cleared can the logged in user log in again.
Set the expiration time of the session through the backend, and when the time is up, you can see through the browser that the cookie will automatically disappear. Therefore, it is only necessary to set that the token value in the user's local storage disappears along with the cookie, and the duration of the user's login status can be controlled by setting the expiration time of the session, such as a seven day no login period.
We may think that login status can be controlled based on cookies, but in reality, it is not easy to manipulate cookie values in Vue. In JavaScript, we can control cookies through instructions such as document. getElementId(). But in Vue, using the document instruction is likely to result in an empty return value. Therefore, controlling login status cannot be achieved through direct control of cookies.
Therefore, we need to write an additional interface in the backend to verify the validity of the token and control the user's login status.
Note: Cookies only affect whether users can log in again, and in Vue, it is inconvenient to use cookies to determine user login. Therefore, only tokens can be used to implement this. However, tokens and cookies are independent in the front-end, so if the cookie expires and the token is not cleared, it will result in continuous login. If the token is cleared and the cookie is not expired, it will cause the user to be unable to log in after the login status ends.
There is no comment, let's add the first one.