Restful API and user session

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?


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.

链接地址: http://www.djcxy.com/p/41152.html

上一篇: ASP.NET WebApi 2获取服务器中的所有活动会话(用户)

下一篇: Restful API和用户会话