Using policies in Lumen
Recently I’ve been using Lumen, basically a micro version of Laravel, to set up a REST API. I have been using the jwt-auth package from tymondesigns to be able to facilitate token based authentication.
In Laravel there is a concept called Policies with which you can authorize certain user actions. For example, you might set up a policy to check if a user is authorized to update a post.
In Lumen, registering a policy works a little different compared to Laravel. Since it wasn’t immediately clear how I needed to go about this, I thought I’d share a quick example after I got it working in case others run into this too.
This article will not explain how to set up token based authentication, setting up routes etc.. I am assuming that this is set up already.
Creating a policy
In the app
folder, let’s create a folder called policies. Within this folder we create a file called PostPolicy. This file is going to contain a class like below.
namespace App\Policies; use App\User; use App\Post; class PostPolicy { public function update(User $user, Post $post) { return $post->user_id === $user->id; } }
Checking if the user is authorized
Now that the policy is in place, we can implement the check in our PostController
.
namespace App\Http\Controllers; use App\Post; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PostController extends Controller { public function update(Request $request, $id) { $post = Post::find($id); $this->authorize('update', $post); // The current user can update the blog post... } }
Register the policy
The final step, is to register the policy. Lumen needs be able to map the authorize-check with corresponding policy. We can register the policy in the AuthServiceProvider.php file (app/Providers). You register the policy in the boot-function of the class.
namespace App\Providers; use App\Post as Post; use App\Policies\PostPolicy as PostPolicy; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; class AuthServiceProvider extends ServiceProvider { public function register() { // } public function boot() { Gate::policy('App\Post', 'App\Policies\PostPolicy'); $this->app['auth']->viaRequest('api', function ($request) { return app('auth')->setRequest($request)->user(); }); } }
Conclusion
If you now make a request to, assuming you’ve set up the needed routes for that, there will be a check to see if the current user is actually authorized to edit a post. The same process applies for delete, create etc.. Just add the needed method to the policy, and then you will be able to do $this->authorize('delete', $post).
I hope this helps anyone!