HttpWebRequest passing Authentication Bearer token on redirect

Viewed 18

When doing HTTP requests I specify the OAuth2 token in my code in the following way:

WebClient webClient = ...;
webClient.Headers.Add("Authorization", $"Bearer {accessToken}");

But when uri is redirect one, then following request failured, because Authorization header is stipped on redirect:

HttpWebRequest request = (HttpWebRequest)webClient.GetWebRequest(uri); // public method in derived class

It is possible to disable AllowAutoRedirect and set it to false, and then manually handle redirects.

Is it a simpler way to handle redirects avoiding manual handling, and preserve access token?

1 Answers

Yes, you can set AllowAutoRedirect to False, and read the location redirect from the headers and make subsequent requests.

They key is to catch the redirect response starting with 3xx and then parse the location header.

If you want to follow the redirect take a look at this SO issue. issue

Related