Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter auth key for REST service

I'm writing a simple RESTful service, using Phil Sturgeon Rest Server. I want to protect my methods by using the API key provided with this library.

Unfortunately, this is not very well documented and I'm a bit lost.

I want to authenticate users (email/password), then generate an auth key to send on every other requests. But it seems that I already need the auth key to generate one ... Create a dummy key does not seem very secure. Sorry if it is a dumb question, but what should be the best practice?

like image 466
jose Avatar asked May 20 '13 17:05

jose


People also ask

What is REST API in PHP?

Rest API is an API that allows programmers to send and receive information from other programs using HTTP protocol commands such as GET and POST. Although REST API works with most protocols, it is specially designed for transmitting data through the HTTP protocol.

What is API in PHP with example?

API stands for Application Programming Interface. A Web API is an application programming interface for the Web. A Browser API can extend the functionality of a web browser. A Server API can extend the functionality of a web server.


1 Answers

If you are familiar with other APIs you'll notice a common pattern. I recommend an authenticate method where the user passes their email and password, which will return a generated unique auth key. The auth key would be like a session id, think of how cookies work. Then all the other API methods should check $this->post('auth') and you need to compare this with your session handler (i.e. database or sessions), before you process each request.

Seems like a lot of code huh? Nope.

All your models should have an overloaded constructor:

class MyAPIController extends Rest_controller
{
    public function __construct()
    {
        parent::__construct();

        if(!authCheck($this->post('auth'))){
            returnFailedResponse();
            exit();
        }
}

Then write you API normally, like in the examples on Phil Sturgeon's website. http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

Make a model that has authCheck to test that the auth key is valid, and make a method for returnFailedResponse to return a 401 Unauthorized.

In another controller, lets call it 'Auth', use the above contructor.

Now every call to your api should set a header for the Auth. Ex. 'Auth: 12m34k23b'.

like image 197
Michael Ozeryansky Avatar answered Sep 20 '22 07:09

Michael Ozeryansky