Since restful api is stateless how do I do user session in this case? Says I'm a set of api that allow user to borrow book, and I don't require user to login to browse the books, how do I do that? And user only can book after it's login, how do I keep the session?
-
You can use passport.js with a strategy that supports sessions – vbranden Feb 23 '16 at 14:22
-
@vbranden no, passport alone doesn't work with restful api – Nichole A. Miler Feb 23 '16 at 14:38
-
2I would say it's a duplicte of http://stackoverflow.com/questions/3105296/if-rest-applications-are-supposed-to-be-stateless-how-do-you-manage-sessions – ChatterOne Feb 23 '16 at 14:38
1 Answers
Your API would hand out authentication tokens to those users that log in, and your endpoints would be defined with a "needs authorization" middleware.
GET /books
(lists the books, no authorization required)
POST /books/:bookId
(reserves a book, needs authorization, returns 401 if not authorized)
Client would store token locally upon logging in, and send token with each request (and since you'll be using SSL, it can be on the request itself).
Server needs to store tokens somewhere, and look them up via middleware on each request. Absence of a token (either not given or not found) means the request is not authenticated. Tokens can be store locally in memory to start (disappear if server crashes, need sticky sessions if load balancing multiple nodes), or in some persistent database (Redis, Mongo, MySQL).
Typically the sessions have an expire time, and each action refreshes that time as well. If client gets a "token expired" message, they should re-login to update their local copy, and have the server store the new value.

- 5,917
- 2
- 23
- 21