Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Passport API: Retrieve Authenticated Token

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.

like image 841
Paul Hermans Avatar asked Oct 10 '17 18:10

Paul Hermans


1 Answers

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();
like image 176
ElChupacabra Avatar answered Oct 20 '22 12:10

ElChupacabra