0

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?

sergtk
  • 10,714
  • 15
  • 75
  • 130

1 Answers1

1

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

  • This is exactly how I handle this, but I am looking for the simpler way. .NET already redirect automatically, I just want to ask it not to strip the Authorization header. – sergtk Sep 21 '22 at 14:27
  • 1
    I've updated the answer, there's someone who had a similar question, but since you already implemented the manual solution you could just make it an extension method for the httpclient/webclient – Arturo Aguilar Sep 21 '22 at 14:31