Jonathan Kittell
Jonathan Kittell

Reputation: 7493

How to get xml from Rest Service using Basic Authentication in C#

I am attempting to get an xml file from a website that uses an API. In the documentation it says to use "Basic Authentication". Others have posted on this site that you can send the username and password credentials to the server unchallenged.

Using HTTP Authentication with a C# WebRequest

Where do you put the username and password? I keep getting a 401 error. It appears that the server is getting the request but is not authorizing the program to get the file.

According to Microsoft you can use the CredentialsCache but in the example I don't see where you can store the actual usernames and passwords.

http://msdn.microsoft.com/en-us/library/47as68k4(v=vs.110).aspx

namespace XmlAuthTest
{
class Program
{
    static void Main(string[] args)
    {
        var request = WebRequest.Create("https://www.host.com/rest-1/Data/Test/somedata");
        SetBasicAuthHeader(request, username, password);

        var response = request.GetResponse();

    }

    public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Headers["Authorization"] = "Basic" + authInfo;
    }


    public static string password { get; set; }

    public static string username { get; set; }
}

}

My goal is to return an xml file from the given URL of the web service.

Upvotes: 0

Views: 3410

Answers (1)

L.B
L.B

Reputation: 116178

Use NetworkCredential

request.Credentials = new NetworkCredential(username, password);

Upvotes: 3

Related Questions