"[{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"}]"

I reviewed the other questions posted but no answers helped. I am using grant type "password".

On my authenticate call I get this back (values changed to protect the innocent):

  "access_token": "00BLARDEBLAR..",
  "instance_url": "https://blar.salesforce.com",
  "id": "https://test.salesforce.com/id/00BLAH/00BLHABLHA",
  "token_type": "Bearer",
  "issued_at": "1611009241343",
  "signature": "A99SigAmature"

Here's how i'm trying to use it:

string response = message.Content.ReadAsStringAsync().Result;
JObject obj = JObject.Parse(response);

// I have confirmed these values match the response.
string AuthToken = (string)obj["access_token"];
string ServiceUrl = (string)obj["instance_url"];

// versionEndpoint = "/services/data/v50.0"
string EndPointURL = ServiceUrl + login.versionEndpoint;

content = new FormUrlEncodedContent(new Dictionary<string, string>
    {"Authorization", "Bearer " + AuthToken},
    {"X-PrettyPrint", "1"}

message = Client.PostAsync(EndPointURL + "/sobjects/", content).Result;
response = message.Content.ReadAsStringAsync().Result;

And this is when I get back:

"[{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"}]"

What am I missing? TIA


The way you're calling it, you're putting data into the body. You need to use the Headers attribute instead.

content = new FormUrlEncodedContent(new Dictionary<string, string>
{ // Whatever body elements you need goes here
content.DefaultRequestHeaders.Authorization = "Bearer " + AuthToken;

See also this question on Stack Overflow, which basically says the same thing.

  • Ah. Ok thanks. This makes sense. But now it's telling me System.InvalidOperationException: 'Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.' I'll poke around a bit. content is defined as HttpContent
    – flashsplat
    Jan 19 at 3:53
  • @flashsplat Looks like DefaultRequestHeaders.Authorization is the correct property here. See this answer on Stack Overflow.
    – sfdcfox
    Jan 19 at 10:23
  • Boom! That got me on the right track. Thank you. Got one more error after that saying I couldn't POST, so I switched to GET and now i'm cookin'! Thanks again!
    – flashsplat
    Jan 19 at 15:10
  • It won't let me upvote your answer do to my rep :(.
    – flashsplat
    Jan 19 at 15:11
  • @flashsplat You're welcome. I edited in the answer.
    – sfdcfox
    Jan 19 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.