Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle authentication in PHP REST web service?

Tags:

rest

php

I've read that a good way to write web services to be consumed from mobile apps is to avoid SOAP (too verbose) and to use REST. In many REST examples, I have seen it is better to avoid sessions due to the stateless nature of REST. But how can I assure security when invoking my web service? I would like to make a "login" call than pass a session_id/token to the next web service call. How can I do it?

like image 786
Cris Avatar asked Mar 07 '11 11:03

Cris


People also ask

How do I authenticate a user in REST Web services?

Use of basic authentication is specified as follows: The string "Basic " is added to the Authorization header of the request. The username and password are combined into a string with the format "username:password", which is then base64 encoded and added to the Authorization header of the request.

How do you pass authentication on REST API?

Users of the REST API can authenticate by providing their user ID and password within an HTTP header. To use this method of authentication with HTTP methods, such as POST, PATCH, and DELETE, the ibm-mq-rest-csrf-token HTTP header must also be provided, as well as a user ID and password.

What type of authentication should I use for REST API?

One of the most common authentication methods used by REST APIs is username and password authentication. There are several different types that use a username and password but the most common one is HTTP Basic authentication.


2 Answers

The cleanest way would be using HTTP authentication. While that wouldn't go by the login+sessionid way you mentioned it would be much cleaner and more straightforward (API calls do not related on other API calls and clients do not need to expect session timeouts etc.)

like image 80
ThiefMaster Avatar answered Sep 23 '22 18:09

ThiefMaster


You can pass user token (and session, or any other auth data if you need it) in a json request like:

{"auth": {"session_id": "abc", "token":"123"},
 "data": "your request data"
}

If you are crazy about security you can generate a new token after each user login and even have life time for tokens.

like image 23
Artur Marnik Avatar answered Sep 26 '22 18:09

Artur Marnik