{"error":"unsupported_grant_type","error_description":"grant type not supported"}

  • I am getting the below error when trying to call the HTTP POST using the Apex

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://ap5.salesforce.com/services/oauth2/token');
    request.setMethod('POST');
    
    request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
    request.setHeader('client_id','3MVG9d8..z.hDcPJZPXXXXXXXXXXXXXXXXXXX');
    request.setHeader('client_secret','XXXXXXXXXXXXXXXXXX');
    request.setHeader('username','XXXXXXXXXXXXXXXXXX');
    request.setHeader('password','XXXXXXXXXXXXXXXXXXXXXX');
    request.setHeader('grant_type','password');
    request.setHeader('callbackURL','https://ap5.salesforce.com/oauthcallback.html');
    
    request.setBody('');
    
    HttpResponse response = http.send(request);
    System.debug('Response :: '+response.getBody());
    

    And I get the error message.

    Response :: {"error":"unsupported_grant_type","error_description":"grant type not supported"}
    

    I am able to call successfully using REST/POSTMAN client and getting the access_token.

    Just a note, the `[apexrest]` tag is for when you are writing an `ApexClass` that will serve as a `@RestResource`, which does not appear to be the case here.

    See answer here for troubleshooting: https://salesforce.stackexchange.com/questions/172800/access-rest-service-oauth/172813?noredirect=1#comment260579_172813 - Also you do not need to provide the callback URL for the UN PW flow

    @user4567570 Since you seem to be new here, just wanted to point out that it is considered being a good citizen to accept an answer if it solve your issue. You are under no obligation to do so but it helps others find answer to similar questions and also shows your appreciation to to efforts towards the person who spent time providing you with the answer

  • Eric

    Eric Correct answer

    4 years ago

    Change:

    request.setEndpoint('https://ap5.salesforce.com/services/oauth2/token');
    

    to either Login or test depending on if in production or sandbox

    request.setEndpoint('https://[login | test].salesforce.com/services/oauth2/token');
    

    You also need to put the parameters in the body or as URL params and not header

    request.setBody(
          'grant_type=password' + 
          '&client_id=xxxx' + 
          '&client_secret=xx' + 
          '&username=xx' + 
          '&password=xx'
    );
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM