Using policies in Lumen

Jeffrey van Rossum
Mar 16, 2019 · 2 min read
Image for post
Image for post

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.

Check Gist

Checking if the user is authorized

Now that the policy is in place, we can implement the check in our `PostController`.

Check Gist

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.

Check gist

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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store