REST API - User session Management in a stateless way

1.9k views Asked by At

This may be something trivial for many of you but I haven't had any luck in understanding the right flow for my usecase. I am building an API for our mobile apps (IOS & Android) and like most of the web applications, the API has certain features/pages(in terms of a website) that can only be accessed by a logged in user. Since sessions are usually discouraged in API construct, I wonder how to track such things in API. My question is, how do I identify that:

  1. User is Logged in from client side. So when a user logs in by sending his/her username and password, server side authorizes the user after verifying from the DB. At this point, what should I send to client that it needs to send me with each request for future identification?
  2. Making sure that I am getting request for the real user...user A, for instance, can't ask for user's B information. In other words what I am thinking is that, if I do things based on a UserID (or some token as it has to have some encryption too) then someone can break my security somehow and ask for content for another user's ID...How do i secure this?

Essentially, I am looking for some guidance for maintaining state in a stateless way.

2

There are 2 answers

2
inf3rno On

There is no such concept in the API development as logged in state, etc... That's why it is stateless. You have to authenticate every request (so send the username and password with every request).

note: You can have session, but it is maintained by the REST client, so the API does not know anything of it.

0
kovalad On

Try sending a session_id after user is authenticated successfully. That might be created as an md5 hash from user_name salted by current timestamp.

At server-side I you can create a table session_data(session_id, user_id, last_access_time, session_data), that would map session_id to a user. Session would become obsolete after last_access_time is to old.

This approach isn't perfect for intense user interaction, since you will have to update session_data after every request.

In this case such table could be moved in any fast storage.