Laravel Passport API: Retrieve Authenticated Token

Paul Hermans picture Paul Hermans · Oct 10, 2017 · Viewed 9.9k times · Source

Situation

I'm using Laravel Passport API to communicate between Laravel and external "agents" via Personal Access Tokens: https://laravel.com/docs/5.5/passport#personal-access-tokens

You can create multiple tokens per user.

Authentication works and I can retrieve the User via Auth::User()

Question

How can I check which token is used?

Background

I want to use different tokens for different "agents" for the same user and I need to know which token is used to see who is connecting.

Answer

ElChupacabra picture ElChupacabra · Oct 11, 2017

You can use:

Auth::user()->token()

function to get token model. This is object of class "Token extends Model" so you should be able to use it like any other model.

In addition in my project I also have that model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class OauthAccessToken extends Model
{
    //
}

and relation:

class User extends Authenticatable
{
    //...
    public function accessTokens()
    {
        return $this->hasMany('App\OauthAccessToken');
    }
}

So I can simply access all tokens and for example delete them:

Auth::user()->accessTokens()->delete();