Authenticate Only Certain HTTP Verbs (POST, PUT, DELETE) in Laravel 4

In working on the API for an upcoming project, I needed a way to allow all reads (GET) to be allowed without authentication but any requests (POST, PUT, or DELETE) changing the data to require authentication.

I wanted to use the Route::group() to help keep the routes.php file simple by grouping all the API calls together. I also wanted to use the Route::resource to keep the controller relatively simple too.

// router.php
Route::group(array('prefix' => 'api/v1'), function()
{
    Route::resource('tweets', 'ApiTweetsController');
}

Next within the controller I added the following to the __construct() class to require auth.basic authentication on all functions except 'index' and 'show'. Since we're using a resource route, the 'index' and 'show' function all represent HTTP GET requests. So any POST, PUT or DELETE request will require authentication - which is exactly what we're looking for!

class ApiTweetsController extends BaseController {

   public function __construct()
   {
      $this->beforeFilter('auth.basic', array('except' => array('index','show')));
   }

   ....

Note: you could also add 'edit' and 'create' to the 'except' array but I did not need those methods for the API I was working on. array('except' => array('index','show','edit','create')).

Update: If you wanted to use the actual HTTP verbs, you can use the following instead. Thanks ericbarnes for pointing this out.

$this->beforeFilter('auth.basic', array('on' => array('post','put','patch','delete')));

Please let me know if you have any questions about this or if you're found a different/better way of doing this.


comments powered by Disqus