3 months ago

Deleting users Passport token on logout.

Posted 3 months ago by DocTolly


Thank you to the community for your continued support!

I am working on implementing API keys using Passport.

For now, the key will be consumed by a small app within my own front-end (for validating a user is logged in / can access the content). I am using Passport as it leaves room for expansion in the future.

When a user logs in, I issue them a new token using the authenticated function in the LoginController which, as we know, automatically gets fired after a user successfully logs in. (This works).

class LoginController .... {

    use AuthenticateUsers;

    protected function authenticated(Request $request, $user)
        $token = $user->createToken('userToken'.$user->id)->accessToken;
    //more code

When the user logs out, I want to revoke this access token.

I can see that I can override the method ::loggedOut($request), however I can't access the user details in this method as the user has been logged out, therefore $request->user() is null!

As with most problems I come across in Laravel - there is probably a simple solution that I don't know about yet! Does anyone have any ideas?

At the moment, the only solution I have thought of is creating a new logout method in the LoginController which deletes the token and then delegates to the logout() method in the Authenticable trait of the Login controller.

class LoginController ....... {

    use AuthenticateUsers;

    public function deleteTokenThenLogout(Request $request)
    //Delete Token here

    //Delegate to the actual default logout method in the AuthenticateUsers trait 
        return $this->logout($request);

Although at first glance, this seems sensible. It's actually really messy, because in order to declare a logout route which points to this method in the controller. I would have to delete Auth::routes from my routes file, and therefore manually declare all the other authentication routes, individually. (On reflection it would be nice if the Auth::routes() helper had an 'except' option!)

Does anybody have any advice on how to cleanly delete the token on logout please?

Am I even going around using Passport / API keys in the right manner?

Please sign in or create an account to participate in this conversation.