RESTful API Authentication – Using Session Tokens

apiappauthenticationrestsession

After looking at a lot of session/state debates with regard to REST and finding nothing concrete, I'm just going to cut to the chase and ask myself.

Developing a RESTful API as a backend for a mobile app, I (think I) want to keep track of all users (even unregistered ones) with guest sessions. This allows me to customise content and do statistics on my users.

Implementation-wise I would have my app identify itself, as if to an /authenticate end-point, just without e-mail/password, more like UUID. But this effectively makes my whole API expect a "session token" with each request.

Is this a bad approach, or would you do the same?

Best Answer

The usual approach is to simply provide a session token back to the client via headers or cookies if they failed to provide one, or provided an invalid one. This is especially necessary for web clients where the session can time out while they're on a page somewhere. This ensures you have your session immediately, without going to the "authenticate" end-point, which should do what its name suggests: Authenticate the user.

Of course, this means that the client must be designed to expect the session token to change, but that's a good thing. Regenerating the session token, particularly on changes of privilege (ie, going from guest to full user), helps to prevent session hijacking. And don't think that just because you're a mobile app instead of a web page you're safe from hijacking. You're not, a hacker can use Fiddler or some other proxy to intercept your mobile API.