Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP API authentication and sessions

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?

like image 722
JonoB Avatar asked Jan 10 '12 15:01

JonoB


People also ask

Can we use JWT in PHP?

Here, you'll use the PHP-JWT package's encode() method. This method helps transform your data array into a JSON object. Following the conversion to a JSON object, the encode function produces JWT headers and signs the received payload with a cryptographic combination of all the information and the given secret key.

How does PHP authentication work?

After receiving user authentication details in PHP, it compares the form data with the user database by executing a query by using the connection object. The query binds the username entered by the user via HTML form. Then, it verifies the password hash with the entered password to return the authentication results.

What is authentication and authorization in PHP?

Authentication vs AuthorizationAuthentication is the process of validating a users credentials. Is the user is in the system and does their username match their password? Authorization is what permissions do they have in the system.


1 Answers

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.

like image 96
Paul Bain Avatar answered Oct 05 '22 09:10

Paul Bain