Search code examples
azure-functionspostmansalesforce

Cannot access Salesforce api from Postman


I am trying to test an application (Azure function) that needs to send an http request to a Salesforce api. This works with unit testing in both Visual Studio and Azure DevOps pipeline. But when I try to test the Azure function using Postman, I get an error: {"error":"invalid_grant","error_description":"authentication failure"}

I tried to set the connected app's "IP Restrictions" to "Relax IP restrictions", but it did not help.

Here is my code:

_httpClient = new HttpClient();

HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    {"grant_type", "password"},
    {"client_id", sfClientId},
    {"client_secret", sfClientSecret},
    {"username", sfUserName},
    {"password", $"{sfPassword}{sfToken}"}
});

message = _httpClient.PostAsync(LoginEndpoint, content).Result;

response = message.Content.ReadAsStringAsync().Result;

Solution

  • What do you see in your user's login history in Salesforce setup. You might need to append "security token" to password (this is separate from OAuth key/secred). Or add your IP to Setup -> Network Access.

    Edit:

    If it correctly appends security token you don't need to add your IP in Setup -> Network access, cool. I'm not familiar with that syntax you're using. Does this automatically urlencode parameters and set the Content-Type correctly?

    Can you try with a raw boring handmade http?

    POST /services/oauth2/token HTTP/1.1
    Host: test.salesforce.com
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=password&client_id=3MVG9redacted&client_secret=3B8AE4C8ADredacted&username=user.name%40example.com.introccp%09&password=Hunter2PlusToken
    

    sample Postman POST login to sandbox

    (note that I have %40 but if you use Postman's x-www-form-urlencoded option you should be able to enter it normally)

    If it still throws errors, try to eliminate the token. Look at login history, there will be your IP. Add it to Setup -> Network Access.

    Something like that