JWT Error – user hasn’t approved this consumer

I am trying to implement the OAuth 2.0 JWT Bearer Token Flow on my node.js app using these instructions, but I’m unable to authenticate successfully, getting this error:

{"error":"invalid_grant","error_description":"user hasn't approved this consumer"}

Details:

1) All users may self-authorize

2) I followed this answer, which states that I need to login first myself.

so I opened the following link using my browser: https://login.salesforce.com/services/oauth2/authorize?response_type=token&client_id=my_client_id&redirect_uri=https://login.salesforce.com/services/oauth2/success

and authenticated, I was then redirected to https://login.salesforce.com/services/oauth2/success and got the following response in the URL:
https://login.salesforce.com/services/oauth2/success#access_token=my_access_token&instance_url=https%3A%2F%2Fmyorg.my.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D1t0000gdfEA2%2F0051t000003gdfGIAAY&issued_at=1564389252266&signature=gdfgdfMa8SYkZu6Rn6K4iY%3D&scope=full&token_type=Bearer

3) OAuth Scopes includes:

Full Access

4) The redirect_uri used in the auth call matchs the callback uri registered for my app

Here’s my code to authenticate:

function jwtLogin(){
    const jsforce = require('jsforce');
    const jwt = require("salesforce-jwt-bearer-token-flow");

    // create the connection to the org
    let conn = new jsforce.Connection();

    // load the private key for the token
    let privateKey = require('fs').readFileSync('./certificates/server.key', 'utf8');

    jwt.getToken({
      iss: 'my_Consumer_Key',
      sub: 'my_username',
      aud: 'https://login.salesforce.com',
      privateKey: privateKey
    }, function(err, response) {
        if (err) {
          console.error('error is: '+JSON.stringify(err));
        } else {
          conn.initialize({
            instanceUrl: response.instance_url,
            accessToken: response.access_token
          });
          console.log('Successfully connected to Org');
        }
      }
    );

    module.exports = conn;     
}

Under Login History, I see the following line: Failed: Not approved

What am I missing?

Answer

This was a policy issue related to Permitted Users under the Connected App, once I changed it from
‘All users may self-authorize’ to ‘Admin approved users are pre-authorized’ issue was resolved.

Attribution
Source : Link , Question Author : Json , Answer Author : Json

Leave a Comment