Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 771
andrewb Avatar asked Aug 21 '13 00:08

andrewb


People also ask

How do I pass username and password to a REST API?

The client must create a POST call and pass the user name, password, and authString in the Request headers using the /x-www-form-urlencoded content type. The AR System server then performs the normal authentication mechanisms to validate the credentials.

How do I pass a username and password in REST API in Postman?

Now, let us select the option Basic Auth as the Authorization type, following which the Username and Password fields get displayed. Enter the postman for the Username and password for the Password field. Then, click on Send.

How does REST API validate username and password?

1) Configure the API Request URL and Authorization header as 'Basic Auth, then mention FortiAuthenticator admin name and password as 'REST API' key received by mail. 2) Configure the POST data in JSON format.

How do I pass username and password in REST API using curl?

For example, if a website has protected content curl allows you to pass authentication credentials. To do so use the following syntax: curl --user "USERNAME:PASSWORD" https://www.domain.com . “USERNAME” must be replaced with your actual username in quotes.


3 Answers

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.

like image 144
Adrian Avatar answered Oct 11 '22 01:10

Adrian


You can also use the RestSharp library for example

var userName = "myuser"; var password = "mypassword"; var host = "170.170.170.170:333"; var client = new RestClient("https://" + host + "/method1");             client.Authenticator = new HttpBasicAuthenticator(userName, password);             var request = new RestRequest(Method.POST);  request.AddHeader("Accept", "application/json"); request.AddHeader("Cache-Control", "no-cache"); request.AddHeader("Content-Type", "application/json");             request.AddParameter("application/json","{}",ParameterType.RequestBody); IRestResponse response = client.Execute(request); 
like image 36
orellabac Avatar answered Oct 11 '22 02:10

orellabac


Here is the solution for Rest API

class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}
like image 31
Pramod Lawate Avatar answered Oct 11 '22 03:10

Pramod Lawate