At work I’ve been tasked with improving an API recently, and I decided it would be a good opportunity to take Laravel out for a spin. I’ve been keen on learning more about laravel and it’s API capabilities which are supposedly very strong, although I have noted that there’s not much documentation around them. The existing API is flat PHP and uses token based authentication. This allows users to authenticate with a string “api_key” in the request URL, in the header or in the body of the JSON request. I decided that instead of trying to get existing users to upgrade to something like oAuth (for which there are some interesting plugins https://packagist.org/packages/lucadegasperi/oauth2-server-laravel), I’d just implement the same token based authentication model for the revised API in Laravel. There are already advantages to using Laravel for APIs – it highly encourages a restful approach, as for Laravel 5.2 it includes rate limiting out of the box and allows for route prefixing, so it is possible to have multiple endpoints in one Laravel application.
Setting up token based authenticaton in Laravel is so poorly documented that it took me a while to work out how it is achieved.
1. User API Tokens
Users need to have an API token to be associated with them in order to allow the authentication model to work. This is easy enough to add by editing the user migration in your laravel installation.
// Store an API key for this user. $table->string('api_token', 60)->unique();
This allows you to store a 60 character unique API Token for each user.
2. Setting up API Authentication
There are several ways you can now call API Token authentication for your application. Probably the best is to use middleware in your routes file:
Route::group([ 'prefix' => 'api', 'middleware' => 'auth::api' ], function() { Route::resource('fruit', FruitController); });
Now any time requests are made to the route group, the API authentication method will be called. This includes token based authentication (now defined in the users table) as well as the API rate limiting.
3. Making API Requests
You can now submit your API requests to see if the Laravel token authentication is working. To do this you can submit “api_token” as either a GET or POST paramiter. There’s also hidden away the option to have it set as a header, however this requires you to use an Authorization header:
Key: ‘Authorization’
Value: ‘Bearer [token]’
Check out the code here:
and here:
https://github.com/laravel/framework/blob/master/src/Illuminate/Auth/TokenGuard.php#L81-L94