0

I'm trying to access my QuickBlox app and getting a token using the REST API.

My code looks like this: http://pastebin.com/rp2KLMp2

The request looks like this (sensitive info removed): application_id=xxxx&auth_key=xxxxxxxxxx&nonce=2851&timestamp=1389951758&signature=D481F13E87F47D4C17697EF9D2C8E25777E09079

I'm getting the error: The remote server returned an error: (422) Unprocessable Entity

What could be the problem?

Lasse O
  • 349
  • 1
  • 3
  • 13

3 Answers3

2
    public  string Timestamp()
    {
        long ticks = DateTime.UtcNow.Ticks - 
        DateTime.Parse("01/01/1970 00:00:00").Ticks;
        ticks /= 10000000;
        return ticks.ToString();
    }
    public  string Hash(string input, string key)
    {
        var encoding = new System.Text.ASCIIEncoding();
        byte[] keyByte = encoding.GetBytes(key);
        HMACSHA1 myhmacsha1 = new HMACSHA1(keyByte);
        byte[] byteArray = Encoding.ASCII.GetBytes(input);
        MemoryStream stream = new MemoryStream(byteArray);
        byte[] hashValue = myhmacsha1.ComputeHash(stream);
        return string.Join("", Array.ConvertAll(hashValue, b => b.ToString("x2")));
    }
    public string GetToken()
    {
        if (HttpContext.Current == null || String.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Cache["QuickBloxToken"])))
        {
        string url = "https://api.quickblox.com"; //ConfigurationManager.AppSettings["ChatUrl"].ToString();
        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url + "/session.xml");

        httpWReq.UserAgent = ".NET Framework Test Client";

        string application_id = System.Configuration.ConfigurationManager.AppSettings["QuickApplication_id"].ToString();
        string auth_key = System.Configuration.ConfigurationManager.AppSettings["QuickAuth_key"].ToString();
        string timestamp = Timestamp();
        string auth_secret = System.Configuration.ConfigurationManager.AppSettings["QuickAuth_secret"].ToString();

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "application_id=" + application_id;
        postData += "&auth_key=" + auth_key;


        Random rand = new Random();

        postData += "&nonce=" + rand.Next(1000, 9999);
        postData += "&timestamp=" + timestamp;
        string signature = Hash(postData, auth_secret);
        postData += "&signature=" + signature;
        byte[] data = encoding.GetBytes(postData);

        httpWReq.Method = "POST";

        httpWReq.ContentLength = data.Length;
        httpWReq.Headers["QuickBlox-REST-API-Version"] = "0.1.0";

        using (Stream stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(responseString);

        var nodes = xmlDoc.SelectNodes("session");
        string token = nodes[0].SelectSingleNode("token").InnerText;

        if (HttpContext.Current != null)
                HttpContext.Current.Cache.Add("QuickBloxToken", token, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 70, 0), System.Web.Caching.CacheItemPriority.Default, null);
            return token;
        }
        else
            return Convert.ToString(HttpContext.Current.Cache["QuickBloxToken"]);

    }
Sanjay Dwivedi
  • 699
  • 7
  • 10
0

Yes, when you retrieve this http-status in server response you will retrieve also response.body with error message which describes a reason this response. Could you check him?

WebDev
  • 256
  • 1
  • 3
  • I have exactly the same problem and the body shows "Unexpected Signature". I'm generating signature exactly as mentioned [here](http://billatnapier.com/security01.aspx) in HMAC-SHA-1 section. – Salman Riaz May 09 '14 at 08:47
  • I've fixed it, the only problem was while generating signature the list of parameters were not sorted alphabetically. – Salman Riaz May 09 '14 at 12:00
0

//Use Restshrap

 public static string token()
    {
        Applicationdetail obj = new Applicationdetail();
        string application_id = obj.application_id.ToString();
        string auth_key = obj.auth_key;
        string timestamp = Timestamp();
        string auth_secret = obj.secretkey;

        string postData = "application_id=" + application_id;
        postData += "&auth_key=" + auth_key;
        Random rand = new Random();
        postData += "&nonce=" + rand.Next(1000, 9999);
        postData += "&timestamp=" + timestamp;
        string signature = Hash(postData, auth_secret);
        postData += "&signature=" + signature;
        RestSharp.RestClient client = new                  RestSharp.RestClient("https://api.quickblox.com/session.json?"+ postData);
        RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
        request.AddHeader("QuickBlox-REST-API-Version", " 0.1.0");        
        var result = client.Execute(request);
        if (result != null && !string.IsNullOrEmpty(result.Content))
        {
            sessionRootObject tokenobj = 
             JsonConvert.DeserializeObject<sessionRootObject>
             (result.Content);
            return tokenobj.session.token;
        }
        else
        {
            return "";
        }

    }    

// add class

 public class Session
    {
    public int application_id { get; set; }
    public DateTime created_at { get; set; }
    public int id { get; set; }
    public int nonce { get; set; }
    public string token { get; set; }
    public int ts { get; set; }
    public DateTime updated_at { get; set; }
    public int user_id { get; set; }
    public string _id { get; set; }
}
public class sessionRootObject
{
    public Session session { get; set; }
}

  public class Applicationdetail
   {
    public int application_id { get {
            return add appid;
        } }
    public string auth_key { get { return "enter auth key"; } }
    public string secretkey { get { return "enter secretkey"; } }

}