Salesforce Access Token Bad Request

I want to generate a Salesforce access token programmatically using the method below, “GetAccessTokenAsync”. I’ll then pass the token to my various methods that retrieve rows using GET.

(1) When I POST this from Postman, I get a 200 OK and an access token is returned.
https://ami-staging.my.salesforce.com/services/oauth2/token?grant_type=password&client_id=&client_secret=&username=myorg@force.com&password=

(2) I used the </> icon on Postman to generate code in c#. When I run that method from Visual Studio, I get a 400 Bad Request. I’ve triple-checked all my strings (client_id, client_secret, username, password) to make sure that what I’m using in Postman is identical to the inputs below. I don’t think the problem is the strings.

I would appreciate suggestions that anyone might have. Thank you!

public static async Task<string> GetAccessTokenAsync()
{
    var client = new HttpClient();

    var request = new HttpRequestMessage(HttpMethod.Post,
	"https://ami-staging.my.salesforce.com/services/oauth2/token?grant_type=password&" +
	"client_id=myid&" +
	"client_secret=mysecret&" +
	"username=myorg@force.com&" +
	"password=mypassword");

    var collection = new List<KeyValuePair<string, string>>();
    collection.Add(new("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"));
    collection.Add(new("assertion", ""));

    var content = new FormUrlEncodedContent(collection);
    request.Content = content;

    var response = await client.SendAsync(request);

    response.EnsureSuccessStatusCode();

    await response.Content.ReadAsStringAsync();

    return "test";
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.