DEV Community

Pike Msonda
Pike Msonda

Posted on

How to retrieve tokenID from acess_token (Personal Access Token)

The gist

I am assuming you are already aware of how Laravel/Passport works.

Let's say you have generated a lot of personal access tokens that are associated to a specific user and you would like to delete a specific token without having to delete all the other tokens.

I am sure you are thinking, I will just get the token associated with the user using the relationship already defined if you use the HasAPiKeys from Laravel/Passport.

That is well and good if the user is also serving as a client in your api. But if it is just a Personal Access Token you can't retrieve the access token of created for that user (unless you get it from the header, but that won't really help solve your problem since you still have to know which token matches a particular ID) because of how Laravel/Passport is designed.

What to do?

To bypass this scenario you can use the following code below.

Forgive me for using an image instead of embedded code 😅. Let me know below if this helps.

Alt Text

Thanks to

mstfakdgn image

I was able to figure it out.

Discussion (6)

Collapse
tr1pp0 profile image
Alberto Peripolli

Laravel 8/9

use Lcobucci\JWT\Parser as JwtParser;

app(JwtParser::class)->parse($token)->claims()->get('jti');

Collapse
skebard profile image
Antonio Jorda

If you are using the auth middleware then you can access the Token object and from that object get the id of the token
$id = $request->user()->token()->id;

Collapse
khaireddines profile image
Acewings • Edited on

laravel = 8,
Lcobucci\JWT = 3.4
solution is =>
dev-to-uploads.s3.amazonaws.com/up...

Collapse
daniyaljavani profile image
Daniyal Javani

Thank you, it worked for Laravel 8.
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token\Parser;

(new Parser(new JoseEncoder()))->parse($token)->claims()->all()['jti']

Collapse
mohamednourdine profile image
Mohamed Nourdine

Thanks you dude. I was really thinking of how to get this done. I had crazy nights trying to figure it out. Thanks you.

Collapse
mstfakdgn profile image
mstfakdgn

Thanks bro