jwt-auth: Deleted Users Causing Errors

January 30 2017, 5:53pm

Recently ran into a situation using jwt-auth for Laravel where deleted users were causing errors because after deleting the user the auth token was still valid in redis, whoever the user no longer existed in the database, so when there was any calls to $auth->user() or Auth::user() it would error out when trying to make calls against that user object because false is returned.

When a user was deleted we should call $jwtAuth->invalidate($token) for that user but that's not gonna help us now that we have a bunch of other users who were deleted or if you need to delete users from DB manually.

I didn't want to have to check that calls to the Auth guard would not return false all over the place where I used the auth guard, so I looked for another answer.

Solution

Well it turns out others must have come across this issue as well because a merged PR to the project added a function to JWTGuard to throw a UserNotDefinedException if the user is not found. They didn't replace what happens when the user() function is called in order to stay compatible with how laravel's default guard returns false if not found. So use userOrFail() any place you normally would have used user.