jwt-auth: Token provides wrong user
I created 2 accounts with different email addresses and passwords. I have a HTTP request that sends the token (stored in local storage after signin) like this:
http://apiurl/api/projects/getProjects?token=tokenString
Inside the method, I used the following line to retrieve the authenticated user based on the token:
$authenticatedUser = JWTAuth::parseToken()->authenticate();
This retrieves the email address for the first account I created, even if I sign in on the second account. For each account the token in the request is different but the authenticatedUser is for the same account every time.
This only ever happens for one specific account, where it thinks I am logged in as a different user. If I remove all my users from the database and create some new accounts, then one of them will have this same issue.
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 5
- Comments: 19
Had the same issue with mine too. Apparently looking at the payload using JWTAuth::payload(), the “sub” claim was null. The sub claim is the value which contains the user id that matches the user primary key in the database. Since it was null, Laravel picked the first value that existed in the Database. First you need to fix this by adding
public function getKey(){ return $this->ID; }In your user Model file.
Also make sure you set getJWTIdentifier like this
/** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ public function getJWTIdentifier() { return $this->getKey(); }see Documentation
Now if you check the payload using JWTAuth::payload() it should contain a value for “sub” which will be the primary key for the authenticated user.
But mostly likely you’ll get an error like this Column not found: 1054 Unknown column ‘’ in ‘where clause’ (SQL: select * from … when you try to access a protected route
This is because in Illuminate\Auth\EloquentUserProvider->retrieveById, Laravel tries to get the getAuthIdentifierName from the model but it doesn’t exist. so you need to set the getAuthIdentifierName to the name of the primary Key field in your user Model file like this
public function getAuthIdentifierName() { return 'ID'; }Or you could set it in the config/jwt.php file and get if from the provider/guard whichever suits your coding style. Personally i prefer the simple version above
Hope this helps