Basic Authentication over redirection

2019-07-22 13:06发布

问题:

I have a webservice that needs a Basic Authentication header. However, when I call it using

   var header = "Authorization: Basic " + 
                CreateBasicHttpAuthenticationHeader(login, password);
   webRequest.Headers.Add(header);
   var webResponse = (HttpWebResponse)webRequest.GetResponse();

It returns a 303 - See Other:

POST https://myservice/rates HTTP/1.1
Authorization: Basic QXZ...NjY=
Content-Type: application/x-content
X-API-Version: 1.1
If-Unmodified-Since: Mon, 23 Sep 2013 08:32:27 GMT
User-Agent: UserAgent

Response:

HTTP/1.1 303 See Other
Date: Mon, 23 Sep 2013 08:30:57 GMT
X-Opaque-ID: q8nxxxxc
Location: https://myservice/rates 
Content-Length: 0

.Net then automatically sends a GET request to the new location:

GET https://myservice/rates HTTP/1.1
Content-Type: application/x-content
X-API-Version: 1.1
If-Unmodified-Since: Mon, 23 Sep 2013 08:32:27 GMT
User-Agent: UserAgent

But does not send the Authorization header this time. Do you know a way to tell it to send all headers, on all calls? Should I tell it not to follow the content?

回答1:

You have to deactivate the AllowRedirect property of your HttpRequest.

Then you have to build you own redirection system with basic auth headers.

This is not wonderful, but otherwise the .Net framework drops your header when redirecting.