I’ve created a new connected app in my dev account. I’ve created a JWT via private key and certificate. Now i’ve run into this error:
{"error":"invalid_grant","error_description":"user hasn't approved this consumer"}
After doing a little research I found a solution:
A JWT OAuth 2.0 bearer assertion request looks at all the previous approvals for the user that include a refresh_token. If matching approvals are found, the values of the approved scopes are combined and an access_token is issued (with “token_type” value “Bearer”). If no previous approvals included a refresh_token, no approved scopes are available, and the request fails as unauthorized.
From the Salesforce OAuth JWT Flow documentation
This tipped me off to check my assertion creation function. I noticed that I was using an username env var that I forgot to set. I set this and it started working.
Here’s a look at an example assertion function in PHP:
function create_assertion()
{
$signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
$keychain = new \Lcobucci\JWT\Signer\Keychain();
$builder = new \Lcobucci\JWT\Builder();
$token = $builder->setIssuer(env('CONSUMER_KEY'))
->setAudience(env('LOGIN_URL'))
->setExpiration(strval(time() + (5 * 60)))
->setSubject(env('USERNAME'))
->sign($signer, $keychain->getPrivateKey(file_get_contents(__DIR__ . '/' . env("PK_FILE"))))->getToken();
return $token->__toString();
}
I hope this also fixes your errors. Please comment below and let me know. Also if this was helpful please share on your social media.
