Search code examples
c#restbasic-authentication

Calling a rest api with username and password - how to


I am new to rest api's and calling them via .NET

I have an api: https://sub.domain.com/api/operations?param=value&param2=value

The notes for the api say that to authorize I need to use the basic access authentication - how do I do that?

I currently have this code:

        WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
        req.Method = "GET";
        //req.Credentials = new NetworkCredential("username", "password");
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

However I get a 401 unauthorized error.

What am I missing, how do I form api calls using the basic access auth?


Solution

  • If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

        WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
        req.Method = "GET";
        req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
        //req.Credentials = new NetworkCredential("username", "password");
        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
    

    Replacing "username" and "password" with the correct values, of course.