Reputation: 134
I have simple problem, I have js application (frontend) that uses my PHP REST api. I need to implement simple token based authentication and I'm not sure how that should work since i dont use sessions in REST. From my understaning it goes something like this:
User tries to login, if valid credentials, I generate token and return user object with token
I update user token in database
Client holds user object in cookies or local storage instead of session and with every request he passes token in header
I check if there's token in DB, if there is (I know which user is sending request)I proceed with request, otherwise I send him to login page
If token expires or user signs out, i update token field in DB with NULL or empty string (not sure if this is needed).
I just need confirmation if this is ok approach or i misunderstood something in protocol. Thank you all in advance
Thank you
Upvotes: 3
Views: 3347
Reputation: 26129
I don't think this approach is stateless. The existence of the token represents the logged in state. Which means that a part of the client state is maintained by the server. In other words the token count on the server increases by the client sessions.
each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. - Fielding - REST - stateless
I would rather do something like this:
This way you will avoid storing the token (and so the client state) on the server. Not a perfect solution (e.g. the token can be used by others before it expires) but it is stateless. I am not sure whether you really need REST or token based auth. (Be aware that these applies on human to machine communication. Machine to machine communication is usually authorized differently.)
Upvotes: 4
Reputation: 36
By stateless. it means that the in REST server does not store any state about the client in session or any other form.
I have personally used something like this for an app and this is the simplest form of security you can have.
When our system used to issue access token it create an expiry date/time also along with it. everytime you make a call with a specific access-token its expiry date/time updated +n hrs
Upvotes: 0