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.
Checking if the user is authorized
Now that the policy is in place, we can implement the check in our PostController.
namespaceApp\Http\Controllers;
useApp\Post;
useIlluminate\Http\Request;
useApp\Http\Controllers\Controller;
classPostControllerextendsController
{
publicfunctionupdate(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.
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).