8

I have a PHP application that relies extensively on sessions. We are now considering building an API for our users. Our initial thoughts are that users will need to authenticate against the api with their email address, password and an API key (unique for each user).

However, as the current application (including the models) relies on user sessions extensively, I am not sure on the best approach.

Assuming that an API request is correctly authenticated, would it be acceptable to:

  • Start the session for the API call once user is authenticated
  • Run the models and return json/xml to the user
  • Kill the session

This means that the session gets instantiated for each API call, and then immediately flushed. Is this OK? Or should we be considering other alternatives?

1
  • You are correct, the API should be stateless and not use sessions/cookies if possible. But that can be done easily, no problem. You should re-use an existing authentication framework, however, because it's really complex. For example, take a look at github.com/delight-im/PHP-Auth which is both framework-agnostic and database-agnostic. Then send the credentials with every request and on the server (1) log in, (2) do the actual work and finally (3) log out again. Commented Oct 21, 2016 at 21:26

1 Answer 1

2

In my experience of creating APIs, I have found it best that sessions only last for one request and to recreate the session information in each execution cycle.

This does obviously introduce an overhead if your session instantiation is significant, however if you're just checking credentials against a database it should be OK. Plus, you should be able to cache any of the heavy lifting in something like APC or memcache based on a user identifier rather than session reducing the work required to recreate a session while ensuring authentication verified in each request.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.