tags:

views:

1349

answers:

2

I'm trying to use HTTPWebRequest to access a web service, and am having problems passing credentials in, see code below. I can see the credentials object, nc, being built in the debugger, and also in the assignment to request.Credentials, but when I get to the last line of code it faults with a not authorized error message. I've had our server folks watch the request on the server, and there are no credentials being passed. Am I doing something wrong with the Credentials object, or is there something I need to do that I'm not doing here?

    Uri requestUri = null;
    Uri.TryCreate("https://mywebserver/webpage"), 
        UriKind.Absolute, out requestUri);

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create
        (requestUri);

    NetworkCredential nc =
        new NetworkCredential("user", "password");

    request.Credentials = nc;

    request.Method = WebRequestMethods.Http.Get;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
A: 

What form of security is the target server implementing? If you just paste the URL in your browser does it work OK? If it works, what is the browser posting that your app is not?

You're not setting request.UseDefaultCredentials anywhere... ?

Bryan
It's an https site so it is using SSL. I just found out yesterday that the NetworkCredential class does not support SSL, and that is causing my problem. Does request.UseDefaultCredentials pass the users own credentials rather than using the NetworkCredentials class to pass in credentials?
Russ Clark
I believe it will pass the credentials of whatever user account is running the ASP.NET process... or possibly the credentials of the logged in user if you are using Windows authentication. Try a search for "SSL HttpWebRequest", I'm sure this is possible.
Bryan
A: 

Microsoft Premier Support finally helped me solve this problem by using the CredentialCache class to add the Credentials and the "Basic" authorization:

    NetworkCredential nc =
        new NetworkCredential(GetSetting("username"), GetSetting("password"));
    CredentialCache cache = new CredentialCache();

    cache.Add(requestUri, "Basic", nc);

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
Russ Clark