2014-01-17 1 views
0

Я пытаюсь получить доступ к моему приложению QuickBlox и получить токен с помощью REST API.Получение токена с Quickblox в C#

Мой код выглядит следующим образом: http://pastebin.com/rp2KLMp2

Запрос выглядит следующим образом (чувствительная информация удалена): application_id = хххх & auth_key = XXXXXXXXXX & нонс = 2851 & метка времени = 1389951758 & подпись = D481F13E87F47D4C17697EF9D2C8E25777E09079

Я получаю сообщение об ошибке: Удаленный сервер возвратил ошибку: (422) Непроцессная организация

В чем может быть проблема?

ответ

0

Да, когда вы получите этот http-статус в ответе сервера, вы также получите сообщение response.body с сообщением об ошибке, которое описывает причину этого ответа. Не могли бы вы его проверить?

+0

У меня точно такая же проблема, и тело показывает "Неожиданный Подпись". Я создаю подпись точно так же, как упоминалось [здесь] (http://billatnapier.com/security01.aspx) в разделе HMAC-SHA-1. –

+0

Я исправил это, единственная проблема заключалась в создании подписи, список параметров не отсортирован в алфавитном порядке. –

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"]); 

    } 
0

// Использование 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 ""; 
     } 

    }  

// добавить класс

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"; } } 

}