Sample C# API authentication code

Help for Z-Command related issues only
admin
Site Admin
Posts: 50
Joined: Sun Dec 14, 2014 2:05 pm
Location: Washington
Contact:

Sample C# API authentication code

Postby admin » Thu Sep 10, 2015 7:08 pm

/// <summary>
/// Main class.
/// Author: Sola Abiodun; sola_at_intulon.com
/// </summary>
using System;
using System.Net;
using System.Xml.Linq;
using System.Linq;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

namespace ExpediaBuildMonitor
{
class MainClass
{
const string zcommandUrl = "http://192.168.2.160";

public static int Main (string[] args)
{
WebClient ZCommandWebClient = GetAuthenticatedWebClient ();

var response = ZCommandWebClient.DownloadString(string.Format("{0}/api/devices", zcommandUrl));

Console.WriteLine(string.Format("Response: {0}", response));
Console.ReadLine();

return 0;

}

private static WebClient GetAuthenticatedWebClient(){
JavaScriptSerializer js = new JavaScriptSerializer();
WebClient webClient = new WebClient ();
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");

var form = js.Serialize (new {Username = "admin", Password = "admin"});
var response = webClient.UploadString(zcommandUrl + "/api/tokenauth", form);
var obj = JObject.Parse (response);

webClient = createAuthorizedWebClient(obj["responseObject"].ToString());
return webClient;
}

private static WebClient createAuthorizedWebClient(string token){
//Console.WriteLine ("Creating auth with token: " + token);

WebClient webClient = new System.Net.WebClient ();
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webClient.Headers.Add(HttpRequestHeader.Authorization, "Token " + token);
return webClient;
}

}
}


The entire project is attached to this post.
zc auth sample.zip
(187.63 KiB) Downloaded 95 times

merthsoft
Posts: 6
Joined: Wed Oct 14, 2015 5:14 pm

Re: Sample C# API authentication code

Postby merthsoft » Wed Oct 21, 2015 6:49 am

Thanks for this! I was struggling a bit until I found this and noticed this line:
webClient.Headers.Set(HttpRequestHeader.UserAgent, "zcommand");
I didn't see anything in the documentation that said I had to set a user agent, but when I did this, it started working!

admin
Site Admin
Posts: 50
Joined: Sun Dec 14, 2014 2:05 pm
Location: Washington
Contact:

Re: Sample C# API authentication code

Postby admin » Wed Oct 21, 2015 8:23 pm

Yes, the user-agent is required.
We will make this clearer in the documentation.


Return to “Z-Command help”

Who is online

Users browsing this forum: No registered users and 1 guest

cron