Reputation: 1664
I am attempting to learn how to pass a JWT token from ReactJS to my PHP API. I have 2 functions currently: the authentication function to check the username and password and then generate and pass back a token. The generation part seems to work, but when I pass the token back in the Authorization Bearer, I can't get it to validate. I am using the Lcobucci\JWT library.
Here is my code:
public function attempt_login($input){
$time = time();
$token = (new Builder())->issuedBy('https://api.example.com')
->permittedFor('https://example.com')
->identifiedBy('4f1g23a12aa', true)
->issuedAt($time)
->canOnlyBeUsedAfter($time + 60)
->expiresAt($time + 3600)
->withClaim('uid',1)
->getToken();
return $token;
}
public function find($headers){
$auth = $headers['Authorization'];
if (preg_match('/Bearer\s(\S+)/', $auth, $matches)) {
$token = (new Parser())->parse((string) $matches[1]);
$data = new ValidationData();
$data->setIssuer('https://api.example.com');
$data->setAudience('https://example.com');
$data->setId('4f1g23a12aa');
dd($token->validate($data));
}else{
dd('nope');
}
}
When I dump and die, I always get false. I am 95% sure I am doing it all wrong, but can anyone help me figure this out?
Upvotes: 4
Views: 5483
Reputation: 2038
If you are checking for validity right away, you would need to change
canOnlyBeUsedAfter($time + 60)
to simply
canOnlyBeUsedAfter($time)
Otherwise you need to wait 60 seconds before it becomes valid.
Upvotes: 2