Click here to Skip to main content
15,886,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi i am trying to call a external rest api which has authentication as username and password. i able to write code till how to call a authentication less api but now when i want to pass username and password i am struck.

This is my code

What I have tried:

C#
public static string username = "xxx";
public static string password = "xxx";
public static string uri = "https://1.1.1.1/x/x";<


webrequest req = webrequest.create(uri);
req.method = "GET";
httpwebresponse res = null;
res = (httpwebresponse)req.getresponse();

string resu = null;

using (stream stm = res.getresponsestream())
{
streamreader sr = new streamreader(stm);
resu = sr.readtoend();
sr.close();
}
}
Posted
Updated 1-Dec-21 3:14am
Comments
Richard Deeming 1-Dec-21 8:52am    
That depends entirely on how the API expects you to pass the credentials. Since we don't know which API you're calling, we have no idea how they expect you to pass the credentials. Consult their documentation, or contact their support team.
Member 13998042 1-Dec-21 8:55am    
its a basic authentication where in postman we pass username and password likewise

1 solution

For "Basic" authentication, you just need to set the appropriate header, as shown in this SO thread[^]:
C#
var encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
byte[] headerBytes = encoding.GetBytes(username + ":" + password);
string headerValue = Convert.ToBase64String(headerBytes);
req.Headers.Add("Authorization", "Basic " + encoded);
Basic authentication scheme | HTTP authentication - HTTP | MDN[^]
rfc7617[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900