One of the advantages of using JSON Web Tokens as the transport for your authentication layer (such as OAuth) is that you can attach additional data in the form of public claims (see the relevant RFC for more details). However, Laravel Passport does not expose any way to attach such a claim, making it up to us to implement such a solution. This blog post will guide you through how to set that up in the easiest way possible.
To understand how this will be implemented we first need to have a brief look at how Laravel Passport issues tokens.
Passport uses an
AccessToken class responsible for converting the data within the token into its final string form. Thus, in order to change what data is placed in our token, we need to modify how the
AccessToken class generates the token. This
AccessToken then gets returned to the OAuth Server by an
AccessTokenRepository, so we also need to replace the repository to return our own implementation of the
AccessToken class will do the heavy lifting for us – we will override the
convertToJWT method to also attach the traits, and in our case also clean up and separate some of Laravel’s own code:
In this implementation, we create a new method,
getToken to set the claims and retrieve the actual
The important part is our
$customClaims variable. This is where you would retrieve the claims, however you decided to set them. For example, you could use a singleton to store the claims, or store it on the user model and retrieve that, retrieving the ID with
$this->getUserIdentifier() – the choice is yours.
With this done, also create a new
Make sure that the
AccessToken instance returned is of the class we created above.
Last but not least, add the following to your
AuthServiceProvider, or another appropriate service provider:
That’s it – we replaced two classes, and added a container binding, and now you can attach custom claims to your Passport JWTs. This is a simple and effective way to attach additional data about your users (for example billing information like trial end date, or email address and name).