For a Jwt token:
HttpResponseMessage responseMsg
var token = responseMsg.Content?
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
Used to authorize a post request, like this:
client.BaseAddress = new Uri("https://...");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
I'm getting this error:
Bearer was not authenticated. Failure message: No SecurityTokenValidator available for token: "eyJ..."
After a closer look to the request in postman I discovered that the issue are the "" added to the token on the header:
That is why I add the token like this:
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Replace("\"", "")}");
And this works, but it seems "dirty" to me. Is there a better way?
You should deserialize the response object so that you can use it as a string:
HttpResponseMessage responseMsg
var response = responseMsg.Content?
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
var token = JsonConvert.DeserializeObject<string>(response);
return token;
Now the string is ready to be included in the header as a bearer token.