If REST applications are supposed to be stateless, how do you manage sessions?

前端 未结 16 1043
既然无缘
既然无缘 2020-11-22 10:23

I\'m in need of some clarification. I\'ve been reading about REST, and building RESTful applications. According to wikipedia, REST itself is defined to be Representation

16条回答
  •  既然无缘
    2020-11-22 10:54

    When you develop a RESTful service, in order to be logged in you will need your user to be authenticated. A possible option would be to send the username and password each time you intend to do a user action. In this case the server will not store session-data at all.

    Another option is to generate a session-id on the server and send it to the client, so the client will be able to send session-id to the server and authenticate with that. This is much much safer than sending username and password each time, since if somebody gets their hand on that data, then he/she can impersonate the user until the username and password is changed. You may say that even the session id can be stolen and the user will be impersonated in that case and you are right. However, in this case impersonating the user will only be possible while the session id is valid.

    If the RESTful API expects username and password in order to change username and password, then even if somebody impersonated the user using the session id, the hacker will not be able to lock out the real user.

    A session-id could be generated by one-way-locking (encryption) of something which identifies the user and adding the time to the session id, this way the session's expiry time could be defined.

    The server may or may not store session ids. Of course, if the server stores the session id, then it would violate the criteria defined in the question. However, it is only important to make sure that the session id can be validated for the given user, which does not necessitate storing the session id. Imagine a way that you have a one-way-encryption of email, user id and some user-specific private data, like favorite color, this would be the first level and somehow adding the username date to the encrypted string and apply a two-way encryption. As a result when a session id is received, the second level could be decrypted to be able to determine which username the user claims to be and whether the session time is right. If this is valid, then the first level of encryption could be validated by doing that encryption again and checking whether it matches the string. You do not need to store session data in order to achieve that.

提交回复
热议问题