8

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?

4
  • 2
    A session token of some kind is inevitable, unless you plan on making your API stateful. Jan 9, 2017 at 16:32
  • 2
    @RobertHarvey: inevitable? Nothing prevents from providing authentication info on every request, and get rid of any state. It has its performance impact, especially when strong hashing algorithms are involved, but this is the only drawback. Jan 9, 2017 at 21:00
  • 1
    Well, sure, if you want to go down that rabbit hole. Jan 9, 2017 at 21:11
  • 3
    RESTful APIs in theory are stateless so no session should be involved. This helps with scalability and has other positive side effects. A problem I see with this is where on some systems after authentication there can be pretty resource intensive checks, that have to be done on each login, to do various calculations related to the authenticated account. Now, with a session these calculations are only done once, stored in session, and the user given a session ID but with truly stateless app each REST call would have to authenticate and regenerate all the heavy calculations each and every time.
    – PadraigD
    Jun 12, 2018 at 10:22

1 Answer 1

6

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.