how to add a base64 encoded authentication string to my webclient in C# ?

5,553 views
Skip to first unread message

Sergey Gnedin

unread,
Oct 21, 2011, 11:07:28 AM10/21/11
to DevTargetProcess, contes.a...@yahoo.com
Can you please show me how to add a base64 encoded authentication
string to my webclient in C# ? I can't find an example anywhere..

Alex Fomin

unread,
Oct 21, 2011, 11:23:41 AM10/21/11
to devtarge...@googlegroups.com, contes.a...@yahoo.com
Don't sure what are you talking about, but assume that you want to use http basic authentication for REST Api. If so, you have no need to encode your login/password by yourself, just set the corresponding values to webclient.Credentials property:

using(var client = new WebClient())
{
    client.Credentials = new NetworkCredential("admin","admin");
    var response =  client.DownloadString("http://localhost/TargetProcess/api/v1/Projects?include=[Name]");
}

The same is applicable for HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/TargetProcess/api/v1/Projects?include=[Name]");
request.Credentials = new NetworkCredential("admin","admin");


Thanks,
Alex, TP Team

deejayundoo

unread,
Oct 21, 2011, 11:26:25 AM10/21/11
to DevTargetProcess
Hi Alex,

I know about the normal authentication with username and password, but
i really want to do it with base64.

Do you have any idea how can that be accomplished ?

Alex

Alex Fomin

unread,
Oct 21, 2011, 11:32:49 AM10/21/11
to devtarge...@googlegroups.com
WebClient will use proper authentication mode in response of HTTP 401 from TargetProcess, so, actually, you do not need to perform manual encoding. But you can use the following code snippet to do it by hands:

string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("basic ", base64);
request
.Headers.Add("Authorization", authorization);

Thanks,
Alex TP Team

deejayundoo

unread,
Oct 21, 2011, 11:37:20 AM10/21/11
to DevTargetProcess
Ok, thanks a lot!
Reply all
Reply to author
Forward
0 new messages