Lumen-jwt is a great library that easily adds JavaScript Web Token (JWT) authentication to any Lumen application. I recently had the opportunity to submit my second pull request to the project, allowing user accounts to be uniquely identified via fields other than id
, which was previously the only option. (As of this writing the PR has been approved, but not yet merged.)
There is now a key called JWT_ID_FIELD
that can optionally be added to a project’s .env
file to specify the name of the field that should be used to look up and uniquely identify users. The default is of course id
, so any existing applications that don’t specify a value will continue to work without any changes.
So if the primary key field in your user table is user_id
, username
, or indeed anything else, then using lumen-jwt is straightforward:
1 2 |
# Specify accounts should be looked up by username JWT_ID_FIELD=username |
My original use case for this feature was to allow using hashids to identify users without exposing database ids publicly. If an alternative unique id field such as this is persisted in your user model then you’re already done.
Another option is for the hashids to be computed properties, calculated via Eloquent mutators whenever a user instance is loaded. The down side to this approach is that there isn’t a straightforward method for retrieving the model corresponding to a given hashid. Instead, you can write a custom user provider to decode the hashid before retrieving the user―that will be the subject of a future post.