9

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.

3
  • You should be able to look up the token, user_id and client_id in the oauth_access_tokens table. Check out this discussion, too: laracasts.com/discuss/channels/laravel/passport-rest-makeauth Commented Oct 10, 2017 at 18:39
  • 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. Commented Oct 10, 2017 at 18:42
  • @ElChupacabra Yes that works! Thanks! Can you put this as answer to the question? Commented Oct 10, 2017 at 19:54

1 Answer 1

16

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();
Sign up to request clarification or add additional context in comments.

3 Comments

This answer is pretty good, but can you please tell me exactly how you linked the OauthAccessToken model to the table, or is a trait you can use? Thank you man!
It's automatically linked if the class name is exact the same as database table. The only difference is that in php you use CamelCase instead of underscored.
Hello thank you for this just a quick question so how do i get the actual token this is my result ``` [ { "id": 825786976, "user_id": 1, "client_id": 1, "name": "admin", "scopes": "[]", "revoked": 0, "created_at": "2022-02-26T16:58:28.000000Z", "updated_at": "2022-02-26T16:58:28.000000Z", "expires_at": "2023-02-26 16:58:28" } ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.