Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Authorization Header to Web Reference

I'm attempting to make requests to a client's web service (I don't know the underlying platform at the client). I've consumed the client's WSDL in Visual Studio 2010 using "Add Web Reference" and generated my proxy class (called "ContactService").

I now need to add an authorization header like the one below to my service request.

Header=Authorization & Value=Basic 12345678901234567890

(the "123456..." value above is just placeholder)

ContactService service = new ContactService();

//not sure if this is the right way - it's not working
WebClient client = new WebClient();
client.Headers.Add("Authorization", "Basic 12345678901234567890");            
service.Credentials = client.Credentials;

int contactKey = null;
try
{                
   contactKey = service.CreateContact("ABC", emailAddress, firstName, lastName, null);
}

What is the proper way of adding the authorization header to the service request?

Thank you!

like image 584
Mike Avatar asked Jan 23 '13 20:01

Mike


People also ask

How do I send Authorization header in URL?

It is indeed not possible to pass the username and password via query parameters in standard HTTP auth. Instead, you use a special URL format, like this: http://username:[email protected]/ -- this sends the credentials in the standard HTTP "Authorization" header.

How do I add Authorization header in GET request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

How do I create an Authorization header?

The command requires the valid user name and password (or API token) in the application to which you want to connect, and it encodes the credentials with base64. In the Authorization Header field, you enter the word "Basic" (which is the Authorization header type), a space, and then the base64-encoded credentials.


1 Answers

The above response was on the right track, but it just had to be in a different location.

I added this to my web reference proxy class that .Net generated:

protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(uri);            
        req.Headers.Add(HttpRequestHeader.Authorization,
                "Basic " + "12345678901234567890");

        return req;
    }

A Web Reference proxy class extends System.Web.Services.Protocols.SoapHttpClientProtocol. This class contains a call to System.Net.WebRequest.GetWebRequest(Uri uri). A WebRequest allow us to set specific headers on the request when the proxy class' methods are invoked.

Thanks for your help!

like image 50
Mike Avatar answered Sep 16 '22 14:09

Mike