Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

c# - GetAsync using Basic Authentication even though I specify Bearer

I have the below GetAsync which I'm trying to authenticate with a bearer token but I get a 403 response. When I look at the request headers I can see Authorization: Basic YWJjOmRlZg==

var client = new HttpClient(handler)
{
    BaseAddress = new Uri("https://api.myendpoint.com/v2/")
};
client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", "token");
var httpResponseMessage = _myclient.GetAsync("instruments?country=US&type=BOND").GetAwaiter().GetResult();

The token is valid. I confirmed that with Postman. I also hardcoded it into AuthenticationHeaderValue to ensure I had the correct token. I guess I assumed I was passing the bearer token incorrectly.

How do I get it to use Bearer authentication?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Passing token to header (I am currently using this):

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

or something like this:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...