Skip to content

Instantly share code, notes, and snippets.

@simonhamp
Created December 10, 2017 06:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonhamp/ecccd585f159768abc5b01d5a0521824 to your computer and use it in GitHub Desktop.
Save simonhamp/ecccd585f159768abc5b01d5a0521824 to your computer and use it in GitHub Desktop.
Laravel Testing: Ensure your controllers enforce authorization
<?php
namespace App\Tests;
use Illuminate\Support\Facades\Route;
class AuthorizationTest extends TestCase
{
public function setUp()
{
parent::setUp();
/**
* Testing without middleware allows us to bypass all of the other security at the route/middleware layer.
* This will allow us to check the controller layer security.
*/
$this->withoutMiddleware();
}
public function testAllRoutesRequireAuthorization()
{
$routes = Route::getRoutes();
foreach ($routes as list('method' => $method, 'uri' => $uri)) {
// Call each endpoint
$response = $this->call($method, $uri);
$this->assertEquals(
403,
$response->getStatusCode(),
"Insecure Route: $method $uri."
);
}
}
}
@simonhamp
Copy link
Author

Using Laravel's built-in Authorization (Gates/Policies) is a simple and excellent way to secure your application. One of the tricks when it's deployed is that, without the presence of an authenticated user, your rules will all fail (as you'd expect) and Laravel adds a 403 Forbidden header to the response.

If you use a common base controller that handles all of your authorization rules, when overriding any of the methods it's all too easy to forget to add the authorization call back in. This test should help you spot those cases where you miss it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment